2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
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.
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.
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
25 import java.awt.event.*;
30 import jalview.datamodel.*;
31 import jalview.datamodel.xdb.embl.*;
34 import jalview.ws.DBRefFetcher;
35 import jalview.ws.ebi.EBIFetchClient;
36 import jalview.ws.seqfetcher.ASequenceFetcher;
37 import jalview.ws.seqfetcher.DbSourceProxy;
39 import java.awt.Rectangle;
40 import java.awt.BorderLayout;
41 import java.awt.Dimension;
43 public class SequenceFetcher extends JPanel implements Runnable
45 // ASequenceFetcher sfetch;
48 IProgressIndicator guiWindow;
50 AlignFrame alignFrame;
54 final String noDbSelected = "-- Select Database --";
56 Hashtable sources = new Hashtable();
58 private static jalview.ws.SequenceFetcher sfetch = null;
60 private static String dasRegistry = null;
63 * Blocking method that initialises and returns the shared instance of the
64 * SequenceFetcher client
67 * where the initialisation delay message should be shown
68 * @return the singleton instance of the sequence fetcher client
70 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
71 final IProgressIndicator guiWindow)
74 || dasRegistry != DasSourceBrowser.getDasRegistryURL())
77 * give a visual indication that sequence fetcher construction is occuring
79 if (guiWindow != null)
81 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
82 Thread.currentThread().hashCode());
84 dasRegistry = DasSourceBrowser.getDasRegistryURL();
85 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
86 if (guiWindow != null)
88 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
89 Thread.currentThread().hashCode());
97 public SequenceFetcher(IProgressIndicator guiIndic)
99 final IProgressIndicator guiWindow = guiIndic;
100 final SequenceFetcher us = this;
101 // launch initialiser thread
102 Thread sf = new Thread(new Runnable()
107 if (getSequenceFetcherSingleton(guiWindow) != null)
109 us.initGui(guiWindow);
113 javax.swing.SwingUtilities.invokeLater(new Runnable()
118 .showInternalMessageDialog(
120 "Could not create the sequence fetcher client. Check error logs for details.",
121 "Couldn't create SequenceFetcher",
122 JOptionPane.ERROR_MESSAGE);
126 // raise warning dialog
134 * called by thread spawned by constructor
138 private void initGui(IProgressIndicator guiWindow)
140 this.guiWindow = guiWindow;
141 if (guiWindow instanceof AlignFrame)
143 alignFrame = (AlignFrame) guiWindow;
146 database.addItem(noDbSelected);
148 * Dynamically generated database list will need a translation function from
149 * internal source to externally distinct names. UNIPROT and UP_NAME are
150 * identical DB sources, and should be collapsed.
153 String dbs[] = sfetch.getOrderedSupportedSources();
154 for (int i = 0; i < dbs.length; i++)
156 if (!sources.containsValue(dbs[i]))
158 String name = sfetch.getSourceProxy(dbs[i]).getDbName();
159 // duplicate source names are thrown away, here.
160 if (!sources.containsKey(name))
162 database.addItem(name);
164 // overwrite with latest version of the retriever for this source
165 sources.put(name, dbs[i]);
171 } catch (Exception ex)
173 ex.printStackTrace();
176 frame = new JInternalFrame();
177 frame.setContentPane(this);
178 if (new jalview.util.Platform().isAMac())
180 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
184 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
188 private String getFrameTitle()
190 return ((alignFrame == null) ? "New " : "Additional ")
191 + "Sequence Fetcher";
194 private void jbInit() throws Exception
196 this.setLayout(borderLayout2);
198 database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
199 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
200 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
201 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
203 .setText("Separate multiple accession ids with semi colon \";\"");
205 ok.addActionListener(new ActionListener()
207 public void actionPerformed(ActionEvent e)
209 ok_actionPerformed();
212 clear.setText("Clear");
213 clear.addActionListener(new ActionListener()
215 public void actionPerformed(ActionEvent e)
217 clear_actionPerformed();
221 example.setText("Example");
222 example.addActionListener(new ActionListener()
224 public void actionPerformed(ActionEvent e)
226 example_actionPerformed();
229 close.setText("Close");
230 close.addActionListener(new ActionListener()
232 public void actionPerformed(ActionEvent e)
234 close_actionPerformed(e);
237 textArea.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
238 textArea.setLineWrap(true);
239 textArea.addKeyListener(new KeyAdapter()
241 public void keyPressed(KeyEvent e)
243 if (e.getKeyCode() == KeyEvent.VK_ENTER)
244 ok_actionPerformed();
247 jPanel3.setLayout(borderLayout1);
248 borderLayout1.setVgap(5);
250 jPanel1.add(example);
253 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
254 jPanel2.setLayout(borderLayout3);
256 database.addActionListener(new ActionListener()
259 public void actionPerformed(ActionEvent e)
261 DbSourceProxy db = null;
264 db = sfetch.getSourceProxy((String) sources.get(database
265 .getSelectedItem()));
266 dbeg.setText("Example query: " + db.getTestQuery());
267 } catch (Exception ex)
275 jPanel2.add(database, java.awt.BorderLayout.NORTH);
276 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
277 jPanel2.add(jLabel1, java.awt.BorderLayout.SOUTH);
278 // jPanel2.setPreferredSize(new Dimension())
279 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
280 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
281 this.add(jPanel3, java.awt.BorderLayout.CENTER);
282 this.add(jPanel2, java.awt.BorderLayout.NORTH);
283 jScrollPane1.getViewport().add(textArea);
287 protected void example_actionPerformed()
289 DbSourceProxy db = null;
292 db = sfetch.getSourceProxy((String) sources.get(database
293 .getSelectedItem()));
294 textArea.setText(db.getTestQuery());
295 } catch (Exception ex)
301 protected void clear_actionPerformed()
303 textArea.setText("");
307 JLabel dbeg = new JLabel();
309 JComboBox database = new JComboBox();
311 JLabel jLabel1 = new JLabel();
313 JButton ok = new JButton();
315 JButton clear = new JButton();
317 JButton example = new JButton();
319 JButton close = new JButton();
321 JPanel jPanel1 = new JPanel();
323 JTextArea textArea = new JTextArea();
325 JScrollPane jScrollPane1 = new JScrollPane();
327 JPanel jPanel2 = new JPanel();
329 JPanel jPanel3 = new JPanel();
331 JPanel jPanel4 = new JPanel();
333 BorderLayout borderLayout1 = new BorderLayout();
335 BorderLayout borderLayout2 = new BorderLayout();
337 BorderLayout borderLayout3 = new BorderLayout();
339 public void close_actionPerformed(ActionEvent e)
343 frame.setClosed(true);
344 } catch (Exception ex)
349 public void ok_actionPerformed()
351 database.setEnabled(false);
352 textArea.setEnabled(false);
353 ok.setEnabled(false);
354 close.setEnabled(false);
356 Thread worker = new Thread(this);
360 private void resetDialog()
362 database.setEnabled(true);
363 textArea.setEnabled(true);
365 close.setEnabled(true);
371 if (database.getSelectedItem().equals(noDbSelected))
373 error += "Please select the source database\n";
375 // TODO: make this transformation optional and configurable
376 com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex("(\\s|[,; ])+",";"); //\\s+", "");
377 textArea.setText(empty.replaceAll(textArea.getText()));
378 // see if there's anthing to search with
379 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea.getText()))
381 error += "Please enter a (semi-colon separated list of) database id(s)";
383 if (error.length() > 0)
385 showErrorMessage(error);
389 AlignmentI aresult = null;
390 Object source = database.getSelectedItem();
391 Enumeration en = new StringTokenizer(textArea.getText(), ";");
394 guiWindow.setProgressBar("Fetching Sequences from "
395 + database.getSelectedItem(), Thread.currentThread()
397 DbSourceProxy proxy = sfetch.getSourceProxy(
398 (String) sources.get(source));
399 if (proxy.getAccessionSeparator()==null)
401 while (en.hasMoreElements())
403 String item = (String) en.nextElement();
408 // give the server a chance to breathe
410 } catch (Exception e)
416 AlignmentI indres = proxy.getSequenceRecords(item);
423 aresult.append(indres);
426 } catch (Exception e)
428 jalview.bin.Cache.log.info("Error retrieving "+item+" from "+source,e);
432 StringBuffer multiacc = new StringBuffer();
433 while (en.hasMoreElements())
435 multiacc.append(en.nextElement());
436 if (en.hasMoreElements())
438 multiacc.append(proxy.getAccessionSeparator());
442 .getSequenceRecords(multiacc.toString());
445 } catch (Exception e)
447 showErrorMessage("Error retrieving " + textArea.getText() + " from "
448 + database.getSelectedItem());
449 // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
450 System.err.println("Retrieval failed for source ='"
451 + database.getSelectedItem() + "' and query\n'"
452 + textArea.getText() + "'\n");
454 } catch (OutOfMemoryError e)
456 // resets dialog box - so we don't use OOMwarning here.
457 showErrorMessage("Out of Memory when retrieving "
460 + database.getSelectedItem()
461 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
465 showErrorMessage("Serious Error retrieving " + textArea.getText()
466 + " from " + database.getSelectedItem());
471 parseResult(aresult, null, null);
473 // only remove visual delay after we finished parsing.
474 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
479 * result = new StringBuffer(); if
480 * (database.getSelectedItem().equals("Uniprot")) {
481 * getUniprotFile(textArea.getText()); } else if
482 * (database.getSelectedItem().equals("EMBL") ||
483 * database.getSelectedItem().equals("EMBLCDS")) { String DBRefSource =
484 * database.getSelectedItem().equals("EMBLCDS") ?
485 * jalview.datamodel.DBRefSource.EMBLCDS : jalview.datamodel.DBRefSource.EMBL;
487 * StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
488 * SequenceI[] seqs = null; while(st.hasMoreTokens()) { EBIFetchClient dbFetch =
489 * new EBIFetchClient(); String qry =
490 * database.getSelectedItem().toString().toLowerCase( ) + ":" +
491 * st.nextToken(); File reply = dbFetch.fetchDataAsFile( qry, "emblxml",null);
493 * jalview.datamodel.xdb.embl.EmblFile efile=null; if (reply != null &&
494 * reply.exists()) { efile =
495 * jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply); } if (efile!=null) {
496 * for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) { EmblEntry
497 * entry = (EmblEntry) i.next(); SequenceI[] seqparts =
498 * entry.getSequences(false,true, DBRefSource); if (seqparts!=null) {
499 * SequenceI[] newseqs = null; int si=0; if (seqs==null) { newseqs = new
500 * SequenceI[seqparts.length]; } else { newseqs = new
501 * SequenceI[seqs.length+seqparts.length];
503 * for (;si<seqs.length; si++) { newseqs[si] = seqs[si]; seqs[si] = null; } }
504 * for (int j=0;j<seqparts.length; si++, j++) { newseqs[si] =
505 * seqparts[j].deriveSequence(); // place DBReferences on dataset and refer }
506 * seqs=newseqs; } } } else { result.append("# no response for "+qry); } } if
507 * (seqs!=null && seqs.length>0) { if (parseResult(new Alignment(seqs), null,
508 * null)!=null) { result.append("# Successfully parsed the
509 * "+database.getSelectedItem()+" Queries into an Alignment"); } } } else if
510 * (database.getSelectedItem().equals("PDB")) { StringTokenizer qset = new
511 * StringTokenizer(textArea.getText(), ";"); String query; SequenceI[] seqs =
512 * null; while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null)) {
513 * SequenceI[] seqparts = getPDBFile(query.toUpperCase()); if (seqparts !=
514 * null) { if (seqs == null) { seqs = seqparts; } else { SequenceI[] newseqs =
515 * new SequenceI[seqs.length+seqparts.length]; int i=0; for (; i <
516 * seqs.length; i++) { newseqs[i] = seqs[i]; seqs[i] = null; } for (int j=0;j<seqparts.length;
517 * i++, j++) { newseqs[i] = seqparts[j]; } seqs=newseqs; } result.append("#
518 * Success for "+query.toUpperCase()+"\n"); } } if (seqs != null &&
519 * seqs.length > 0) { if (parseResult(new Alignment(seqs), null, null)!=null) {
520 * result.append( "# Successfully parsed the PDB File Queries into an
521 * Alignment"); } } } else if( database.getSelectedItem().equals("PFAM")) {
522 * try { result.append(new FastaFile(
523 * "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc=" +
524 * textArea.getText().toUpperCase(), "URL").print() );
526 * if(result.length()>0) { parseResult( result.toString(),
527 * textArea.getText().toUpperCase() ); } } catch (java.io.IOException ex) {
530 * if (result == null || result.length() == 0) { showErrorMessage("Error
531 * retrieving " + textArea.getText() + " from " + database.getSelectedItem()); }
533 * resetDialog(); return; }
535 * void getUniprotFile(String id) { EBIFetchClient ebi = new EBIFetchClient();
536 * File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
538 * DBRefFetcher dbref = new DBRefFetcher(); Vector entries =
539 * dbref.getUniprotEntries(file);
541 * if (entries != null) { //First, make the new sequences Enumeration en =
542 * entries.elements(); while (en.hasMoreElements()) { UniprotEntry entry =
543 * (UniprotEntry) en.nextElement();
545 * StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot"); Enumeration
546 * en2 = entry.getAccession().elements(); while (en2.hasMoreElements()) {
547 * name.append("|"); name.append(en2.nextElement()); } en2 =
548 * entry.getName().elements(); while (en2.hasMoreElements()) {
549 * name.append("|"); name.append(en2.nextElement()); }
551 * if (entry.getProtein() != null) { name.append(" " +
552 * entry.getProtein().getName().elementAt(0)); }
554 * result.append(name + "\n" + entry.getUniprotSequence().getContent() +
557 * //Then read in the features and apply them to the dataset Alignment al =
558 * parseResult(result.toString(), null); for (int i = 0; i < entries.size();
559 * i++) { UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
560 * Enumeration e = entry.getDbReference().elements(); Vector onlyPdbEntries =
561 * new Vector(); while (e.hasMoreElements()) { PDBEntry pdb = (PDBEntry)
562 * e.nextElement(); if (!pdb.getType().equals("PDB")) { continue; }
564 * onlyPdbEntries.addElement(pdb); }
566 * Enumeration en2 = entry.getAccession().elements(); while
567 * (en2.hasMoreElements()) {
568 * al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
569 * DBRefSource.UNIPROT, "0", en2.nextElement().toString())); }
574 * al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries); if
575 * (entry.getFeature() != null) { e = entry.getFeature().elements(); while
576 * (e.hasMoreElements()) { SequenceFeature sf = (SequenceFeature)
577 * e.nextElement(); sf.setFeatureGroup("Uniprot");
578 * al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf ); } } } } }
580 * SequenceI[] getPDBFile(String id) { Vector result = new Vector(); String
581 * chain = null; if (id.indexOf(":") > -1) { chain =
582 * id.substring(id.indexOf(":") + 1); id = id.substring(0, id.indexOf(":")); }
584 * EBIFetchClient ebi = new EBIFetchClient(); String file =
585 * ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw"). getAbsolutePath(); if (file ==
586 * null) { return null; } try { PDBfile pdbfile = new PDBfile(file,
587 * jalview.io.AppletFormatAdapter.FILE); for (int i = 0; i <
588 * pdbfile.chains.size(); i++) { if (chain == null || ( (PDBChain)
589 * pdbfile.chains.elementAt(i)).id. toUpperCase().equals(chain)) { PDBChain
590 * pdbchain = (PDBChain) pdbfile.chains.elementAt(i); // Get the Chain's
591 * Sequence - who's dataset includes any special features added from the PDB
592 * file SequenceI sq = pdbchain.sequence; // Specially formatted name for the
593 * PDB chain sequences retrieved from the PDB
594 * sq.setName("PDB|"+id+"|"+sq.getName()); // Might need to add more metadata
595 * to the PDBEntry object // like below /* PDBEntry entry = new PDBEntry(); //
596 * Construct the PDBEntry entry.setId(id); if (entry.getProperty() == null)
597 * entry.setProperty(new Hashtable()); entry.getProperty().put("chains",
598 * pdbchain.id + "=" + sq.getStart() + "-" + sq.getEnd());
599 * sq.getDatasetSequence().addPDBId(entry); // Add PDB DB Refs // We make a
600 * DBRefEtntry because we have obtained the PDB file from a verifiable source //
601 * JBPNote - PDB DBRefEntry should also carry the chain and mapping
602 * information DBRefEntry dbentry = new
603 * DBRefEntry(jalview.datamodel.DBRefSource.PDB, "0", id + pdbchain.id);
604 * sq.addDBRef(dbentry); // and add seuqence to the retrieved set
605 * result.addElement(sq.deriveSequence()); } }
607 * if (result.size() < 1) { throw new Exception("WsDBFetch for PDB id resulted
608 * in zero result size"); } } catch (Exception ex) // Problem parsing PDB file {
609 * jalview.bin.Cache.log.warn("Exception when retrieving " +
610 * textArea.getText() + " from " + database.getSelectedItem(), ex); return
614 * SequenceI[] results = new SequenceI[result.size()]; for (int i = 0, j =
615 * result.size(); i < j; i++) { results[i] = (SequenceI) result.elementAt(i);
616 * result.setElementAt(null,i); } return results; }
618 AlignmentI parseResult(String result, String title)
620 String format = new IdentifyFile().Identify(result, "Paste");
621 Alignment sequences = null;
622 if (FormatAdapter.isValidFormat(format))
627 sequences = new FormatAdapter().readFile(result.toString(),
629 } catch (Exception ex)
633 if (sequences != null)
635 return parseResult(sequences, title, format);
640 showErrorMessage("Error retrieving " + textArea.getText() + " from "
641 + database.getSelectedItem());
647 AlignmentI parseResult(AlignmentI al, String title,
648 String currentFileFormat)
651 if (al != null && al.getHeight() > 0)
653 if (alignFrame == null)
655 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
656 AlignFrame.DEFAULT_HEIGHT);
657 if (currentFileFormat != null)
659 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
661 // NON-FormatAdapter Sourced
667 title = "Retrieved from " + database.getSelectedItem();
669 SequenceFeature[] sfs=null;
670 for (Enumeration sq=al.getSequences().elements(); sq.hasMoreElements();)
672 if ((sfs=((SequenceI)sq.nextElement()).getDatasetSequence().getSequenceFeatures())!=null)
676 af.setShowSeqFeatures(true);
682 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
683 AlignFrame.DEFAULT_HEIGHT);
685 af.statusBar.setText("Successfully pasted alignment file");
689 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
691 } catch (Exception ex)
697 for (int i = 0; i < al.getHeight(); i++)
699 alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this
706 alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment
708 alignFrame.viewport.alignment.getWidth();
709 alignFrame.viewport.firePropertyChange("alignment", null,
710 alignFrame.viewport.getAlignment().getSequences());
716 void showErrorMessage(final String error)
719 javax.swing.SwingUtilities.invokeLater(new Runnable()
723 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
724 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);