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