2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
24 import java.awt.event.*;
29 import jalview.datamodel.*;
30 import jalview.datamodel.xdb.embl.*;
33 import jalview.ws.DBRefFetcher;
34 import jalview.ws.ebi.EBIFetchClient;
35 import jalview.ws.seqfetcher.ASequenceFetcher;
36 import jalview.ws.seqfetcher.DbSourceProxy;
38 import java.awt.Rectangle;
39 import java.awt.BorderLayout;
40 import java.awt.Dimension;
42 public class SequenceFetcher extends JPanel implements Runnable
44 // ASequenceFetcher sfetch;
47 IProgressIndicator guiWindow;
49 AlignFrame alignFrame;
53 final String noDbSelected = "-- Select Database --";
55 Hashtable sources = new Hashtable();
57 private static jalview.ws.SequenceFetcher sfetch = null;
59 private static String dasRegistry = null;
60 private static boolean _initingFetcher=false;
61 private static Thread initingThread=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)
73 if (_initingFetcher && initingThread!=null && initingThread.isAlive())
75 if (guiWindow != null)
77 guiWindow.setProgressBar("Waiting for Sequence Database Fetchers to initialise",
78 Thread.currentThread().hashCode());
80 // initting happening on another thread - so wait around to see if it finishes.
81 while (_initingFetcher && initingThread!=null && initingThread.isAlive())
83 try {Thread.sleep(10);} catch (Exception e){};
85 if (guiWindow != null)
87 guiWindow.setProgressBar("Waiting for Sequence Database Fetchers to initialise",
88 Thread.currentThread().hashCode());
92 || dasRegistry != DasSourceBrowser.getDasRegistryURL())
95 initingThread=Thread.currentThread();
97 * give a visual indication that sequence fetcher construction is occuring
99 if (guiWindow != null)
101 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
102 Thread.currentThread().hashCode());
104 dasRegistry = DasSourceBrowser.getDasRegistryURL();
105 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
106 if (guiWindow != null)
108 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
109 initingThread.hashCode());
112 _initingFetcher=false;
118 public SequenceFetcher(IProgressIndicator guiIndic)
120 final IProgressIndicator guiWindow = guiIndic;
121 final SequenceFetcher us = this;
122 // launch initialiser thread
123 Thread sf = new Thread(new Runnable()
128 if (getSequenceFetcherSingleton(guiWindow) != null)
130 us.initGui(guiWindow);
134 javax.swing.SwingUtilities.invokeLater(new Runnable()
139 .showInternalMessageDialog(
141 "Could not create the sequence fetcher client. Check error logs for details.",
142 "Couldn't create SequenceFetcher",
143 JOptionPane.ERROR_MESSAGE);
147 // raise warning dialog
155 * called by thread spawned by constructor
159 private void initGui(IProgressIndicator guiWindow)
161 this.guiWindow = guiWindow;
162 if (guiWindow instanceof AlignFrame)
164 alignFrame = (AlignFrame) guiWindow;
167 database.addItem(noDbSelected);
169 * Dynamically generated database list will need a translation function from
170 * internal source to externally distinct names. UNIPROT and UP_NAME are
171 * identical DB sources, and should be collapsed.
174 String dbs[] = sfetch.getOrderedSupportedSources();
175 for (int i = 0; i < dbs.length; i++)
177 if (!sources.containsValue(dbs[i]))
179 String name = sfetch.getSourceProxy(dbs[i]).getDbName();
180 // duplicate source names are thrown away, here.
181 if (!sources.containsKey(name))
183 database.addItem(name);
185 // overwrite with latest version of the retriever for this source
186 sources.put(name, dbs[i]);
192 } catch (Exception ex)
194 ex.printStackTrace();
197 frame = new JInternalFrame();
198 frame.setContentPane(this);
199 if (new jalview.util.Platform().isAMac())
201 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
205 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
209 private String getFrameTitle()
211 return ((alignFrame == null) ? "New " : "Additional ")
212 + "Sequence Fetcher";
215 private void jbInit() throws Exception
217 this.setLayout(borderLayout2);
219 database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
220 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
221 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
222 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
224 .setText("Separate multiple accession ids with semi colon \";\"");
226 ok.addActionListener(new ActionListener()
228 public void actionPerformed(ActionEvent e)
230 ok_actionPerformed();
233 clear.setText("Clear");
234 clear.addActionListener(new ActionListener()
236 public void actionPerformed(ActionEvent e)
238 clear_actionPerformed();
242 example.setText("Example");
243 example.addActionListener(new ActionListener()
245 public void actionPerformed(ActionEvent e)
247 example_actionPerformed();
250 close.setText("Close");
251 close.addActionListener(new ActionListener()
253 public void actionPerformed(ActionEvent e)
255 close_actionPerformed(e);
258 textArea.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
259 textArea.setLineWrap(true);
260 textArea.addKeyListener(new KeyAdapter()
262 public void keyPressed(KeyEvent e)
264 if (e.getKeyCode() == KeyEvent.VK_ENTER)
265 ok_actionPerformed();
268 jPanel3.setLayout(borderLayout1);
269 borderLayout1.setVgap(5);
271 jPanel1.add(example);
274 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
275 jPanel2.setLayout(borderLayout3);
277 database.addActionListener(new ActionListener()
280 public void actionPerformed(ActionEvent e)
282 DbSourceProxy db = null;
285 db = sfetch.getSourceProxy((String) sources.get(database
286 .getSelectedItem()));
287 dbeg.setText("Example query: " + db.getTestQuery());
288 } catch (Exception ex)
296 jPanel2.add(database, java.awt.BorderLayout.NORTH);
297 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
298 jPanel2.add(jLabel1, java.awt.BorderLayout.SOUTH);
299 // jPanel2.setPreferredSize(new Dimension())
300 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
301 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
302 this.add(jPanel3, java.awt.BorderLayout.CENTER);
303 this.add(jPanel2, java.awt.BorderLayout.NORTH);
304 jScrollPane1.getViewport().add(textArea);
308 protected void example_actionPerformed()
310 DbSourceProxy db = null;
313 db = sfetch.getSourceProxy((String) sources.get(database
314 .getSelectedItem()));
315 textArea.setText(db.getTestQuery());
316 } catch (Exception ex)
322 protected void clear_actionPerformed()
324 textArea.setText("");
328 JLabel dbeg = new JLabel();
330 JComboBox database = new JComboBox();
332 JLabel jLabel1 = new JLabel();
334 JButton ok = new JButton();
336 JButton clear = new JButton();
338 JButton example = new JButton();
340 JButton close = new JButton();
342 JPanel jPanel1 = new JPanel();
344 JTextArea textArea = new JTextArea();
346 JScrollPane jScrollPane1 = new JScrollPane();
348 JPanel jPanel2 = new JPanel();
350 JPanel jPanel3 = new JPanel();
352 JPanel jPanel4 = new JPanel();
354 BorderLayout borderLayout1 = new BorderLayout();
356 BorderLayout borderLayout2 = new BorderLayout();
358 BorderLayout borderLayout3 = new BorderLayout();
360 public void close_actionPerformed(ActionEvent e)
364 frame.setClosed(true);
365 } catch (Exception ex)
370 public void ok_actionPerformed()
372 database.setEnabled(false);
373 textArea.setEnabled(false);
374 ok.setEnabled(false);
375 close.setEnabled(false);
377 Thread worker = new Thread(this);
381 private void resetDialog()
383 database.setEnabled(true);
384 textArea.setEnabled(true);
386 close.setEnabled(true);
392 if (database.getSelectedItem().equals(noDbSelected))
394 error += "Please select the source database\n";
396 // TODO: make this transformation optional and configurable
397 com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex(
398 "(\\s|[,; ])+", ";"); // \\s+", "");
399 textArea.setText(empty.replaceAll(textArea.getText()));
400 // see if there's anthing to search with
401 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
404 error += "Please enter a (semi-colon separated list of) database id(s)";
406 if (error.length() > 0)
408 showErrorMessage(error);
412 AlignmentI aresult = null;
413 Object source = database.getSelectedItem();
414 Enumeration en = new StringTokenizer(textArea.getText(), ";");
417 guiWindow.setProgressBar("Fetching Sequences from "
418 + database.getSelectedItem(), Thread.currentThread()
420 DbSourceProxy proxy = sfetch.getSourceProxy((String) sources
422 if (proxy.getAccessionSeparator() == null)
424 while (en.hasMoreElements())
426 String item = (String) en.nextElement();
433 // give the server a chance to breathe
435 } catch (Exception e)
442 AlignmentI indres = null;
445 indres = proxy.getSequenceRecords(item);
446 } catch (OutOfMemoryError oome)
449 "fetching " + item + " from "
450 + database.getSelectedItem(),oome,
461 aresult.append(indres);
464 } catch (Exception e)
466 jalview.bin.Cache.log.info("Error retrieving " + item
467 + " from " + source, e);
473 StringBuffer multiacc = new StringBuffer();
474 while (en.hasMoreElements())
476 multiacc.append(en.nextElement());
477 if (en.hasMoreElements())
479 multiacc.append(proxy.getAccessionSeparator());
484 aresult = proxy.getSequenceRecords(multiacc.toString());
485 } catch (OutOfMemoryError oome)
488 "fetching " + multiacc + " from "
489 + database.getSelectedItem(),oome,
496 } catch (Exception e)
498 showErrorMessage("Error retrieving " + textArea.getText() + " from "
499 + database.getSelectedItem());
500 // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
501 System.err.println("Retrieval failed for source ='"
502 + database.getSelectedItem() + "' and query\n'"
503 + textArea.getText() + "'\n");
505 } catch (OutOfMemoryError e)
507 // resets dialog box - so we don't use OOMwarning here.
508 showErrorMessage("Out of Memory when retrieving "
511 + database.getSelectedItem()
512 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
516 showErrorMessage("Serious Error retrieving " + textArea.getText()
517 + " from " + database.getSelectedItem());
522 parseResult(aresult, null, null);
524 // only remove visual delay after we finished parsing.
525 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
530 * result = new StringBuffer(); if
531 * (database.getSelectedItem().equals("Uniprot")) {
532 * getUniprotFile(textArea.getText()); } else if
533 * (database.getSelectedItem().equals("EMBL") ||
534 * database.getSelectedItem().equals("EMBLCDS")) { String DBRefSource =
535 * database.getSelectedItem().equals("EMBLCDS") ?
536 * jalview.datamodel.DBRefSource.EMBLCDS : jalview.datamodel.DBRefSource.EMBL;
538 * StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
539 * SequenceI[] seqs = null; while(st.hasMoreTokens()) { EBIFetchClient dbFetch
540 * = new EBIFetchClient(); String qry =
541 * database.getSelectedItem().toString().toLowerCase( ) + ":" +
542 * st.nextToken(); File reply = dbFetch.fetchDataAsFile( qry, "emblxml",null);
544 * jalview.datamodel.xdb.embl.EmblFile efile=null; if (reply != null &&
545 * reply.exists()) { efile =
546 * jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply); } if (efile!=null)
547 * { for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) { EmblEntry
548 * entry = (EmblEntry) i.next(); SequenceI[] seqparts =
549 * entry.getSequences(false,true, DBRefSource); if (seqparts!=null) {
550 * SequenceI[] newseqs = null; int si=0; if (seqs==null) { newseqs = new
551 * SequenceI[seqparts.length]; } else { newseqs = new
552 * SequenceI[seqs.length+seqparts.length];
554 * for (;si<seqs.length; si++) { newseqs[si] = seqs[si]; seqs[si] = null; } }
555 * for (int j=0;j<seqparts.length; si++, j++) { newseqs[si] =
556 * seqparts[j].deriveSequence(); // place DBReferences on dataset and refer }
557 * seqs=newseqs; } } } else { result.append("# no response for "+qry); } } if
558 * (seqs!=null && seqs.length>0) { if (parseResult(new Alignment(seqs), null,
559 * null)!=null) { result.append("# Successfully parsed the
560 * "+database.getSelectedItem()+" Queries into an Alignment"); } } } else if
561 * (database.getSelectedItem().equals("PDB")) { StringTokenizer qset = new
562 * StringTokenizer(textArea.getText(), ";"); String query; SequenceI[] seqs =
563 * null; while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null)) {
564 * SequenceI[] seqparts = getPDBFile(query.toUpperCase()); if (seqparts !=
565 * null) { if (seqs == null) { seqs = seqparts; } else { SequenceI[] newseqs =
566 * new SequenceI[seqs.length+seqparts.length]; int i=0; for (; i <
567 * seqs.length; i++) { newseqs[i] = seqs[i]; seqs[i] = null; } for (int
568 * j=0;j<seqparts.length; i++, j++) { newseqs[i] = seqparts[j]; }
569 * seqs=newseqs; } result.append("# Success for "+query.toUpperCase()+"\n"); }
570 * } if (seqs != null && seqs.length > 0) { if (parseResult(new
571 * Alignment(seqs), null, null)!=null) { result.append( "# Successfully parsed
572 * the PDB File Queries into an
573 * Alignment"); } } } else if( database.getSelectedItem().equals("PFAM")) {
574 * try { result.append(new FastaFile(
575 * "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc=" +
576 * textArea.getText().toUpperCase(), "URL").print() );
578 * if(result.length()>0) { parseResult( result.toString(),
579 * textArea.getText().toUpperCase() ); } } catch (java.io.IOException ex) {
582 * if (result == null || result.length() == 0) { showErrorMessage("Error
583 * retrieving " + textArea.getText() + " from " + database.getSelectedItem());
586 * resetDialog(); return; }
588 * void getUniprotFile(String id) { EBIFetchClient ebi = new EBIFetchClient();
589 * File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
591 * DBRefFetcher dbref = new DBRefFetcher(); Vector entries =
592 * dbref.getUniprotEntries(file);
594 * if (entries != null) { //First, make the new sequences Enumeration en =
595 * entries.elements(); while (en.hasMoreElements()) { UniprotEntry entry =
596 * (UniprotEntry) en.nextElement();
598 * StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot"); Enumeration
599 * en2 = entry.getAccession().elements(); while (en2.hasMoreElements()) {
600 * name.append("|"); name.append(en2.nextElement()); } en2 =
601 * entry.getName().elements(); while (en2.hasMoreElements()) {
602 * name.append("|"); name.append(en2.nextElement()); }
604 * if (entry.getProtein() != null) { name.append(" " +
605 * entry.getProtein().getName().elementAt(0)); }
607 * result.append(name + "\n" + entry.getUniprotSequence().getContent() +
610 * //Then read in the features and apply them to the dataset Alignment al =
611 * parseResult(result.toString(), null); for (int i = 0; i < entries.size();
612 * i++) { UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
613 * Enumeration e = entry.getDbReference().elements(); Vector onlyPdbEntries =
614 * new Vector(); while (e.hasMoreElements()) { PDBEntry pdb = (PDBEntry)
615 * e.nextElement(); if (!pdb.getType().equals("PDB")) { continue; }
617 * onlyPdbEntries.addElement(pdb); }
619 * Enumeration en2 = entry.getAccession().elements(); while
620 * (en2.hasMoreElements()) {
621 * al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
622 * DBRefSource.UNIPROT, "0", en2.nextElement().toString())); }
627 * al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries); if
628 * (entry.getFeature() != null) { e = entry.getFeature().elements(); while
629 * (e.hasMoreElements()) { SequenceFeature sf = (SequenceFeature)
630 * e.nextElement(); sf.setFeatureGroup("Uniprot");
631 * al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf ); } } } }
634 * SequenceI[] getPDBFile(String id) { Vector result = new Vector(); String
635 * chain = null; if (id.indexOf(":") > -1) { chain =
636 * id.substring(id.indexOf(":") + 1); id = id.substring(0, id.indexOf(":")); }
638 * EBIFetchClient ebi = new EBIFetchClient(); String file =
639 * ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw"). getAbsolutePath(); if (file
640 * == null) { return null; } try { PDBfile pdbfile = new PDBfile(file,
641 * jalview.io.AppletFormatAdapter.FILE); for (int i = 0; i <
642 * pdbfile.chains.size(); i++) { if (chain == null || ( (PDBChain)
643 * pdbfile.chains.elementAt(i)).id. toUpperCase().equals(chain)) { PDBChain
644 * pdbchain = (PDBChain) pdbfile.chains.elementAt(i); // Get the Chain's
645 * Sequence - who's dataset includes any special features added from the PDB
646 * file SequenceI sq = pdbchain.sequence; // Specially formatted name for the
647 * PDB chain sequences retrieved from the PDB
648 * sq.setName("PDB|"+id+"|"+sq.getName()); // Might need to add more metadata
649 * to the PDBEntry object // like below /* PDBEntry entry = new PDBEntry(); //
650 * Construct the PDBEntry entry.setId(id); if (entry.getProperty() == null)
651 * entry.setProperty(new Hashtable()); entry.getProperty().put("chains",
652 * pdbchain.id + "=" + sq.getStart() + "-" + sq.getEnd());
653 * sq.getDatasetSequence().addPDBId(entry); // Add PDB DB Refs // We make a
654 * DBRefEtntry because we have obtained the PDB file from a verifiable source
655 * // JBPNote - PDB DBRefEntry should also carry the chain and mapping
656 * information DBRefEntry dbentry = new
657 * DBRefEntry(jalview.datamodel.DBRefSource.PDB, "0", id + pdbchain.id);
658 * sq.addDBRef(dbentry); // and add seuqence to the retrieved set
659 * result.addElement(sq.deriveSequence()); } }
661 * if (result.size() < 1) { throw new Exception("WsDBFetch for PDB id resulted
662 * in zero result size"); } } catch (Exception ex) // Problem parsing PDB file
663 * { jalview.bin.Cache.log.warn("Exception when retrieving " +
664 * textArea.getText() + " from " + database.getSelectedItem(), ex); return
668 * SequenceI[] results = new SequenceI[result.size()]; for (int i = 0, j =
669 * result.size(); i < j; i++) { results[i] = (SequenceI) result.elementAt(i);
670 * result.setElementAt(null,i); } return results; }
672 AlignmentI parseResult(String result, String title)
674 String format = new IdentifyFile().Identify(result, "Paste");
675 Alignment sequences = null;
676 if (FormatAdapter.isValidFormat(format))
681 sequences = new FormatAdapter().readFile(result.toString(),
683 } catch (Exception ex)
687 if (sequences != null)
689 return parseResult(sequences, title, format);
694 showErrorMessage("Error retrieving " + textArea.getText() + " from "
695 + database.getSelectedItem());
701 AlignmentI parseResult(AlignmentI al, String title,
702 String currentFileFormat)
705 if (al != null && al.getHeight() > 0)
707 if (alignFrame == null)
709 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
710 AlignFrame.DEFAULT_HEIGHT);
711 if (currentFileFormat != null)
713 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
715 // NON-FormatAdapter Sourced
721 title = "Retrieved from " + database.getSelectedItem();
723 SequenceFeature[] sfs = null;
724 for (Enumeration sq = al.getSequences().elements(); sq
727 if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
728 .getSequenceFeatures()) != null)
732 af.setShowSeqFeatures(true);
738 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
739 AlignFrame.DEFAULT_HEIGHT);
741 af.statusBar.setText("Successfully pasted alignment file");
745 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
747 } catch (Exception ex)
753 for (int i = 0; i < al.getHeight(); i++)
755 alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this
762 alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment
764 alignFrame.viewport.alignment.getWidth();
765 alignFrame.viewport.firePropertyChange("alignment", null,
766 alignFrame.viewport.getAlignment().getSequences());
772 void showErrorMessage(final String error)
775 javax.swing.SwingUtilities.invokeLater(new Runnable()
779 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
780 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);