2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 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 com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex("\\s+", "");
376 textArea.setText(empty.replaceAll(textArea.getText()));
377 if (textArea.getText().length() == 0)
379 error += "Please enter a (semi-colon separated list of) database id(s)";
381 if (error.length() > 0)
383 showErrorMessage(error);
387 AlignmentI aresult = null;
388 Object source = database.getSelectedItem();
389 Enumeration en = new StringTokenizer(textArea.getText(), ";");
392 guiWindow.setProgressBar("Fetching Sequences from "
393 + database.getSelectedItem(), Thread.currentThread()
395 DbSourceProxy proxy = sfetch.getSourceProxy(
396 (String) sources.get(source));
397 if (proxy.getAccessionSeparator()==null)
399 while (en.hasMoreElements())
401 String item = (String) en.nextElement();
406 // give the server a chance to breathe
408 } catch (Exception e)
414 AlignmentI indres = proxy.getSequenceRecords(item);
421 aresult.append(indres);
424 } catch (Exception e)
426 jalview.bin.Cache.log.info("Error retrieving "+item+" from "+source,e);
430 StringBuffer multiacc = new StringBuffer();
431 while (en.hasMoreElements())
433 multiacc.append(en.nextElement());
434 if (en.hasMoreElements())
436 multiacc.append(proxy.getAccessionSeparator());
440 .getSequenceRecords(multiacc.toString());
443 } catch (Exception e)
445 showErrorMessage("Error retrieving " + textArea.getText() + " from "
446 + database.getSelectedItem());
447 // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
448 System.err.println("Retrieval failed for source ='"
449 + database.getSelectedItem() + "' and query\n'"
450 + textArea.getText() + "'\n");
452 } catch (OutOfMemoryError e)
454 // resets dialog box - so we don't use OOMwarning here.
455 showErrorMessage("Out of Memory when retrieving "
458 + database.getSelectedItem()
459 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
463 showErrorMessage("Serious Error retrieving " + textArea.getText()
464 + " from " + database.getSelectedItem());
469 parseResult(aresult, null, null);
471 // only remove visual delay after we finished parsing.
472 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
477 * result = new StringBuffer(); if
478 * (database.getSelectedItem().equals("Uniprot")) {
479 * getUniprotFile(textArea.getText()); } else if
480 * (database.getSelectedItem().equals("EMBL") ||
481 * database.getSelectedItem().equals("EMBLCDS")) { String DBRefSource =
482 * database.getSelectedItem().equals("EMBLCDS") ?
483 * jalview.datamodel.DBRefSource.EMBLCDS : jalview.datamodel.DBRefSource.EMBL;
485 * StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
486 * SequenceI[] seqs = null; while(st.hasMoreTokens()) { EBIFetchClient dbFetch =
487 * new EBIFetchClient(); String qry =
488 * database.getSelectedItem().toString().toLowerCase( ) + ":" +
489 * st.nextToken(); File reply = dbFetch.fetchDataAsFile( qry, "emblxml",null);
491 * jalview.datamodel.xdb.embl.EmblFile efile=null; if (reply != null &&
492 * reply.exists()) { efile =
493 * jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply); } if (efile!=null) {
494 * for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) { EmblEntry
495 * entry = (EmblEntry) i.next(); SequenceI[] seqparts =
496 * entry.getSequences(false,true, DBRefSource); if (seqparts!=null) {
497 * SequenceI[] newseqs = null; int si=0; if (seqs==null) { newseqs = new
498 * SequenceI[seqparts.length]; } else { newseqs = new
499 * SequenceI[seqs.length+seqparts.length];
501 * for (;si<seqs.length; si++) { newseqs[si] = seqs[si]; seqs[si] = null; } }
502 * for (int j=0;j<seqparts.length; si++, j++) { newseqs[si] =
503 * seqparts[j].deriveSequence(); // place DBReferences on dataset and refer }
504 * seqs=newseqs; } } } else { result.append("# no response for "+qry); } } if
505 * (seqs!=null && seqs.length>0) { if (parseResult(new Alignment(seqs), null,
506 * null)!=null) { result.append("# Successfully parsed the
507 * "+database.getSelectedItem()+" Queries into an Alignment"); } } } else if
508 * (database.getSelectedItem().equals("PDB")) { StringTokenizer qset = new
509 * StringTokenizer(textArea.getText(), ";"); String query; SequenceI[] seqs =
510 * null; while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null)) {
511 * SequenceI[] seqparts = getPDBFile(query.toUpperCase()); if (seqparts !=
512 * null) { if (seqs == null) { seqs = seqparts; } else { SequenceI[] newseqs =
513 * new SequenceI[seqs.length+seqparts.length]; int i=0; for (; i <
514 * seqs.length; i++) { newseqs[i] = seqs[i]; seqs[i] = null; } for (int j=0;j<seqparts.length;
515 * i++, j++) { newseqs[i] = seqparts[j]; } seqs=newseqs; } result.append("#
516 * Success for "+query.toUpperCase()+"\n"); } } if (seqs != null &&
517 * seqs.length > 0) { if (parseResult(new Alignment(seqs), null, null)!=null) {
518 * result.append( "# Successfully parsed the PDB File Queries into an
519 * Alignment"); } } } else if( database.getSelectedItem().equals("PFAM")) {
520 * try { result.append(new FastaFile(
521 * "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc=" +
522 * textArea.getText().toUpperCase(), "URL").print() );
524 * if(result.length()>0) { parseResult( result.toString(),
525 * textArea.getText().toUpperCase() ); } } catch (java.io.IOException ex) {
528 * if (result == null || result.length() == 0) { showErrorMessage("Error
529 * retrieving " + textArea.getText() + " from " + database.getSelectedItem()); }
531 * resetDialog(); return; }
533 * void getUniprotFile(String id) { EBIFetchClient ebi = new EBIFetchClient();
534 * File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
536 * DBRefFetcher dbref = new DBRefFetcher(); Vector entries =
537 * dbref.getUniprotEntries(file);
539 * if (entries != null) { //First, make the new sequences Enumeration en =
540 * entries.elements(); while (en.hasMoreElements()) { UniprotEntry entry =
541 * (UniprotEntry) en.nextElement();
543 * StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot"); Enumeration
544 * en2 = entry.getAccession().elements(); while (en2.hasMoreElements()) {
545 * name.append("|"); name.append(en2.nextElement()); } en2 =
546 * entry.getName().elements(); while (en2.hasMoreElements()) {
547 * name.append("|"); name.append(en2.nextElement()); }
549 * if (entry.getProtein() != null) { name.append(" " +
550 * entry.getProtein().getName().elementAt(0)); }
552 * result.append(name + "\n" + entry.getUniprotSequence().getContent() +
555 * //Then read in the features and apply them to the dataset Alignment al =
556 * parseResult(result.toString(), null); for (int i = 0; i < entries.size();
557 * i++) { UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
558 * Enumeration e = entry.getDbReference().elements(); Vector onlyPdbEntries =
559 * new Vector(); while (e.hasMoreElements()) { PDBEntry pdb = (PDBEntry)
560 * e.nextElement(); if (!pdb.getType().equals("PDB")) { continue; }
562 * onlyPdbEntries.addElement(pdb); }
564 * Enumeration en2 = entry.getAccession().elements(); while
565 * (en2.hasMoreElements()) {
566 * al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
567 * DBRefSource.UNIPROT, "0", en2.nextElement().toString())); }
572 * al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries); if
573 * (entry.getFeature() != null) { e = entry.getFeature().elements(); while
574 * (e.hasMoreElements()) { SequenceFeature sf = (SequenceFeature)
575 * e.nextElement(); sf.setFeatureGroup("Uniprot");
576 * al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf ); } } } } }
578 * SequenceI[] getPDBFile(String id) { Vector result = new Vector(); String
579 * chain = null; if (id.indexOf(":") > -1) { chain =
580 * id.substring(id.indexOf(":") + 1); id = id.substring(0, id.indexOf(":")); }
582 * EBIFetchClient ebi = new EBIFetchClient(); String file =
583 * ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw"). getAbsolutePath(); if (file ==
584 * null) { return null; } try { PDBfile pdbfile = new PDBfile(file,
585 * jalview.io.AppletFormatAdapter.FILE); for (int i = 0; i <
586 * pdbfile.chains.size(); i++) { if (chain == null || ( (PDBChain)
587 * pdbfile.chains.elementAt(i)).id. toUpperCase().equals(chain)) { PDBChain
588 * pdbchain = (PDBChain) pdbfile.chains.elementAt(i); // Get the Chain's
589 * Sequence - who's dataset includes any special features added from the PDB
590 * file SequenceI sq = pdbchain.sequence; // Specially formatted name for the
591 * PDB chain sequences retrieved from the PDB
592 * sq.setName("PDB|"+id+"|"+sq.getName()); // Might need to add more metadata
593 * to the PDBEntry object // like below /* PDBEntry entry = new PDBEntry(); //
594 * Construct the PDBEntry entry.setId(id); if (entry.getProperty() == null)
595 * entry.setProperty(new Hashtable()); entry.getProperty().put("chains",
596 * pdbchain.id + "=" + sq.getStart() + "-" + sq.getEnd());
597 * sq.getDatasetSequence().addPDBId(entry); // Add PDB DB Refs // We make a
598 * DBRefEtntry because we have obtained the PDB file from a verifiable source //
599 * JBPNote - PDB DBRefEntry should also carry the chain and mapping
600 * information DBRefEntry dbentry = new
601 * DBRefEntry(jalview.datamodel.DBRefSource.PDB, "0", id + pdbchain.id);
602 * sq.addDBRef(dbentry); // and add seuqence to the retrieved set
603 * result.addElement(sq.deriveSequence()); } }
605 * if (result.size() < 1) { throw new Exception("WsDBFetch for PDB id resulted
606 * in zero result size"); } } catch (Exception ex) // Problem parsing PDB file {
607 * jalview.bin.Cache.log.warn("Exception when retrieving " +
608 * textArea.getText() + " from " + database.getSelectedItem(), ex); return
612 * SequenceI[] results = new SequenceI[result.size()]; for (int i = 0, j =
613 * result.size(); i < j; i++) { results[i] = (SequenceI) result.elementAt(i);
614 * result.setElementAt(null,i); } return results; }
616 AlignmentI parseResult(String result, String title)
618 String format = new IdentifyFile().Identify(result, "Paste");
619 Alignment sequences = null;
620 if (FormatAdapter.isValidFormat(format))
625 sequences = new FormatAdapter().readFile(result.toString(),
627 } catch (Exception ex)
631 if (sequences != null)
633 return parseResult(sequences, title, format);
638 showErrorMessage("Error retrieving " + textArea.getText() + " from "
639 + database.getSelectedItem());
645 AlignmentI parseResult(AlignmentI al, String title,
646 String currentFileFormat)
649 if (al != null && al.getHeight() > 0)
651 if (alignFrame == null)
653 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
654 AlignFrame.DEFAULT_HEIGHT);
655 if (currentFileFormat != null)
657 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
659 // NON-FormatAdapter Sourced
665 title = "Retrieved from " + database.getSelectedItem();
667 SequenceFeature[] sfs=null;
668 for (Enumeration sq=al.getSequences().elements(); sq.hasMoreElements();)
670 if ((sfs=((SequenceI)sq.nextElement()).getDatasetSequence().getSequenceFeatures())!=null)
674 af.setShowSeqFeatures(true);
680 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
681 AlignFrame.DEFAULT_HEIGHT);
683 af.statusBar.setText("Successfully pasted alignment file");
687 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
689 } catch (Exception ex)
695 for (int i = 0; i < al.getHeight(); i++)
697 alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this
704 alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment
706 alignFrame.viewport.alignment.getWidth();
707 alignFrame.viewport.firePropertyChange("alignment", null,
708 alignFrame.viewport.getAlignment().getSequences());
714 void showErrorMessage(final String error)
717 javax.swing.SwingUtilities.invokeLater(new Runnable()
721 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
722 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);