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