update author list in license for (JAL-826)
[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, J Engelhardt, LM Lui, 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                 Thread.currentThread().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(JvSwingUtils.getLabelFont());
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(JvSwingUtils.getLabelFont());
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     ArrayList<String> aresultq=new ArrayList<String>();
448     ArrayList<AlignmentI> aresult = new ArrayList<AlignmentI>();
449     Object source = database.getSelectedItem();
450     Enumeration en = new StringTokenizer(textArea.getText(), ";");
451     boolean isAliSource=false;
452     try
453     {
454       guiWindow.setProgressBar(
455               "Fetching Sequences from " + database.getSelectedItem(),
456               Thread.currentThread().hashCode());
457       DbSourceProxy proxy = sfetch.getSourceProxy((String) sources
458               .get(source));
459       isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
460       if (proxy.getAccessionSeparator() == null)
461       {
462         while (en.hasMoreElements())
463         {
464           String item = (String) en.nextElement();
465           try
466           {
467             if (aresult != null)
468             {
469               try
470               {
471                 // give the server a chance to breathe
472                 Thread.sleep(5);
473               } catch (Exception e)
474               {
475                 //
476               }
477
478             }
479
480             AlignmentI indres = null;
481             try
482             {
483               indres = proxy.getSequenceRecords(item);
484             } catch (OutOfMemoryError oome)
485             {
486               new OOMWarning("fetching " + item + " from "
487                       + database.getSelectedItem(), oome, this);
488             }
489             if (indres != null)
490             {
491               aresultq.add(item);
492               aresult.add(indres);
493             }
494           } catch (Exception e)
495           {
496             jalview.bin.Cache.log.info("Error retrieving " + item
497                     + " from " + source, e);
498           }
499         }
500       }
501       else
502       {
503         StringBuffer multiacc = new StringBuffer();
504         while (en.hasMoreElements())
505         {
506           multiacc.append(en.nextElement());
507           if (en.hasMoreElements())
508           {
509             multiacc.append(proxy.getAccessionSeparator());
510           }
511         }
512         try
513         {
514           aresultq.add(multiacc.toString());
515           aresult.add(proxy.getSequenceRecords(multiacc.toString()));
516         } catch (OutOfMemoryError oome)
517         {
518           new OOMWarning("fetching " + multiacc + " from "
519                   + database.getSelectedItem(), oome, this);
520         }
521
522       }
523
524     } catch (Exception e)
525     {
526       showErrorMessage("Error retrieving " + textArea.getText() + " from "
527               + database.getSelectedItem());
528       // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
529       System.err.println("Retrieval failed for source ='"
530               + database.getSelectedItem() + "' and query\n'"
531               + textArea.getText() + "'\n");
532       e.printStackTrace();
533     } catch (OutOfMemoryError e)
534     {
535       // resets dialog box - so we don't use OOMwarning here.
536       showErrorMessage("Out of Memory when retrieving "
537               + textArea.getText()
538               + " from "
539               + database.getSelectedItem()
540               + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
541       e.printStackTrace();
542     } catch (Error e)
543     {
544       showErrorMessage("Serious Error retrieving " + textArea.getText()
545               + " from " + database.getSelectedItem());
546       e.printStackTrace();
547     }
548     if (aresult != null && aresult.size()>0)
549     {
550       AlignmentI ar=null;
551       if (isAliSource) {
552         // new window for each result
553         while (aresult.size()>0)
554         {
555           parseResult(aresult.remove(0), aresultq.remove(0)+" "+getDefaultRetrievalTitle(), null);
556         }
557       } else {
558         // concatenate all results in one window
559         while (aresult.size()>0)
560         {
561           if (ar==null) { ar = aresult.remove(0);}
562           else { ar.append(aresult.remove(0)); };
563         }
564         parseResult(ar, null, null);
565       } 
566     }
567     // only remove visual delay after we finished parsing.
568     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
569     resetDialog();
570   }
571
572   /*
573    * result = new StringBuffer(); if
574    * (database.getSelectedItem().equals("Uniprot")) {
575    * getUniprotFile(textArea.getText()); } else if
576    * (database.getSelectedItem().equals("EMBL") ||
577    * database.getSelectedItem().equals("EMBLCDS")) { String DBRefSource =
578    * database.getSelectedItem().equals("EMBLCDS") ?
579    * jalview.datamodel.DBRefSource.EMBLCDS : jalview.datamodel.DBRefSource.EMBL;
580    * 
581    * StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
582    * SequenceI[] seqs = null; while(st.hasMoreTokens()) { EBIFetchClient dbFetch
583    * = new EBIFetchClient(); String qry =
584    * database.getSelectedItem().toString().toLowerCase( ) + ":" +
585    * st.nextToken(); File reply = dbFetch.fetchDataAsFile( qry, "emblxml",null);
586    * 
587    * jalview.datamodel.xdb.embl.EmblFile efile=null; if (reply != null &&
588    * reply.exists()) { efile =
589    * jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply); } if (efile!=null)
590    * { for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) { EmblEntry
591    * entry = (EmblEntry) i.next(); SequenceI[] seqparts =
592    * entry.getSequences(false,true, DBRefSource); if (seqparts!=null) {
593    * SequenceI[] newseqs = null; int si=0; if (seqs==null) { newseqs = new
594    * SequenceI[seqparts.length]; } else { newseqs = new
595    * SequenceI[seqs.length+seqparts.length];
596    * 
597    * for (;si<seqs.length; si++) { newseqs[si] = seqs[si]; seqs[si] = null; } }
598    * for (int j=0;j<seqparts.length; si++, j++) { newseqs[si] =
599    * seqparts[j].deriveSequence(); // place DBReferences on dataset and refer }
600    * seqs=newseqs; } } } else { result.append("# no response for "+qry); } } if
601    * (seqs!=null && seqs.length>0) { if (parseResult(new Alignment(seqs), null,
602    * null)!=null) { result.append("# Successfully parsed the
603    * "+database.getSelectedItem()+" Queries into an Alignment"); } } } else if
604    * (database.getSelectedItem().equals("PDB")) { StringTokenizer qset = new
605    * StringTokenizer(textArea.getText(), ";"); String query; SequenceI[] seqs =
606    * null; while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null)) {
607    * SequenceI[] seqparts = getPDBFile(query.toUpperCase()); if (seqparts !=
608    * null) { if (seqs == null) { seqs = seqparts; } else { SequenceI[] newseqs =
609    * new SequenceI[seqs.length+seqparts.length]; int i=0; for (; i <
610    * seqs.length; i++) { newseqs[i] = seqs[i]; seqs[i] = null; } for (int
611    * j=0;j<seqparts.length; i++, j++) { newseqs[i] = seqparts[j]; }
612    * seqs=newseqs; } result.append("# Success for "+query.toUpperCase()+"\n"); }
613    * } if (seqs != null && seqs.length > 0) { if (parseResult(new
614    * Alignment(seqs), null, null)!=null) { result.append( "# Successfully parsed
615    * the PDB File Queries into an
616    * Alignment"); } } } else if( database.getSelectedItem().equals("PFAM")) {
617    * try { result.append(new FastaFile(
618    * "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc=" +
619    * textArea.getText().toUpperCase(), "URL").print() );
620    * 
621    * if(result.length()>0) { parseResult( result.toString(),
622    * textArea.getText().toUpperCase() ); } } catch (java.io.IOException ex) {
623    * result = null; } }
624    * 
625    * if (result == null || result.length() == 0) { showErrorMessage("Error
626    * retrieving " + textArea.getText() + " from " + database.getSelectedItem());
627    * }
628    * 
629    * resetDialog(); return; }
630    * 
631    * void getUniprotFile(String id) { EBIFetchClient ebi = new EBIFetchClient();
632    * File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
633    * 
634    * DBRefFetcher dbref = new DBRefFetcher(); Vector entries =
635    * dbref.getUniprotEntries(file);
636    * 
637    * if (entries != null) { //First, make the new sequences Enumeration en =
638    * entries.elements(); while (en.hasMoreElements()) { UniprotEntry entry =
639    * (UniprotEntry) en.nextElement();
640    * 
641    * StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot"); Enumeration
642    * en2 = entry.getAccession().elements(); while (en2.hasMoreElements()) {
643    * name.append("|"); name.append(en2.nextElement()); } en2 =
644    * entry.getName().elements(); while (en2.hasMoreElements()) {
645    * name.append("|"); name.append(en2.nextElement()); }
646    * 
647    * if (entry.getProtein() != null) { name.append(" " +
648    * entry.getProtein().getName().elementAt(0)); }
649    * 
650    * result.append(name + "\n" + entry.getUniprotSequence().getContent() +
651    * "\n"); }
652    * 
653    * //Then read in the features and apply them to the dataset Alignment al =
654    * parseResult(result.toString(), null); for (int i = 0; i < entries.size();
655    * i++) { UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
656    * Enumeration e = entry.getDbReference().elements(); Vector onlyPdbEntries =
657    * new Vector(); while (e.hasMoreElements()) { PDBEntry pdb = (PDBEntry)
658    * e.nextElement(); if (!pdb.getType().equals("PDB")) { continue; }
659    * 
660    * onlyPdbEntries.addElement(pdb); }
661    * 
662    * Enumeration en2 = entry.getAccession().elements(); while
663    * (en2.hasMoreElements()) {
664    * al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
665    * DBRefSource.UNIPROT, "0", en2.nextElement().toString())); }
666    * 
667    * 
668    * 
669    * 
670    * al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries); if
671    * (entry.getFeature() != null) { e = entry.getFeature().elements(); while
672    * (e.hasMoreElements()) { SequenceFeature sf = (SequenceFeature)
673    * e.nextElement(); sf.setFeatureGroup("Uniprot");
674    * al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf ); } } } }
675    * }
676    * 
677    * SequenceI[] getPDBFile(String id) { Vector result = new Vector(); String
678    * chain = null; if (id.indexOf(":") > -1) { chain =
679    * id.substring(id.indexOf(":") + 1); id = id.substring(0, id.indexOf(":")); }
680    * 
681    * EBIFetchClient ebi = new EBIFetchClient(); String file =
682    * ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw"). getAbsolutePath(); if (file
683    * == null) { return null; } try { PDBfile pdbfile = new PDBfile(file,
684    * jalview.io.AppletFormatAdapter.FILE); for (int i = 0; i <
685    * pdbfile.chains.size(); i++) { if (chain == null || ( (PDBChain)
686    * pdbfile.chains.elementAt(i)).id. toUpperCase().equals(chain)) { PDBChain
687    * pdbchain = (PDBChain) pdbfile.chains.elementAt(i); // Get the Chain's
688    * Sequence - who's dataset includes any special features added from the PDB
689    * file SequenceI sq = pdbchain.sequence; // Specially formatted name for the
690    * PDB chain sequences retrieved from the PDB
691    * sq.setName("PDB|"+id+"|"+sq.getName()); // Might need to add more metadata
692    * to the PDBEntry object // like below /* PDBEntry entry = new PDBEntry(); //
693    * Construct the PDBEntry entry.setId(id); if (entry.getProperty() == null)
694    * entry.setProperty(new Hashtable()); entry.getProperty().put("chains",
695    * pdbchain.id + "=" + sq.getStart() + "-" + sq.getEnd());
696    * sq.getDatasetSequence().addPDBId(entry); // Add PDB DB Refs // We make a
697    * DBRefEtntry because we have obtained the PDB file from a verifiable source
698    * // JBPNote - PDB DBRefEntry should also carry the chain and mapping
699    * information DBRefEntry dbentry = new
700    * DBRefEntry(jalview.datamodel.DBRefSource.PDB, "0", id + pdbchain.id);
701    * sq.addDBRef(dbentry); // and add seuqence to the retrieved set
702    * result.addElement(sq.deriveSequence()); } }
703    * 
704    * if (result.size() < 1) { throw new Exception("WsDBFetch for PDB id resulted
705    * in zero result size"); } } catch (Exception ex) // Problem parsing PDB file
706    * { jalview.bin.Cache.log.warn("Exception when retrieving " +
707    * textArea.getText() + " from " + database.getSelectedItem(), ex); return
708    * null; }
709    * 
710    * 
711    * SequenceI[] results = new SequenceI[result.size()]; for (int i = 0, j =
712    * result.size(); i < j; i++) { results[i] = (SequenceI) result.elementAt(i);
713    * result.setElementAt(null,i); } return results; }
714    */
715   AlignmentI parseResult(String result, String title)
716   {
717     String format = new IdentifyFile().Identify(result, "Paste");
718     Alignment sequences = null;
719     if (FormatAdapter.isValidFormat(format))
720     {
721       sequences = null;
722       try
723       {
724         sequences = new FormatAdapter().readFile(result.toString(),
725                 "Paste", format);
726       } catch (Exception ex)
727       {
728       }
729
730       if (sequences != null)
731       {
732         return parseResult(sequences, title, format);
733       }
734     }
735     else
736     {
737       showErrorMessage("Error retrieving " + textArea.getText() + " from "
738               + database.getSelectedItem());
739     }
740
741     return null;
742   }
743
744   /**
745    * 
746    * @return a standard title for any results retrieved using the currently selected source and settings
747    */
748   public String getDefaultRetrievalTitle() {
749     return "Retrieved from " + database.getSelectedItem();
750   }
751   AlignmentI parseResult(AlignmentI al, String title,
752           String currentFileFormat)
753   {
754
755     if (al != null && al.getHeight() > 0)
756     {
757       if (alignFrame == null)
758       {
759         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
760                 AlignFrame.DEFAULT_HEIGHT);
761         if (currentFileFormat != null)
762         {
763           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
764           // FORMAT FOR
765           // NON-FormatAdapter Sourced
766           // Alignments?
767         }
768
769         if (title == null)
770         {
771           title = getDefaultRetrievalTitle();
772         }
773         SequenceFeature[] sfs = null;
774         for (Enumeration sq = al.getSequences().elements(); sq
775                 .hasMoreElements();)
776         {
777           if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
778                   .getSequenceFeatures()) != null)
779           {
780             if (sfs.length > 0)
781             {
782               af.setShowSeqFeatures(true);
783               break;
784             }
785           }
786
787         }
788         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
789                 AlignFrame.DEFAULT_HEIGHT);
790
791         af.statusBar.setText("Successfully pasted alignment file");
792
793         try
794         {
795           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
796                   false));
797         } catch (Exception ex)
798         {
799         }
800       }
801       else
802       {
803         for (int i = 0; i < al.getHeight(); i++)
804         {
805           alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this
806           // also
807           // creates
808           // dataset
809           // sequence
810           // entries
811         }
812         alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment
813                 .getHeight());
814         alignFrame.viewport.alignment.getWidth();
815         alignFrame.viewport.firePropertyChange("alignment", null,
816                 alignFrame.viewport.getAlignment().getSequences());
817       }
818     }
819     return al;
820   }
821
822   void showErrorMessage(final String error)
823   {
824     resetDialog();
825     javax.swing.SwingUtilities.invokeLater(new Runnable()
826     {
827       public void run()
828       {
829         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
830                 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);
831       }
832     });
833   }
834 }