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