2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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/>.
21 import java.util.List;
24 import java.awt.event.*;
27 import javax.swing.tree.DefaultMutableTreeNode;
29 import com.stevesoft.pat.Regex;
31 import jalview.datamodel.*;
33 import jalview.util.DBRefUtils;
34 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
35 import jalview.ws.seqfetcher.DbSourceProxy;
36 import java.awt.BorderLayout;
38 public class SequenceFetcher extends JPanel implements Runnable
40 // ASequenceFetcher sfetch;
43 IProgressIndicator guiWindow;
45 AlignFrame alignFrame;
49 final String noDbSelected = "-- Select Database --";
51 private static jalview.ws.SequenceFetcher sfetch = null;
53 private static long lastDasSourceRegistry = -3;
55 private static DasSourceRegistryI dasRegistry = null;
57 private static boolean _initingFetcher = false;
59 private static Thread initingThread = null;
62 * Blocking method that initialises and returns the shared instance of the
63 * SequenceFetcher client
66 * - where the initialisation delay message should be shown
67 * @return the singleton instance of the sequence fetcher client
69 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
70 final IProgressIndicator guiWindow)
72 if (_initingFetcher && initingThread != null && initingThread.isAlive())
74 if (guiWindow != null)
76 guiWindow.setProgressBar(
77 "Waiting for Sequence Database Fetchers to initialise",
78 Thread.currentThread().hashCode());
80 // initting happening on another thread - so wait around to see if it
82 while (_initingFetcher && initingThread != null
83 && initingThread.isAlive())
93 if (guiWindow != null)
95 guiWindow.setProgressBar(
96 "Waiting for Sequence Database Fetchers to initialise",
97 Thread.currentThread().hashCode());
101 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
102 || lastDasSourceRegistry != (jalview.bin.Cache
103 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
104 .getDasSourceRegistry().getLocalSourceString())
107 _initingFetcher = true;
108 initingThread = Thread.currentThread();
110 * give a visual indication that sequence fetcher construction is occuring
112 if (guiWindow != null)
114 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
115 Thread.currentThread().hashCode());
117 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
118 dasRegistry.refreshSources();
120 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
121 if (guiWindow != null)
123 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
124 Thread.currentThread().hashCode());
126 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
127 .getLocalSourceString()).hashCode();
129 _initingFetcher = false;
130 initingThread = null;
135 public SequenceFetcher(IProgressIndicator guiIndic)
137 final IProgressIndicator guiWindow = guiIndic;
138 final SequenceFetcher us = this;
139 // launch initialiser thread
140 Thread sf = new Thread(new Runnable()
146 if (getSequenceFetcherSingleton(guiWindow) != null)
148 us.initGui(guiWindow);
152 javax.swing.SwingUtilities.invokeLater(new Runnable()
158 .showInternalMessageDialog(
160 "Could not create the sequence fetcher client. Check error logs for details.",
161 "Couldn't create SequenceFetcher",
162 JOptionPane.ERROR_MESSAGE);
166 // raise warning dialog
173 private class DatabaseAuthority extends DefaultMutableTreeNode
178 private class DatabaseSource extends DefaultMutableTreeNode
184 * called by thread spawned by constructor
188 private void initGui(IProgressIndicator guiWindow)
190 this.guiWindow = guiWindow;
191 if (guiWindow instanceof AlignFrame)
193 alignFrame = (AlignFrame) guiWindow;
195 database = new JDatabaseTree(sfetch);
199 } catch (Exception ex)
201 ex.printStackTrace();
204 frame = new JInternalFrame();
205 frame.setContentPane(this);
206 if (new jalview.util.Platform().isAMac())
208 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
212 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
216 private String getFrameTitle()
218 return ((alignFrame == null) ? "New " : "Additional ")
219 + "Sequence Fetcher";
222 private void jbInit() throws Exception
224 this.setLayout(borderLayout2);
226 database.setFont(JvSwingUtils.getLabelFont());
227 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
228 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
229 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
230 jLabel1.setText("Separate multiple accession ids with semi colon \";\"");
232 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
234 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
235 replacePunctuation.setText("Replace commas with semi-colons");
237 ok.addActionListener(new ActionListener()
240 public void actionPerformed(ActionEvent e)
242 ok_actionPerformed();
245 clear.setText("Clear");
246 clear.addActionListener(new ActionListener()
249 public void actionPerformed(ActionEvent e)
251 clear_actionPerformed();
255 example.setText("Example");
256 example.addActionListener(new ActionListener()
259 public void actionPerformed(ActionEvent e)
261 example_actionPerformed();
264 close.setText("Close");
265 close.addActionListener(new ActionListener()
268 public void actionPerformed(ActionEvent e)
270 close_actionPerformed(e);
273 textArea.setFont(JvSwingUtils.getLabelFont());
274 textArea.setLineWrap(true);
275 textArea.addKeyListener(new KeyAdapter()
278 public void keyPressed(KeyEvent e)
280 if (e.getKeyCode() == KeyEvent.VK_ENTER)
281 ok_actionPerformed();
284 jPanel3.setLayout(borderLayout1);
285 borderLayout1.setVgap(5);
287 jPanel1.add(example);
290 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
291 jPanel2.setLayout(borderLayout3);
292 databaseButt = database.getDatabaseSelectorButton();
293 databaseButt.setFont(JvSwingUtils.getLabelFont());
294 database.addActionListener(new ActionListener()
298 public void actionPerformed(ActionEvent e)
302 databaseButt.setText(database.getSelectedItem()
303 + (database.getSelectedSources().size() > 1 ? " (and "
304 + database.getSelectedSources().size()
306 String eq = database.getExampleQueries();
307 dbeg.setText("Example query: " + eq);
308 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
309 for (DbSourceProxy dbs : database.getSelectedSources())
311 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
317 replacePunctuation.setEnabled(enablePunct);
319 } catch (Exception ex)
322 replacePunctuation.setEnabled(true);
328 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
329 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
330 JPanel jPanel2a = new JPanel(new BorderLayout());
331 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
332 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
333 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
334 // jPanel2.setPreferredSize(new Dimension())
335 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
336 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
337 this.add(jPanel3, java.awt.BorderLayout.CENTER);
338 this.add(jPanel2, java.awt.BorderLayout.NORTH);
339 jScrollPane1.getViewport().add(textArea);
343 protected void example_actionPerformed()
345 DbSourceProxy db = null;
348 textArea.setText(database.getExampleQueries());
349 } catch (Exception ex)
355 protected void clear_actionPerformed()
357 textArea.setText("");
361 JLabel dbeg = new JLabel();
363 JDatabaseTree database;
365 JButton databaseButt;
367 JLabel jLabel1 = new JLabel();
369 JCheckBox replacePunctuation = new JCheckBox();
371 JButton ok = new JButton();
373 JButton clear = new JButton();
375 JButton example = new JButton();
377 JButton close = new JButton();
379 JPanel jPanel1 = new JPanel();
381 JTextArea textArea = new JTextArea();
383 JScrollPane jScrollPane1 = new JScrollPane();
385 JPanel jPanel2 = new JPanel();
387 JPanel jPanel3 = new JPanel();
389 JPanel jPanel4 = new JPanel();
391 BorderLayout borderLayout1 = new BorderLayout();
393 BorderLayout borderLayout2 = new BorderLayout();
395 BorderLayout borderLayout3 = new BorderLayout();
397 public void close_actionPerformed(ActionEvent e)
401 frame.setClosed(true);
402 } catch (Exception ex)
407 public void ok_actionPerformed()
409 database.setEnabled(false);
410 textArea.setEnabled(false);
411 ok.setEnabled(false);
412 close.setEnabled(false);
414 Thread worker = new Thread(this);
418 private void resetDialog()
420 database.setEnabled(true);
421 textArea.setEnabled(true);
423 close.setEnabled(true);
430 if (!database.hasSelection())
432 error += "Please select the source database\n";
434 // TODO: make this transformation more configurable
435 com.stevesoft.pat.Regex empty;
436 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
438 empty = new com.stevesoft.pat.Regex(
439 // replace commas and spaces with a semicolon
440 "(\\s|[,; ])+", ";");
444 // just turn spaces and semicolons into single semicolons
445 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
447 textArea.setText(empty.replaceAll(textArea.getText()));
448 // see if there's anthing to search with
449 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
452 error += "Please enter a (semi-colon separated list of) database id(s)";
454 if (error.length() > 0)
456 showErrorMessage(error);
460 // indicate if successive sources should be merged into one alignment.
461 boolean addToLast = false;
462 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
463 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
464 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
467 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
469 Iterator<String> en = Arrays.asList(new String[0]).iterator();
470 int nqueries = qries.length;
471 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
473 if (!en.hasNext() && nextfetch.size() > 0)
475 en = nextfetch.iterator();
476 nqueries = nextfetch.size();
477 // save the remaining queries in the original array
478 qries = nextfetch.toArray(new String[nqueries]);
479 nextfetch = new ArrayList<String>();
482 DbSourceProxy proxy = proxies.next();
483 boolean isAliSource = false;
487 guiWindow.setProgressBar("Fetching " + nqueries
488 + " sequence queries from " + proxy.getDbName(), Thread
489 .currentThread().hashCode());
490 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
491 if (proxy.getAccessionSeparator() == null)
495 String item = en.next();
502 // give the server a chance to breathe
504 } catch (Exception e)
511 AlignmentI indres = null;
514 indres = proxy.getSequenceRecords(item);
515 } catch (OutOfMemoryError oome)
517 new OOMWarning("fetching " + item + " from "
518 + proxy.getDbName(), oome, this);
529 } catch (Exception e)
531 jalview.bin.Cache.log.info("Error retrieving " + item
532 + " from " + proxy.getDbName(), e);
539 StringBuffer multiacc = new StringBuffer();
540 ArrayList<String> tosend = new ArrayList<String>();
543 String nel = en.next();
545 multiacc.append(nel);
548 multiacc.append(proxy.getAccessionSeparator());
555 List<String> nores = new ArrayList<String>();
556 rslt = proxy.getSequenceRecords(multiacc.toString());
557 if (rslt == null || rslt.getHeight() == 0)
559 // no results - pass on all queries to next source
560 nextfetch.addAll(tosend);
564 aresultq.add(multiacc.toString());
567 rs = rslt.getSequencesArray();
568 // search for each query in the dbrefs associated with each
571 // ones we do not find will be used to query next source (if any)
572 for (String q : tosend)
574 DBRefEntry dbr = new DBRefEntry(), found[] = null;
575 dbr.setSource(proxy.getDbSource());
576 dbr.setVersion(null);
577 if (proxy.getAccessionValidator() != null)
579 Regex vgr = proxy.getAccessionValidator();
581 if (vgr.numSubs() > 0)
583 dbr.setAccessionId(vgr.stringMatched(1));
587 dbr.setAccessionId(vgr.stringMatched());
592 dbr.setAccessionId(q);
594 boolean rfound = false;
595 for (int r = 0; r < rs.length; r++)
598 && (found = DBRefUtils.searchRefs(
599 rs[r].getDBRef(), dbr)) != null
613 } catch (OutOfMemoryError oome)
615 new OOMWarning("fetching " + multiacc + " from "
616 + database.getSelectedItem(), oome, this);
620 } catch (Exception e)
622 showErrorMessage("Error retrieving " + textArea.getText()
623 + " from " + database.getSelectedItem());
625 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
626 System.err.println("Retrieval failed for source ='"
627 + database.getSelectedItem() + "' and query\n'"
628 + textArea.getText() + "'\n");
630 } catch (OutOfMemoryError e)
632 // resets dialog box - so we don't use OOMwarning here.
633 showErrorMessage("Out of Memory when retrieving "
636 + database.getSelectedItem()
637 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
641 showErrorMessage("Serious Error retrieving " + textArea.getText()
642 + " from " + database.getSelectedItem());
645 // Stack results ready for opening in alignment windows
646 if (aresult != null && aresult.size() > 0)
648 AlignmentI ar = null;
652 // new window for each result
653 while (aresult.size() > 0)
655 presult.add(aresult.remove(0));
656 presultTitle.add(aresultq.remove(0) + " "
657 + getDefaultRetrievalTitle());
663 if (addToLast && presult.size() > 0)
665 ar = presult.remove(presult.size() - 1);
666 titl = presultTitle.remove(presultTitle.size() - 1);
668 // concatenate all results in one window
669 while (aresult.size() > 0)
673 ar = aresult.remove(0);
677 ar.append(aresult.remove(0));
683 presultTitle.add(titl);
686 guiWindow.setProgressBar("Finished querying", Thread.currentThread()
689 guiWindow.setProgressBar((presult.size() > 0) ? "Parsing results."
690 : "Processing ..", Thread.currentThread().hashCode());
692 while (presult.size() > 0)
694 parseResult(presult.remove(0), presultTitle.remove(0), null);
696 // only remove visual delay after we finished parsing.
697 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
698 if (nextfetch.size() > 0)
700 StringBuffer sb = new StringBuffer();
701 sb.append("Didn't retrieve the following "
702 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
703 + " queries") + ": \n");
704 int l = sb.length(), lr = 0;
705 for (String s : nextfetch)
707 if (l != sb.length())
711 if (lr - sb.length() > 40)
717 showErrorMessage(sb.toString());
722 AlignmentI parseResult(String result, String title)
724 String format = new IdentifyFile().Identify(result, "Paste");
725 Alignment sequences = null;
726 if (FormatAdapter.isValidFormat(format))
731 sequences = new FormatAdapter().readFile(result.toString(),
733 } catch (Exception ex)
737 if (sequences != null)
739 return parseResult(sequences, title, format);
744 showErrorMessage("Error retrieving " + textArea.getText() + " from "
745 + database.getSelectedItem());
753 * @return a standard title for any results retrieved using the currently
754 * selected source and settings
756 public String getDefaultRetrievalTitle()
758 return "Retrieved from " + database.getSelectedItem();
761 AlignmentI parseResult(AlignmentI al, String title,
762 String currentFileFormat)
765 if (al != null && al.getHeight() > 0)
767 if (alignFrame == null)
769 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
770 AlignFrame.DEFAULT_HEIGHT);
771 if (currentFileFormat != null)
773 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
775 // NON-FormatAdapter Sourced
781 title = getDefaultRetrievalTitle();
783 SequenceFeature[] sfs = null;
784 List<SequenceI> alsqs;
785 synchronized (alsqs = al.getSequences())
787 for (SequenceI sq : alsqs)
789 if ((sfs = (sq).getDatasetSequence().getSequenceFeatures()) != null)
793 af.setShowSeqFeatures(true);
800 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
801 AlignFrame.DEFAULT_HEIGHT);
803 af.statusBar.setText("Successfully pasted alignment file");
807 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
809 } catch (Exception ex)
815 for (int i = 0; i < al.getHeight(); i++)
817 alignFrame.viewport.getAlignment().addSequence(
818 al.getSequenceAt(i)); // this
825 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
827 alignFrame.viewport.getAlignment().getWidth();
828 alignFrame.viewport.firePropertyChange("alignment", null,
829 alignFrame.viewport.getAlignment().getSequences());
835 void showErrorMessage(final String error)
838 javax.swing.SwingUtilities.invokeLater(new Runnable()
843 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
844 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);