c5a923531493c052c2ad05f9ae629474f252e557
[jalview.git] / src / jalview / gui / SequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.io.*;
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25
26 import javax.swing.*;
27
28 import MCview.*;
29 import jalview.datamodel.*;
30 import jalview.datamodel.xdb.embl.*;
31 import java.io.File;
32 import jalview.io.*;
33 import jalview.ws.DBRefFetcher;
34 import jalview.ws.ebi.EBIFetchClient;
35 import jalview.ws.seqfetcher.ASequenceFetcher;
36 import jalview.ws.seqfetcher.DbSourceProxy;
37
38 import java.awt.Rectangle;
39 import java.awt.BorderLayout;
40 import java.awt.Dimension;
41
42 public class SequenceFetcher extends JPanel implements Runnable
43 {
44   // ASequenceFetcher sfetch;
45   JInternalFrame frame;
46
47   IProgressIndicator guiWindow;
48
49   AlignFrame alignFrame;
50
51   StringBuffer result;
52
53   final String noDbSelected = "-- Select Database --";
54
55   Hashtable sources = new Hashtable();
56
57   private static jalview.ws.SequenceFetcher sfetch = null;
58
59   private static String dasRegistry = null;
60   private static boolean _initingFetcher=false;
61   private static Thread initingThread=null;
62   /**
63    * Blocking method that initialises and returns the shared instance of the
64    * SequenceFetcher client
65    * 
66    * @param guiWindow
67    *          - where the initialisation delay message should be shown
68    * @return the singleton instance of the sequence fetcher client
69    */
70   public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
71           final IProgressIndicator guiWindow)
72   {
73     if (_initingFetcher && initingThread!=null && initingThread.isAlive())
74     {
75       if (guiWindow != null)
76       {
77         guiWindow.setProgressBar("Waiting for Sequence Database Fetchers to initialise",
78                 Thread.currentThread().hashCode());
79       }
80       // initting happening on another thread - so wait around to see if it finishes.
81       while (_initingFetcher && initingThread!=null && initingThread.isAlive())
82       {
83         try {Thread.sleep(10);} catch (Exception e){};
84       }
85       if (guiWindow != null)
86       {
87         guiWindow.setProgressBar("Waiting for Sequence Database Fetchers to initialise",
88                 Thread.currentThread().hashCode());
89       }
90     }
91     if (sfetch == null
92             || dasRegistry != DasSourceBrowser.getDasRegistryURL())
93     {
94       _initingFetcher=true;
95       initingThread=Thread.currentThread();
96       /**
97        * give a visual indication that sequence fetcher construction is occuring
98        */
99       if (guiWindow != null)
100       {
101         guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
102                 Thread.currentThread().hashCode());
103       }
104       dasRegistry = DasSourceBrowser.getDasRegistryURL();
105       jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
106       if (guiWindow != null)
107       {
108         guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
109                 initingThread.hashCode());
110       }
111       sfetch = sf;
112       _initingFetcher=false;
113       initingThread=null;
114     }
115     return sfetch;
116   }
117
118   public SequenceFetcher(IProgressIndicator guiIndic)
119   {
120     final IProgressIndicator guiWindow = guiIndic;
121     final SequenceFetcher us = this;
122     // launch initialiser thread
123     Thread sf = new Thread(new Runnable()
124     {
125
126       public void run()
127       {
128         if (getSequenceFetcherSingleton(guiWindow) != null)
129         {
130           us.initGui(guiWindow);
131         }
132         else
133         {
134           javax.swing.SwingUtilities.invokeLater(new Runnable()
135           {
136             public void run()
137             {
138               JOptionPane
139                       .showInternalMessageDialog(
140                               Desktop.desktop,
141                               "Could not create the sequence fetcher client. Check error logs for details.",
142                               "Couldn't create SequenceFetcher",
143                               JOptionPane.ERROR_MESSAGE);
144             }
145           });
146
147           // raise warning dialog
148         }
149       }
150     });
151     sf.start();
152   }
153
154   /**
155    * called by thread spawned by constructor
156    * 
157    * @param guiWindow
158    */
159   private void initGui(IProgressIndicator guiWindow)
160   {
161     this.guiWindow = guiWindow;
162     if (guiWindow instanceof AlignFrame)
163     {
164       alignFrame = (AlignFrame) guiWindow;
165     }
166
167     database.addItem(noDbSelected);
168     /*
169      * Dynamically generated database list will need a translation function from
170      * internal source to externally distinct names. UNIPROT and UP_NAME are
171      * identical DB sources, and should be collapsed.
172      */
173
174     String dbs[] = sfetch.getOrderedSupportedSources();
175     for (int i = 0; i < dbs.length; i++)
176     {
177       if (!sources.containsValue(dbs[i]))
178       {
179         String name = sfetch.getSourceProxy(dbs[i]).getDbName();
180         // duplicate source names are thrown away, here.
181         if (!sources.containsKey(name))
182         {
183           database.addItem(name);
184         }
185         // overwrite with latest version of the retriever for this source
186         sources.put(name, dbs[i]);
187       }
188     }
189     try
190     {
191       jbInit();
192     } catch (Exception ex)
193     {
194       ex.printStackTrace();
195     }
196
197     frame = new JInternalFrame();
198     frame.setContentPane(this);
199     if (new jalview.util.Platform().isAMac())
200     {
201       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
202     }
203     else
204     {
205       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
206     }
207   }
208
209   private String getFrameTitle()
210   {
211     return ((alignFrame == null) ? "New " : "Additional ")
212             + "Sequence Fetcher";
213   }
214
215   private void jbInit() throws Exception
216   {
217     this.setLayout(borderLayout2);
218
219     database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
220     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
221     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
222     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
223     jLabel1
224             .setText("Separate multiple accession ids with semi colon \";\"");
225     ok.setText("OK");
226     ok.addActionListener(new ActionListener()
227     {
228       public void actionPerformed(ActionEvent e)
229       {
230         ok_actionPerformed();
231       }
232     });
233     clear.setText("Clear");
234     clear.addActionListener(new ActionListener()
235     {
236       public void actionPerformed(ActionEvent e)
237       {
238         clear_actionPerformed();
239       }
240     });
241
242     example.setText("Example");
243     example.addActionListener(new ActionListener()
244     {
245       public void actionPerformed(ActionEvent e)
246       {
247         example_actionPerformed();
248       }
249     });
250     close.setText("Close");
251     close.addActionListener(new ActionListener()
252     {
253       public void actionPerformed(ActionEvent e)
254       {
255         close_actionPerformed(e);
256       }
257     });
258     textArea.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
259     textArea.setLineWrap(true);
260     textArea.addKeyListener(new KeyAdapter()
261     {
262       public void keyPressed(KeyEvent e)
263       {
264         if (e.getKeyCode() == KeyEvent.VK_ENTER)
265           ok_actionPerformed();
266       }
267     });
268     jPanel3.setLayout(borderLayout1);
269     borderLayout1.setVgap(5);
270     jPanel1.add(ok);
271     jPanel1.add(example);
272     jPanel1.add(clear);
273     jPanel1.add(close);
274     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
275     jPanel2.setLayout(borderLayout3);
276
277     database.addActionListener(new ActionListener()
278     {
279
280       public void actionPerformed(ActionEvent e)
281       {
282         DbSourceProxy db = null;
283         try
284         {
285           db = sfetch.getSourceProxy((String) sources.get(database
286                   .getSelectedItem()));
287           dbeg.setText("Example query: " + db.getTestQuery());
288         } catch (Exception ex)
289         {
290           dbeg.setText("");
291         }
292         jPanel2.repaint();
293       }
294     });
295     dbeg.setText("");
296     jPanel2.add(database, java.awt.BorderLayout.NORTH);
297     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
298     jPanel2.add(jLabel1, java.awt.BorderLayout.SOUTH);
299     // jPanel2.setPreferredSize(new Dimension())
300     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
301     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
302     this.add(jPanel3, java.awt.BorderLayout.CENTER);
303     this.add(jPanel2, java.awt.BorderLayout.NORTH);
304     jScrollPane1.getViewport().add(textArea);
305
306   }
307
308   protected void example_actionPerformed()
309   {
310     DbSourceProxy db = null;
311     try
312     {
313       db = sfetch.getSourceProxy((String) sources.get(database
314               .getSelectedItem()));
315       textArea.setText(db.getTestQuery());
316     } catch (Exception ex)
317     {
318     }
319     jPanel3.repaint();
320   }
321
322   protected void clear_actionPerformed()
323   {
324     textArea.setText("");
325     jPanel3.repaint();
326   }
327
328   JLabel dbeg = new JLabel();
329
330   JComboBox database = new JComboBox();
331
332   JLabel jLabel1 = new JLabel();
333
334   JButton ok = new JButton();
335
336   JButton clear = new JButton();
337
338   JButton example = new JButton();
339
340   JButton close = new JButton();
341
342   JPanel jPanel1 = new JPanel();
343
344   JTextArea textArea = new JTextArea();
345
346   JScrollPane jScrollPane1 = new JScrollPane();
347
348   JPanel jPanel2 = new JPanel();
349
350   JPanel jPanel3 = new JPanel();
351
352   JPanel jPanel4 = new JPanel();
353
354   BorderLayout borderLayout1 = new BorderLayout();
355
356   BorderLayout borderLayout2 = new BorderLayout();
357
358   BorderLayout borderLayout3 = new BorderLayout();
359
360   public void close_actionPerformed(ActionEvent e)
361   {
362     try
363     {
364       frame.setClosed(true);
365     } catch (Exception ex)
366     {
367     }
368   }
369
370   public void ok_actionPerformed()
371   {
372     database.setEnabled(false);
373     textArea.setEnabled(false);
374     ok.setEnabled(false);
375     close.setEnabled(false);
376
377     Thread worker = new Thread(this);
378     worker.start();
379   }
380
381   private void resetDialog()
382   {
383     database.setEnabled(true);
384     textArea.setEnabled(true);
385     ok.setEnabled(true);
386     close.setEnabled(true);
387   }
388
389   public void run()
390   {
391     String error = "";
392     if (database.getSelectedItem().equals(noDbSelected))
393     {
394       error += "Please select the source database\n";
395     }
396     // TODO: make this transformation optional and configurable
397     com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex(
398             "(\\s|[,; ])+", ";"); // \\s+", "");
399     textArea.setText(empty.replaceAll(textArea.getText()));
400     // see if there's anthing to search with
401     if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
402             .getText()))
403     {
404       error += "Please enter a (semi-colon separated list of) database id(s)";
405     }
406     if (error.length() > 0)
407     {
408       showErrorMessage(error);
409       resetDialog();
410       return;
411     }
412     AlignmentI aresult = null;
413     Object source = database.getSelectedItem();
414     Enumeration en = new StringTokenizer(textArea.getText(), ";");
415     try
416     {
417       guiWindow.setProgressBar("Fetching Sequences from "
418               + database.getSelectedItem(), Thread.currentThread()
419               .hashCode());
420       DbSourceProxy proxy = sfetch.getSourceProxy((String) sources
421               .get(source));
422       if (proxy.getAccessionSeparator() == null)
423       {
424         while (en.hasMoreElements())
425         {
426           String item = (String) en.nextElement();
427           try
428           {
429             if (aresult != null)
430             {
431               try
432               {
433                 // give the server a chance to breathe
434                 Thread.sleep(5);
435               } catch (Exception e)
436               {
437                 //
438               }
439
440             }
441
442             AlignmentI indres = null;
443             try
444             {
445               indres = proxy.getSequenceRecords(item);
446             } catch (OutOfMemoryError oome)
447             {
448               new OOMWarning(
449                       "fetching " + item + " from "
450                               + database.getSelectedItem(),oome,
451                       this);
452             }
453             if (indres != null)
454             {
455               if (aresult == null)
456               {
457                 aresult = indres;
458               }
459               else
460               {
461                 aresult.append(indres);
462               }
463             }
464           } catch (Exception e)
465           {
466             jalview.bin.Cache.log.info("Error retrieving " + item
467                     + " from " + source, e);
468           }
469         }
470       }
471       else
472       {
473         StringBuffer multiacc = new StringBuffer();
474         while (en.hasMoreElements())
475         {
476           multiacc.append(en.nextElement());
477           if (en.hasMoreElements())
478           {
479             multiacc.append(proxy.getAccessionSeparator());
480           }
481         }
482         try
483         {
484           aresult = proxy.getSequenceRecords(multiacc.toString());
485         } catch (OutOfMemoryError oome)
486         {
487           new OOMWarning(
488                   "fetching " + multiacc + " from "
489                           + database.getSelectedItem(),oome,
490                   this);
491         }
492         
493         
494       }
495
496     } catch (Exception e)
497     {
498       showErrorMessage("Error retrieving " + textArea.getText() + " from "
499               + database.getSelectedItem());
500       // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
501       System.err.println("Retrieval failed for source ='"
502               + database.getSelectedItem() + "' and query\n'"
503               + textArea.getText() + "'\n");
504       e.printStackTrace();
505     } catch (OutOfMemoryError e)
506     {
507       // resets dialog box - so we don't use OOMwarning here.
508       showErrorMessage("Out of Memory when retrieving "
509               + textArea.getText()
510               + " from "
511               + database.getSelectedItem()
512               + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
513       e.printStackTrace();
514     } catch (Error e)
515     {
516       showErrorMessage("Serious Error retrieving " + textArea.getText()
517               + " from " + database.getSelectedItem());
518       e.printStackTrace();
519     }
520     if (aresult != null)
521     {
522       parseResult(aresult, null, null);
523     }
524     // only remove visual delay after we finished parsing.
525     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
526     resetDialog();
527   }
528
529   /*
530    * result = new StringBuffer(); if
531    * (database.getSelectedItem().equals("Uniprot")) {
532    * getUniprotFile(textArea.getText()); } else if
533    * (database.getSelectedItem().equals("EMBL") ||
534    * database.getSelectedItem().equals("EMBLCDS")) { String DBRefSource =
535    * database.getSelectedItem().equals("EMBLCDS") ?
536    * jalview.datamodel.DBRefSource.EMBLCDS : jalview.datamodel.DBRefSource.EMBL;
537    * 
538    * StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
539    * SequenceI[] seqs = null; while(st.hasMoreTokens()) { EBIFetchClient dbFetch
540    * = new EBIFetchClient(); String qry =
541    * database.getSelectedItem().toString().toLowerCase( ) + ":" +
542    * st.nextToken(); File reply = dbFetch.fetchDataAsFile( qry, "emblxml",null);
543    * 
544    * jalview.datamodel.xdb.embl.EmblFile efile=null; if (reply != null &&
545    * reply.exists()) { efile =
546    * jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply); } if (efile!=null)
547    * { for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) { EmblEntry
548    * entry = (EmblEntry) i.next(); SequenceI[] seqparts =
549    * entry.getSequences(false,true, DBRefSource); if (seqparts!=null) {
550    * SequenceI[] newseqs = null; int si=0; if (seqs==null) { newseqs = new
551    * SequenceI[seqparts.length]; } else { newseqs = new
552    * SequenceI[seqs.length+seqparts.length];
553    * 
554    * for (;si<seqs.length; si++) { newseqs[si] = seqs[si]; seqs[si] = null; } }
555    * for (int j=0;j<seqparts.length; si++, j++) { newseqs[si] =
556    * seqparts[j].deriveSequence(); // place DBReferences on dataset and refer }
557    * seqs=newseqs; } } } else { result.append("# no response for "+qry); } } if
558    * (seqs!=null && seqs.length>0) { if (parseResult(new Alignment(seqs), null,
559    * null)!=null) { result.append("# Successfully parsed the
560    * "+database.getSelectedItem()+" Queries into an Alignment"); } } } else if
561    * (database.getSelectedItem().equals("PDB")) { StringTokenizer qset = new
562    * StringTokenizer(textArea.getText(), ";"); String query; SequenceI[] seqs =
563    * null; while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null)) {
564    * SequenceI[] seqparts = getPDBFile(query.toUpperCase()); if (seqparts !=
565    * null) { if (seqs == null) { seqs = seqparts; } else { SequenceI[] newseqs =
566    * new SequenceI[seqs.length+seqparts.length]; int i=0; for (; i <
567    * seqs.length; i++) { newseqs[i] = seqs[i]; seqs[i] = null; } for (int
568    * j=0;j<seqparts.length; i++, j++) { newseqs[i] = seqparts[j]; }
569    * seqs=newseqs; } result.append("# Success for "+query.toUpperCase()+"\n"); }
570    * } if (seqs != null && seqs.length > 0) { if (parseResult(new
571    * Alignment(seqs), null, null)!=null) { result.append( "# Successfully parsed
572    * the PDB File Queries into an
573    * Alignment"); } } } else if( database.getSelectedItem().equals("PFAM")) {
574    * try { result.append(new FastaFile(
575    * "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc=" +
576    * textArea.getText().toUpperCase(), "URL").print() );
577    * 
578    * if(result.length()>0) { parseResult( result.toString(),
579    * textArea.getText().toUpperCase() ); } } catch (java.io.IOException ex) {
580    * result = null; } }
581    * 
582    * if (result == null || result.length() == 0) { showErrorMessage("Error
583    * retrieving " + textArea.getText() + " from " + database.getSelectedItem());
584    * }
585    * 
586    * resetDialog(); return; }
587    * 
588    * void getUniprotFile(String id) { EBIFetchClient ebi = new EBIFetchClient();
589    * File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
590    * 
591    * DBRefFetcher dbref = new DBRefFetcher(); Vector entries =
592    * dbref.getUniprotEntries(file);
593    * 
594    * if (entries != null) { //First, make the new sequences Enumeration en =
595    * entries.elements(); while (en.hasMoreElements()) { UniprotEntry entry =
596    * (UniprotEntry) en.nextElement();
597    * 
598    * StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot"); Enumeration
599    * en2 = entry.getAccession().elements(); while (en2.hasMoreElements()) {
600    * name.append("|"); name.append(en2.nextElement()); } en2 =
601    * entry.getName().elements(); while (en2.hasMoreElements()) {
602    * name.append("|"); name.append(en2.nextElement()); }
603    * 
604    * if (entry.getProtein() != null) { name.append(" " +
605    * entry.getProtein().getName().elementAt(0)); }
606    * 
607    * result.append(name + "\n" + entry.getUniprotSequence().getContent() +
608    * "\n"); }
609    * 
610    * //Then read in the features and apply them to the dataset Alignment al =
611    * parseResult(result.toString(), null); for (int i = 0; i < entries.size();
612    * i++) { UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
613    * Enumeration e = entry.getDbReference().elements(); Vector onlyPdbEntries =
614    * new Vector(); while (e.hasMoreElements()) { PDBEntry pdb = (PDBEntry)
615    * e.nextElement(); if (!pdb.getType().equals("PDB")) { continue; }
616    * 
617    * onlyPdbEntries.addElement(pdb); }
618    * 
619    * Enumeration en2 = entry.getAccession().elements(); while
620    * (en2.hasMoreElements()) {
621    * al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
622    * DBRefSource.UNIPROT, "0", en2.nextElement().toString())); }
623    * 
624    * 
625    * 
626    * 
627    * al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries); if
628    * (entry.getFeature() != null) { e = entry.getFeature().elements(); while
629    * (e.hasMoreElements()) { SequenceFeature sf = (SequenceFeature)
630    * e.nextElement(); sf.setFeatureGroup("Uniprot");
631    * al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf ); } } } }
632    * }
633    * 
634    * SequenceI[] getPDBFile(String id) { Vector result = new Vector(); String
635    * chain = null; if (id.indexOf(":") > -1) { chain =
636    * id.substring(id.indexOf(":") + 1); id = id.substring(0, id.indexOf(":")); }
637    * 
638    * EBIFetchClient ebi = new EBIFetchClient(); String file =
639    * ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw"). getAbsolutePath(); if (file
640    * == null) { return null; } try { PDBfile pdbfile = new PDBfile(file,
641    * jalview.io.AppletFormatAdapter.FILE); for (int i = 0; i <
642    * pdbfile.chains.size(); i++) { if (chain == null || ( (PDBChain)
643    * pdbfile.chains.elementAt(i)).id. toUpperCase().equals(chain)) { PDBChain
644    * pdbchain = (PDBChain) pdbfile.chains.elementAt(i); // Get the Chain's
645    * Sequence - who's dataset includes any special features added from the PDB
646    * file SequenceI sq = pdbchain.sequence; // Specially formatted name for the
647    * PDB chain sequences retrieved from the PDB
648    * sq.setName("PDB|"+id+"|"+sq.getName()); // Might need to add more metadata
649    * to the PDBEntry object // like below /* PDBEntry entry = new PDBEntry(); //
650    * Construct the PDBEntry entry.setId(id); if (entry.getProperty() == null)
651    * entry.setProperty(new Hashtable()); entry.getProperty().put("chains",
652    * pdbchain.id + "=" + sq.getStart() + "-" + sq.getEnd());
653    * sq.getDatasetSequence().addPDBId(entry); // Add PDB DB Refs // We make a
654    * DBRefEtntry because we have obtained the PDB file from a verifiable source
655    * // JBPNote - PDB DBRefEntry should also carry the chain and mapping
656    * information DBRefEntry dbentry = new
657    * DBRefEntry(jalview.datamodel.DBRefSource.PDB, "0", id + pdbchain.id);
658    * sq.addDBRef(dbentry); // and add seuqence to the retrieved set
659    * result.addElement(sq.deriveSequence()); } }
660    * 
661    * if (result.size() < 1) { throw new Exception("WsDBFetch for PDB id resulted
662    * in zero result size"); } } catch (Exception ex) // Problem parsing PDB file
663    * { jalview.bin.Cache.log.warn("Exception when retrieving " +
664    * textArea.getText() + " from " + database.getSelectedItem(), ex); return
665    * null; }
666    * 
667    * 
668    * SequenceI[] results = new SequenceI[result.size()]; for (int i = 0, j =
669    * result.size(); i < j; i++) { results[i] = (SequenceI) result.elementAt(i);
670    * result.setElementAt(null,i); } return results; }
671    */
672   AlignmentI parseResult(String result, String title)
673   {
674     String format = new IdentifyFile().Identify(result, "Paste");
675     Alignment sequences = null;
676     if (FormatAdapter.isValidFormat(format))
677     {
678       sequences = null;
679       try
680       {
681         sequences = new FormatAdapter().readFile(result.toString(),
682                 "Paste", format);
683       } catch (Exception ex)
684       {
685       }
686
687       if (sequences != null)
688       {
689         return parseResult(sequences, title, format);
690       }
691     }
692     else
693     {
694       showErrorMessage("Error retrieving " + textArea.getText() + " from "
695               + database.getSelectedItem());
696     }
697
698     return null;
699   }
700
701   AlignmentI parseResult(AlignmentI al, String title,
702           String currentFileFormat)
703   {
704
705     if (al != null && al.getHeight() > 0)
706     {
707       if (alignFrame == null)
708       {
709         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
710                 AlignFrame.DEFAULT_HEIGHT);
711         if (currentFileFormat != null)
712         {
713           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
714           // FORMAT FOR
715           // NON-FormatAdapter Sourced
716           // Alignments?
717         }
718
719         if (title == null)
720         {
721           title = "Retrieved from " + database.getSelectedItem();
722         }
723         SequenceFeature[] sfs = null;
724         for (Enumeration sq = al.getSequences().elements(); sq
725                 .hasMoreElements();)
726         {
727           if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
728                   .getSequenceFeatures()) != null)
729           {
730             if (sfs.length > 0)
731             {
732               af.setShowSeqFeatures(true);
733               break;
734             }
735           }
736
737         }
738         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
739                 AlignFrame.DEFAULT_HEIGHT);
740
741         af.statusBar.setText("Successfully pasted alignment file");
742
743         try
744         {
745           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
746                   false));
747         } catch (Exception ex)
748         {
749         }
750       }
751       else
752       {
753         for (int i = 0; i < al.getHeight(); i++)
754         {
755           alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this
756           // also
757           // creates
758           // dataset
759           // sequence
760           // entries
761         }
762         alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment
763                 .getHeight());
764         alignFrame.viewport.alignment.getWidth();
765         alignFrame.viewport.firePropertyChange("alignment", null,
766                 alignFrame.viewport.getAlignment().getSequences());
767       }
768     }
769     return al;
770   }
771
772   void showErrorMessage(final String error)
773   {
774     resetDialog();
775     javax.swing.SwingUtilities.invokeLater(new Runnable()
776     {
777       public void run()
778       {
779         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
780                 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);
781       }
782     });
783   }
784 }