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