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