0ea13a22b7324d302ce4fc4c617f1c19701a79c7
[jalview.git] / src / jalview / gui / SequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.io.*;
22 import java.util.*;
23
24 import java.awt.*;
25 import java.awt.event.*;
26 import javax.swing.*;
27
28 import MCview.*;
29 import jalview.datamodel.*;
30 import jalview.datamodel.xdb.embl.*;
31 import jalview.analysis.*;
32 import java.io.File;
33 import jalview.io.*;
34
35 public class SequenceFetcher
36 extends JPanel implements Runnable
37 {
38   JInternalFrame frame;
39   AlignFrame alignFrame;
40   StringBuffer result;
41   final String noDbSelected = "-- Select Database --";
42   public SequenceFetcher(AlignFrame af)
43   {
44     alignFrame = af;
45     database.addItem(noDbSelected);
46     database.addItem("Uniprot");
47     database.addItem("EMBL");
48     database.addItem("EMBLCDS");
49     database.addItem("PDB");
50     database.addItem("PFAM");
51
52     try
53     {
54       jbInit();
55     }
56     catch (Exception ex)
57     {
58       ex.printStackTrace();
59     }
60
61     frame = new JInternalFrame();
62     frame.setContentPane(this);
63     if (System.getProperty("os.name").startsWith("Mac"))
64     {
65       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
66     }
67     else
68     {
69       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 125);
70     }
71   }
72
73   private String getFrameTitle()
74   {
75     return ( (alignFrame == null) ? "New " : "Additional ") +
76     "Sequence Fetcher";
77   }
78
79   private void jbInit()
80   throws Exception
81   {
82     this.setLayout(gridBagLayout1);
83
84     database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
85     database.setMinimumSize(new Dimension(160, 21));
86     database.setPreferredSize(new Dimension(160, 21));
87     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
88     jLabel1.setText(
89     "Separate multiple accession ids with semi colon \";\"");
90     ok.setText("OK");
91     ok.addActionListener(new ActionListener()
92     {
93       public void actionPerformed(ActionEvent e)
94       {
95         ok_actionPerformed(e);
96       }
97     });
98     close.setText("Close");
99     close.addActionListener(new ActionListener()
100     {
101       public void actionPerformed(ActionEvent e)
102       {
103         close_actionPerformed(e);
104       }
105     });
106     textfield.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
107     textfield.addActionListener(new ActionListener()
108     {
109       public void actionPerformed(ActionEvent e)
110       {
111         ok_actionPerformed(e);
112       }
113     });
114     jPanel1.add(ok);
115     jPanel1.add(close);
116     this.add(jLabel1, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0
117         , GridBagConstraints.WEST,
118         GridBagConstraints.NONE,
119         new Insets(7, 4, 0, 6), 77, 6));
120     this.add(jPanel1, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0
121         , GridBagConstraints.WEST,
122         GridBagConstraints.BOTH,
123         new Insets(7, -2, 7, 12), 241, -2));
124     this.add(database, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0
125         , GridBagConstraints.WEST,
126         GridBagConstraints.NONE,
127         new Insets(0, 4, 0, 0), 1, 0));
128     this.add(textfield, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0
129         , GridBagConstraints.CENTER,
130         GridBagConstraints.NONE,
131         new Insets(0, 0, 0, 6), 211, 1));
132   }
133
134   JComboBox database = new JComboBox();
135   JLabel jLabel1 = new JLabel();
136   JButton ok = new JButton();
137   JButton close = new JButton();
138   JPanel jPanel1 = new JPanel();
139   JTextField textfield = new JTextField();
140   GridBagLayout gridBagLayout1 = new GridBagLayout();
141   public void close_actionPerformed(ActionEvent e)
142   {
143     try
144     {
145       frame.setClosed(true);
146     }
147     catch (Exception ex)
148     {}
149   }
150
151   public void ok_actionPerformed(ActionEvent e)
152   {
153     database.setEnabled(false);
154     textfield.setEnabled(false);
155     ok.setEnabled(false);
156     close.setEnabled(false);
157
158     Thread worker = new Thread(this);
159     worker.start();
160   }
161
162   private void resetDialog()
163   {
164     database.setEnabled(true);
165     textfield.setEnabled(true);
166     ok.setEnabled(true);
167     close.setEnabled(true);
168   }
169
170   public void run()
171   {
172     String error = "";
173     if (database.getSelectedItem().equals(noDbSelected))
174     {
175       error += "Please select the source database\n";
176     }
177     com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex("\\s+", "");
178     textfield.setText(empty.replaceAll(textfield.getText()));
179     if (textfield.getText().length() == 0)
180     {
181       error += "Please enter a (semi-colon separated list of) database id(s)";
182     }
183     if (error.length() > 0)
184     {
185       showErrorMessage(error);
186       resetDialog();
187       return;
188     }
189
190     result = new StringBuffer();
191     if (database.getSelectedItem().equals("Uniprot"))
192     {
193       getUniprotFile(textfield.getText());
194     }
195     else if (database.getSelectedItem().equals("EMBL")
196         || database.getSelectedItem().equals("EMBLCDS"))
197     {
198       String DBRefSource = database.getSelectedItem().equals("EMBLCDS")
199       ? jalview.datamodel.DBRefSource.EMBLCDS
200           : jalview.datamodel.DBRefSource.EMBL;
201
202       StringTokenizer st = new StringTokenizer(textfield.getText(), ";");
203       SequenceI[] seqs = null;
204       while(st.hasMoreTokens())
205       {
206         EBIFetchClient dbFetch = new EBIFetchClient();
207
208         File reply = dbFetch.fetchDataAsFile(
209             database.getSelectedItem().toString().toLowerCase(
210             ) + ":" + st.nextToken(),
211             "emblxml",null);
212
213         jalview.datamodel.xdb.embl.EmblFile efile=null;
214         if (reply != null && reply.exists())
215         {
216           efile = jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply);
217         }
218         if (efile!=null) {
219           for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) {
220             EmblEntry entry = (EmblEntry) i.next();
221             SequenceI[] seqparts = entry.getSequences(false,true, DBRefSource);
222             if (seqparts!=null) {
223               SequenceI[] newseqs = null;
224               int si=0;
225               if (seqs==null) {
226                 newseqs = new SequenceI[seqparts.length];
227               } else {
228                 newseqs  = new SequenceI[seqs.length+seqparts.length];
229
230                 for (;si<seqs.length; si++) {
231                   newseqs[si] = seqs[si];
232                   seqs[si] = null;
233                 }
234               }
235               for (int j=0;j<seqparts.length; si++, j++) {
236                 newseqs[si] = seqparts[j].deriveSequence(); // place DBReferences on dataset and refer
237               }
238               seqs=newseqs;
239
240             }
241           }
242         } else {
243           result=null;
244         }
245       }
246       if (seqs!=null && seqs.length>0) {
247         if (parseResult(new Alignment(seqs), null, null)!=null)
248           result.append("# Successfully parsed the "+database.getSelectedItem()+" Queries into an Alignment");
249       }
250     }
251     else if (database.getSelectedItem().equals("PDB"))
252     {
253       StringTokenizer qset = new StringTokenizer(textfield.getText(), ";");
254       String query;
255       SequenceI[] seqs = null;
256       while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null))
257       {
258         SequenceI[] seqparts = getPDBFile(query.toUpperCase());
259         if (seqparts != null)
260         {
261           if (seqs == null)
262           {
263             seqs = seqparts;
264           }
265           else
266           {
267             SequenceI[] newseqs = new SequenceI[seqs.length+seqparts.length];
268             int i=0;
269             for (; i < seqs.length; i++)
270             {
271               newseqs[i] = seqs[i];
272               seqs[i] = null;
273             }
274             for (int j=0;j<seqparts.length; i++, j++)
275             {
276               newseqs[i] = seqparts[j];
277             }
278             seqs=newseqs;
279           }
280           result.append("# Success for "+query.toUpperCase()+"\n");
281         }
282       }
283       if (seqs != null && seqs.length > 0)
284       {
285         if (parseResult(new Alignment(seqs), null, null)!=null)
286         {
287           result.append(
288           "# Successfully parsed the PDB File Queries into an Alignment");
289         }
290       }
291     }
292     else if( database.getSelectedItem().equals("PFAM"))
293     {
294       try
295       {
296         result.append(new FastaFile(
297             "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc="
298             +  textfield.getText().toUpperCase(), "URL").print()
299         );
300
301         if(result.length()>0)
302         {
303           parseResult( result.toString(), textfield.getText().toUpperCase() );
304         }
305
306       }
307       catch (java.io.IOException ex)
308       {
309         result = null;
310       }
311     }
312
313     if (result == null || result.length() == 0)
314     {
315       showErrorMessage("Error retrieving " + textfield.getText()
316           + " from " + database.getSelectedItem());
317     }
318
319     resetDialog();
320     return;
321   }
322
323   void getUniprotFile(String id)
324   {
325     EBIFetchClient ebi = new EBIFetchClient();
326     File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
327
328     DBRefFetcher dbref = new DBRefFetcher();
329     Vector entries = dbref.getUniprotEntries(file);
330
331     if (entries != null)
332     {
333       //First, make the new sequences
334       Enumeration en = entries.elements();
335       while (en.hasMoreElements())
336       {
337         UniprotEntry entry = (UniprotEntry) en.nextElement();
338
339         StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot");
340         Enumeration en2 = entry.getAccession().elements();
341         while (en2.hasMoreElements())
342         {
343           name.append("|");
344           name.append(en2.nextElement());
345         }
346         en2 = entry.getName().elements();
347         while (en2.hasMoreElements())
348         {
349           name.append("|");
350           name.append(en2.nextElement());
351         }
352
353         if (entry.getProtein() != null)
354         {
355           name.append(" " + entry.getProtein().getName().elementAt(0));
356         }
357
358         result.append(name + "\n" + entry.getUniprotSequence().getContent() +
359         "\n");
360
361       }
362
363       //Then read in the features and apply them to the dataset
364       Alignment al = parseResult(result.toString(), null);
365       for (int i = 0; i < entries.size(); i++)
366       {
367         UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
368         Enumeration e = entry.getDbReference().elements();
369         Vector onlyPdbEntries = new Vector();
370         while (e.hasMoreElements())
371         {
372           PDBEntry pdb = (PDBEntry) e.nextElement();
373           if (!pdb.getType().equals("PDB"))
374           {
375             continue;
376           }
377
378           onlyPdbEntries.addElement(pdb);
379         }
380
381         Enumeration en2 = entry.getAccession().elements();
382         while (en2.hasMoreElements())
383         {
384           al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
385               DBRefSource.UNIPROT,
386               "0",
387               en2.nextElement().toString()));
388         }
389
390
391
392
393         al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries);
394         if (entry.getFeature() != null)
395         {
396           e = entry.getFeature().elements();
397           while (e.hasMoreElements())
398           {
399             SequenceFeature sf = (SequenceFeature) e.nextElement();
400             sf.setFeatureGroup("Uniprot");
401             al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf );
402           }
403         }
404       }
405     }
406   }
407
408   SequenceI[] getPDBFile(String id)
409   {
410     Vector result = new Vector();
411     String chain = null;
412     if (id.indexOf(":") > -1)
413     {
414       chain = id.substring(id.indexOf(":") + 1);
415       id = id.substring(0, id.indexOf(":"));
416     }
417
418     EBIFetchClient ebi = new EBIFetchClient();
419     String file = ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw").
420     getAbsolutePath();
421     if (file == null)
422     {
423       return null;
424     }
425     try
426     {
427       PDBfile pdbfile = new PDBfile(file, jalview.io.AppletFormatAdapter.FILE);
428       for (int i = 0; i < pdbfile.chains.size(); i++)
429       {
430         if (chain == null ||
431             ( (PDBChain) pdbfile.chains.elementAt(i)).id.
432             toUpperCase().equals(chain))
433         {
434           PDBChain pdbchain = (PDBChain) pdbfile.chains.elementAt(i);
435           // Get the Chain's Sequence - who's dataset includes any special features added from the PDB file
436           SequenceI sq = pdbchain.sequence;
437           // Specially formatted name for the PDB chain sequences retrieved from the PDB
438           sq.setName("PDB|"+id+"|"+sq.getName());
439           // Might need to add more metadata to the PDBEntry object
440           // like below
441           /*
442            * PDBEntry entry = new PDBEntry();
443             // Construct the PDBEntry
444             entry.setId(id);
445             if (entry.getProperty() == null)
446                 entry.setProperty(new Hashtable());
447             entry.getProperty().put("chains",
448                         pdbchain.id
449                         + "=" + sq.getStart()
450                         + "-" + sq.getEnd());
451             sq.getDatasetSequence().addPDBId(entry);
452            */
453           // Add PDB DB Refs
454           // We make a DBRefEtntry because we have obtained the PDB file from a verifiable source
455           // JBPNote - PDB DBRefEntry should also carry the chain and mapping information
456           DBRefEntry dbentry = new DBRefEntry(jalview.datamodel.DBRefSource.PDB,
457               "0", id + pdbchain.id);
458           sq.addDBRef(dbentry);
459           // and add seuqence to the retrieved set
460           result.addElement(sq.deriveSequence());
461         }
462       }
463
464       if (result.size() < 1)
465       {
466         throw new Exception("WsDBFetch for PDB id resulted in zero result size");
467       }
468     }
469     catch (Exception ex) // Problem parsing PDB file
470     {
471       jalview.bin.Cache.log.warn("Exception when retrieving " +
472           textfield.getText() + " from " +
473           database.getSelectedItem(), ex);
474       return null;
475     }
476
477
478     SequenceI[] results = new SequenceI[result.size()];
479     for (int i = 0, j = result.size(); i < j; i++)
480     {
481       results[i] = (SequenceI) result.elementAt(i);
482       result.setElementAt(null,i);
483     }
484     return results;
485   }
486   Alignment parseResult(String result, String title)
487   {
488     String format = new IdentifyFile().Identify(result, "Paste");
489     Alignment sequences = null;
490     if (FormatAdapter.isValidFormat(format))
491     {
492       sequences = null;
493       try
494       {
495         sequences = new FormatAdapter().readFile(result.toString(), "Paste",
496             format);
497       }
498       catch (Exception ex)
499       {}
500
501       if (sequences!=null)
502       {
503         return parseResult(sequences, title, format);
504       }
505     }
506     else
507     {
508       showErrorMessage("Error retrieving " + textfield.getText()
509           + " from " + database.getSelectedItem());
510     }
511
512     return null;
513   }
514
515   Alignment parseResult(Alignment al, String title, String currentFileFormat)
516   {
517
518     if (al != null && al.getHeight() > 0)
519     {
520       if (alignFrame == null)
521       {
522         AlignFrame af = new AlignFrame(al,
523             AlignFrame.DEFAULT_WIDTH,
524             AlignFrame.DEFAULT_HEIGHT);
525         if (currentFileFormat!=null)
526         {
527           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT FORMAT FOR NON-FormatAdapter Sourced Alignments?
528         }
529
530         if(title==null)
531         {
532           title = "Retrieved from " + database.getSelectedItem();
533         }
534
535         Desktop.addInternalFrame(af,
536             title,
537             AlignFrame.DEFAULT_WIDTH,
538             AlignFrame.DEFAULT_HEIGHT);
539
540         af.statusBar.setText("Successfully pasted alignment file");
541
542         try
543         {
544           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
545         }
546         catch (Exception ex)
547         {}
548       }
549       else
550       {
551         for (int i = 0; i < al.getHeight(); i++)
552         {
553           alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this also creates dataset sequence entries
554         }
555         alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment.
556             getHeight());
557         alignFrame.viewport.alignment.getWidth();
558         alignFrame.viewport.firePropertyChange("alignment", null,
559             alignFrame.viewport.
560             getAlignment().getSequences());
561       }
562     }
563     return al;
564   }
565
566   void showErrorMessage(final String error)
567   {
568     resetDialog();
569     javax.swing.SwingUtilities.invokeLater(new Runnable()
570     {
571       public void run()
572       {
573         JOptionPane.showInternalMessageDialog(Desktop.desktop,
574             error, "Error Retrieving Data",
575             JOptionPane.WARNING_MESSAGE);
576       }
577     });
578   }
579 }
580