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()) {
310 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
316 replacePunctuation.setEnabled(enablePunct);
318 } catch (Exception ex)
321 replacePunctuation.setEnabled(true);
327 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
328 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
329 JPanel jPanel2a = new JPanel(new BorderLayout());
330 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
331 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
332 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
333 // jPanel2.setPreferredSize(new Dimension())
334 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
335 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
336 this.add(jPanel3, java.awt.BorderLayout.CENTER);
337 this.add(jPanel2, java.awt.BorderLayout.NORTH);
338 jScrollPane1.getViewport().add(textArea);
342 protected void example_actionPerformed()
344 DbSourceProxy db = null;
347 textArea.setText(database.getExampleQueries());
348 } catch (Exception ex)
354 protected void clear_actionPerformed()
356 textArea.setText("");
360 JLabel dbeg = new JLabel();
362 JDatabaseTree database;
364 JButton databaseButt;
366 JLabel jLabel1 = new JLabel();
368 JCheckBox replacePunctuation = new JCheckBox();
370 JButton ok = new JButton();
372 JButton clear = new JButton();
374 JButton example = new JButton();
376 JButton close = new JButton();
378 JPanel jPanel1 = new JPanel();
380 JTextArea textArea = new JTextArea();
382 JScrollPane jScrollPane1 = new JScrollPane();
384 JPanel jPanel2 = new JPanel();
386 JPanel jPanel3 = new JPanel();
388 JPanel jPanel4 = new JPanel();
390 BorderLayout borderLayout1 = new BorderLayout();
392 BorderLayout borderLayout2 = new BorderLayout();
394 BorderLayout borderLayout3 = new BorderLayout();
396 public void close_actionPerformed(ActionEvent e)
400 frame.setClosed(true);
401 } catch (Exception ex)
406 public void ok_actionPerformed()
408 databaseButt.setEnabled(false);
409 example.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 databaseButt.setEnabled(true);
421 example.setEnabled(true);
422 textArea.setEnabled(true);
424 close.setEnabled(true);
431 if (!database.hasSelection())
433 error += "Please select the source database\n";
435 // TODO: make this transformation more configurable
436 com.stevesoft.pat.Regex empty;
437 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
439 empty = new com.stevesoft.pat.Regex(
440 // replace commas and spaces with a semicolon
441 "(\\s|[,; ])+", ";");
445 // just turn spaces and semicolons into single semicolons
446 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
448 textArea.setText(empty.replaceAll(textArea.getText()));
449 // see if there's anthing to search with
450 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
453 error += "Please enter a (semi-colon separated list of) database id(s)";
455 if (error.length() > 0)
457 showErrorMessage(error);
461 // indicate if successive sources should be merged into one alignment.
462 boolean addToLast=false;
463 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
464 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
465 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
468 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
470 Iterator<String> en = Arrays.asList(new String[0]).iterator();
471 int nqueries = qries.length;
472 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
474 if (!en.hasNext() && nextfetch.size() > 0)
476 en = nextfetch.iterator();
477 nqueries = nextfetch.size();
478 // save the remaining queries in the original array
479 qries = nextfetch.toArray(new String[nqueries]);
480 nextfetch = new ArrayList<String>();
483 DbSourceProxy proxy = proxies.next();
484 boolean isAliSource = false;
488 guiWindow.setProgressBar("Fetching " + nqueries
489 + " sequence queries from " + proxy.getDbName(), Thread
490 .currentThread().hashCode());
491 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
492 if (proxy.getAccessionSeparator() == null)
496 String item = en.next();
503 // give the server a chance to breathe
505 } catch (Exception e)
512 AlignmentI indres = null;
515 indres = proxy.getSequenceRecords(item);
516 } catch (OutOfMemoryError oome)
518 new OOMWarning("fetching " + item + " from "
519 + proxy.getDbName(), oome, this);
530 } catch (Exception e)
532 jalview.bin.Cache.log.info("Error retrieving " + item
533 + " from " + proxy.getDbName(), e);
540 StringBuffer multiacc = new StringBuffer();
541 ArrayList<String> tosend = new ArrayList<String>();
544 String nel = en.next();
546 multiacc.append(nel);
549 multiacc.append(proxy.getAccessionSeparator());
556 List<String> nores = new ArrayList<String>();
557 rslt = proxy.getSequenceRecords(multiacc.toString());
558 if (rslt == null || rslt.getHeight() == 0)
560 // no results - pass on all queries to next source
561 nextfetch.addAll(tosend);
565 aresultq.add(multiacc.toString());
568 rs = rslt.getSequencesArray();
569 // search for each query in the dbrefs associated with each
572 // ones we do not find will be used to query next source (if any)
573 for (String q : tosend)
575 DBRefEntry dbr = new DBRefEntry(), found[] = null;
576 dbr.setSource(proxy.getDbSource());
577 dbr.setVersion(null);
578 if (proxy.getAccessionValidator()!=null) {
579 Regex vgr=proxy.getAccessionValidator();
581 if (vgr.numSubs()>0) {
582 dbr.setAccessionId(vgr.stringMatched(1));
584 dbr.setAccessionId(vgr.stringMatched());
587 dbr.setAccessionId(q);
589 boolean rfound = false;
590 for (int r = 0; r < rs.length; r++)
593 && (found = DBRefUtils.searchRefs(
594 rs[r].getDBRef(), dbr)) != null
608 } catch (OutOfMemoryError oome)
610 new OOMWarning("fetching " + multiacc + " from "
611 + database.getSelectedItem(), oome, this);
615 } catch (Exception e)
617 showErrorMessage("Error retrieving " + textArea.getText()
618 + " from " + database.getSelectedItem());
620 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
621 System.err.println("Retrieval failed for source ='"
622 + database.getSelectedItem() + "' and query\n'"
623 + textArea.getText() + "'\n");
625 } catch (OutOfMemoryError e)
627 // resets dialog box - so we don't use OOMwarning here.
628 showErrorMessage("Out of Memory when retrieving "
631 + database.getSelectedItem()
632 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
636 showErrorMessage("Serious Error retrieving " + textArea.getText()
637 + " from " + database.getSelectedItem());
640 // Stack results ready for opening in alignment windows
641 if (aresult != null && aresult.size() > 0)
643 AlignmentI ar = null;
647 // new window for each result
648 while (aresult.size() > 0)
650 presult.add(aresult.remove(0));
651 presultTitle.add(aresultq.remove(0) + " "
652 + getDefaultRetrievalTitle());
658 if (addToLast && presult.size()>0)
660 ar=presult.remove(presult.size()-1);
661 titl=presultTitle.remove(presultTitle.size()-1);
663 // concatenate all results in one window
664 while (aresult.size() > 0)
668 ar = aresult.remove(0);
672 ar.append(aresult.remove(0));
678 presultTitle.add(titl);
681 guiWindow.setProgressBar("Finished querying", Thread.currentThread().hashCode());
683 guiWindow.setProgressBar((presult.size()>0) ? "Parsing results.":"Processing ..", Thread.currentThread().hashCode());
685 while (presult.size() > 0)
687 parseResult(presult.remove(0), presultTitle.remove(0), null);
689 // only remove visual delay after we finished parsing.
690 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
691 if (nextfetch.size() > 0)
693 StringBuffer sb = new StringBuffer();
694 sb.append("Didn't retrieve the following "
695 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
696 + " queries") + ": \n");
697 int l = sb.length(),lr=0;
698 for (String s : nextfetch)
700 if (l != sb.length())
704 if (lr-sb.length()>40)
710 showErrorMessage(sb.toString());
715 AlignmentI parseResult(String result, String title)
717 String format = new IdentifyFile().Identify(result, "Paste");
718 Alignment sequences = null;
719 if (FormatAdapter.isValidFormat(format))
724 sequences = new FormatAdapter().readFile(result.toString(),
726 } catch (Exception ex)
730 if (sequences != null)
732 return parseResult(sequences, title, format);
737 showErrorMessage("Error retrieving " + textArea.getText() + " from "
738 + database.getSelectedItem());
746 * @return a standard title for any results retrieved using the currently
747 * selected source and settings
749 public String getDefaultRetrievalTitle()
751 return "Retrieved from " + database.getSelectedItem();
754 AlignmentI parseResult(AlignmentI al, String title,
755 String currentFileFormat)
758 if (al != null && al.getHeight() > 0)
760 if (alignFrame == null)
762 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
763 AlignFrame.DEFAULT_HEIGHT);
764 if (currentFileFormat != null)
766 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
768 // NON-FormatAdapter Sourced
774 title = getDefaultRetrievalTitle();
776 SequenceFeature[] sfs = null;
777 List<SequenceI> alsqs;
778 synchronized (alsqs = al.getSequences())
780 for (SequenceI sq : alsqs)
782 if ((sfs = (sq).getDatasetSequence().getSequenceFeatures()) != null)
786 af.setShowSeqFeatures(true);
793 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
794 AlignFrame.DEFAULT_HEIGHT);
796 af.statusBar.setText("Successfully pasted alignment file");
800 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
802 } catch (Exception ex)
808 for (int i = 0; i < al.getHeight(); i++)
810 alignFrame.viewport.getAlignment().addSequence(
811 al.getSequenceAt(i)); // this
818 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
820 alignFrame.viewport.getAlignment().getWidth();
821 alignFrame.viewport.firePropertyChange("alignment", null,
822 alignFrame.viewport.getAlignment().getSequences());
828 void showErrorMessage(final String error)
831 javax.swing.SwingUtilities.invokeLater(new Runnable()
836 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
837 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);