2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.util.List;
27 import java.awt.event.*;
30 import javax.swing.tree.DefaultMutableTreeNode;
32 import com.stevesoft.pat.Regex;
34 import jalview.datamodel.*;
36 import jalview.util.DBRefUtils;
37 import jalview.util.MessageManager;
38 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
39 import jalview.ws.seqfetcher.DbSourceProxy;
40 import java.awt.BorderLayout;
42 public class SequenceFetcher extends JPanel implements Runnable
44 // ASequenceFetcher sfetch;
47 IProgressIndicator guiWindow;
49 AlignFrame alignFrame;
53 final String noDbSelected = "-- Select Database --";
55 private static jalview.ws.SequenceFetcher sfetch = null;
57 private static long lastDasSourceRegistry = -3;
59 private static DasSourceRegistryI dasRegistry = null;
61 private static boolean _initingFetcher = false;
63 private static Thread initingThread = null;
66 * Blocking method that initialises and returns the shared instance of the
67 * SequenceFetcher client
70 * - where the initialisation delay message should be shown
71 * @return the singleton instance of the sequence fetcher client
73 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
74 final IProgressIndicator guiWindow)
76 if (_initingFetcher && initingThread != null && initingThread.isAlive())
78 if (guiWindow != null)
80 guiWindow.setProgressBar(
81 "Waiting for Sequence Database Fetchers to initialise",
82 Thread.currentThread().hashCode());
84 // initting happening on another thread - so wait around to see if it
86 while (_initingFetcher && initingThread != null
87 && initingThread.isAlive())
97 if (guiWindow != null)
99 guiWindow.setProgressBar(
100 "Waiting for Sequence Database Fetchers to initialise",
101 Thread.currentThread().hashCode());
105 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
106 || lastDasSourceRegistry != (jalview.bin.Cache
107 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
108 .getDasSourceRegistry().getLocalSourceString())
111 _initingFetcher = true;
112 initingThread = Thread.currentThread();
114 * give a visual indication that sequence fetcher construction is occuring
116 if (guiWindow != null)
118 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
119 Thread.currentThread().hashCode());
121 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
122 dasRegistry.refreshSources();
124 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
125 if (guiWindow != null)
127 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
128 Thread.currentThread().hashCode());
130 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
131 .getLocalSourceString()).hashCode();
133 _initingFetcher = false;
134 initingThread = null;
139 public SequenceFetcher(IProgressIndicator guiIndic)
141 final IProgressIndicator guiWindow = guiIndic;
142 final SequenceFetcher us = this;
143 // launch initialiser thread
144 Thread sf = new Thread(new Runnable()
150 if (getSequenceFetcherSingleton(guiWindow) != null)
152 us.initGui(guiWindow);
156 javax.swing.SwingUtilities.invokeLater(new Runnable()
162 .showInternalMessageDialog(
164 "Could not create the sequence fetcher client. Check error logs for details.",
165 "Couldn't create SequenceFetcher",
166 JOptionPane.ERROR_MESSAGE);
170 // raise warning dialog
177 private class DatabaseAuthority extends DefaultMutableTreeNode
182 private class DatabaseSource extends DefaultMutableTreeNode
188 * called by thread spawned by constructor
192 private void initGui(IProgressIndicator guiWindow)
194 this.guiWindow = guiWindow;
195 if (guiWindow instanceof AlignFrame)
197 alignFrame = (AlignFrame) guiWindow;
199 database = new JDatabaseTree(sfetch);
203 } catch (Exception ex)
205 ex.printStackTrace();
208 frame = new JInternalFrame();
209 frame.setContentPane(this);
210 if (new jalview.util.Platform().isAMac())
212 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
216 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
220 private String getFrameTitle()
222 return ((alignFrame == null) ? "New " : "Additional ")
223 + "Sequence Fetcher";
226 private void jbInit() throws Exception
228 this.setLayout(borderLayout2);
230 database.setFont(JvSwingUtils.getLabelFont());
231 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
232 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
233 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
234 jLabel1.setText(MessageManager.getString("label.separate_multiple_accession_ids"));
236 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
238 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
239 replacePunctuation.setText(MessageManager.getString("label.replace_commas_semicolons"));
240 ok.setText(MessageManager.getString("action.ok"));
241 ok.addActionListener(new ActionListener()
244 public void actionPerformed(ActionEvent e)
246 ok_actionPerformed();
249 clear.setText(MessageManager.getString("action.clear"));
250 clear.addActionListener(new ActionListener()
253 public void actionPerformed(ActionEvent e)
255 clear_actionPerformed();
259 example.setText(MessageManager.getString("label.example"));
260 example.addActionListener(new ActionListener()
263 public void actionPerformed(ActionEvent e)
265 example_actionPerformed();
268 close.setText(MessageManager.getString("action.close"));
269 close.addActionListener(new ActionListener()
272 public void actionPerformed(ActionEvent e)
274 close_actionPerformed(e);
277 textArea.setFont(JvSwingUtils.getLabelFont());
278 textArea.setLineWrap(true);
279 textArea.addKeyListener(new KeyAdapter()
282 public void keyPressed(KeyEvent e)
284 if (e.getKeyCode() == KeyEvent.VK_ENTER)
285 ok_actionPerformed();
288 jPanel3.setLayout(borderLayout1);
289 borderLayout1.setVgap(5);
291 jPanel1.add(example);
294 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
295 jPanel2.setLayout(borderLayout3);
296 databaseButt = database.getDatabaseSelectorButton();
297 databaseButt.setFont(JvSwingUtils.getLabelFont());
298 database.addActionListener(new ActionListener()
302 public void actionPerformed(ActionEvent e)
306 databaseButt.setText(database.getSelectedItem()
307 + (database.getSelectedSources().size() > 1 ? " (and "
308 + database.getSelectedSources().size()
310 String eq = database.getExampleQueries();
311 dbeg.setText(MessageManager.formatMessage("label.example_query_param", new String[]{eq}));
312 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
313 for (DbSourceProxy dbs : database.getSelectedSources())
315 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
321 replacePunctuation.setEnabled(enablePunct);
323 } catch (Exception ex)
326 replacePunctuation.setEnabled(true);
332 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
333 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
334 JPanel jPanel2a = new JPanel(new BorderLayout());
335 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
336 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
337 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
338 // jPanel2.setPreferredSize(new Dimension())
339 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
340 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
341 this.add(jPanel3, java.awt.BorderLayout.CENTER);
342 this.add(jPanel2, java.awt.BorderLayout.NORTH);
343 jScrollPane1.getViewport().add(textArea);
347 protected void example_actionPerformed()
349 DbSourceProxy db = null;
352 textArea.setText(database.getExampleQueries());
353 } catch (Exception ex)
359 protected void clear_actionPerformed()
361 textArea.setText("");
365 JLabel dbeg = new JLabel();
367 JDatabaseTree database;
369 JButton databaseButt;
371 JLabel jLabel1 = new JLabel();
373 JCheckBox replacePunctuation = new JCheckBox();
375 JButton ok = new JButton();
377 JButton clear = new JButton();
379 JButton example = new JButton();
381 JButton close = new JButton();
383 JPanel jPanel1 = new JPanel();
385 JTextArea textArea = new JTextArea();
387 JScrollPane jScrollPane1 = new JScrollPane();
389 JPanel jPanel2 = new JPanel();
391 JPanel jPanel3 = new JPanel();
393 JPanel jPanel4 = new JPanel();
395 BorderLayout borderLayout1 = new BorderLayout();
397 BorderLayout borderLayout2 = new BorderLayout();
399 BorderLayout borderLayout3 = new BorderLayout();
401 public void close_actionPerformed(ActionEvent e)
405 frame.setClosed(true);
406 } catch (Exception ex)
411 public void ok_actionPerformed()
413 databaseButt.setEnabled(false);
414 example.setEnabled(false);
415 textArea.setEnabled(false);
416 ok.setEnabled(false);
417 close.setEnabled(false);
419 Thread worker = new Thread(this);
423 private void resetDialog()
425 databaseButt.setEnabled(true);
426 example.setEnabled(true);
427 textArea.setEnabled(true);
429 close.setEnabled(true);
436 if (!database.hasSelection())
438 error += "Please select the source database\n";
440 // TODO: make this transformation more configurable
441 com.stevesoft.pat.Regex empty;
442 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
444 empty = new com.stevesoft.pat.Regex(
445 // replace commas and spaces with a semicolon
446 "(\\s|[,; ])+", ";");
450 // just turn spaces and semicolons into single semicolons
451 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
453 textArea.setText(empty.replaceAll(textArea.getText()));
454 // see if there's anthing to search with
455 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
458 error += "Please enter a (semi-colon separated list of) database id(s)";
460 if (error.length() > 0)
462 showErrorMessage(error);
466 // indicate if successive sources should be merged into one alignment.
467 boolean addToLast = false;
468 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
469 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
470 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
473 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
475 Iterator<String> en = Arrays.asList(new String[0]).iterator();
476 int nqueries = qries.length;
477 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
479 if (!en.hasNext() && nextfetch.size() > 0)
481 en = nextfetch.iterator();
482 nqueries = nextfetch.size();
483 // save the remaining queries in the original array
484 qries = nextfetch.toArray(new String[nqueries]);
485 nextfetch = new ArrayList<String>();
488 DbSourceProxy proxy = proxies.next();
489 boolean isAliSource = false;
493 guiWindow.setProgressBar("Fetching " + nqueries
494 + " sequence queries from " + proxy.getDbName(), Thread
495 .currentThread().hashCode());
496 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
497 if (proxy.getAccessionSeparator() == null)
501 String item = en.next();
508 // give the server a chance to breathe
510 } catch (Exception e)
517 AlignmentI indres = null;
520 indres = proxy.getSequenceRecords(item);
521 } catch (OutOfMemoryError oome)
523 new OOMWarning("fetching " + item + " from "
524 + proxy.getDbName(), oome, this);
535 } catch (Exception e)
537 jalview.bin.Cache.log.info("Error retrieving " + item
538 + " from " + proxy.getDbName(), e);
545 StringBuffer multiacc = new StringBuffer();
546 ArrayList<String> tosend = new ArrayList<String>();
549 String nel = en.next();
551 multiacc.append(nel);
554 multiacc.append(proxy.getAccessionSeparator());
561 List<String> nores = new ArrayList<String>();
562 rslt = proxy.getSequenceRecords(multiacc.toString());
563 if (rslt == null || rslt.getHeight() == 0)
565 // no results - pass on all queries to next source
566 nextfetch.addAll(tosend);
570 aresultq.add(multiacc.toString());
573 rs = rslt.getSequencesArray();
574 // search for each query in the dbrefs associated with each
577 // ones we do not find will be used to query next source (if any)
578 for (String q : tosend)
580 DBRefEntry dbr = new DBRefEntry(), found[] = null;
581 dbr.setSource(proxy.getDbSource());
582 dbr.setVersion(null);
583 if (proxy.getAccessionValidator() != null)
585 Regex vgr = proxy.getAccessionValidator();
587 if (vgr.numSubs() > 0)
589 dbr.setAccessionId(vgr.stringMatched(1));
593 dbr.setAccessionId(vgr.stringMatched());
598 dbr.setAccessionId(q);
600 boolean rfound = false;
601 for (int r = 0; r < rs.length; r++)
604 && (found = DBRefUtils.searchRefs(
605 rs[r].getDBRef(), dbr)) != null
619 } catch (OutOfMemoryError oome)
621 new OOMWarning("fetching " + multiacc + " from "
622 + database.getSelectedItem(), oome, this);
626 } catch (Exception e)
628 showErrorMessage("Error retrieving " + textArea.getText()
629 + " from " + database.getSelectedItem());
631 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
632 System.err.println("Retrieval failed for source ='"
633 + database.getSelectedItem() + "' and query\n'"
634 + textArea.getText() + "'\n");
636 } catch (OutOfMemoryError e)
638 // resets dialog box - so we don't use OOMwarning here.
639 showErrorMessage("Out of Memory when retrieving "
642 + database.getSelectedItem()
643 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
647 showErrorMessage("Serious Error retrieving " + textArea.getText()
648 + " from " + database.getSelectedItem());
651 // Stack results ready for opening in alignment windows
652 if (aresult != null && aresult.size() > 0)
654 AlignmentI ar = null;
658 // new window for each result
659 while (aresult.size() > 0)
661 presult.add(aresult.remove(0));
662 presultTitle.add(aresultq.remove(0) + " "
663 + getDefaultRetrievalTitle());
669 if (addToLast && presult.size() > 0)
671 ar = presult.remove(presult.size() - 1);
672 titl = presultTitle.remove(presultTitle.size() - 1);
674 // concatenate all results in one window
675 while (aresult.size() > 0)
679 ar = aresult.remove(0);
683 ar.append(aresult.remove(0));
689 presultTitle.add(titl);
692 guiWindow.setProgressBar("Finished querying", Thread.currentThread()
695 guiWindow.setProgressBar((presult.size() > 0) ? "Parsing results."
696 : "Processing ..", Thread.currentThread().hashCode());
698 while (presult.size() > 0)
700 parseResult(presult.remove(0), presultTitle.remove(0), null);
702 // only remove visual delay after we finished parsing.
703 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
704 if (nextfetch.size() > 0)
706 StringBuffer sb = new StringBuffer();
707 sb.append("Didn't retrieve the following "
708 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
709 + " queries") + ": \n");
710 int l = sb.length(), lr = 0;
711 for (String s : nextfetch)
713 if (l != sb.length())
717 if (lr - sb.length() > 40)
723 showErrorMessage(sb.toString());
728 AlignmentI parseResult(String result, String title)
730 String format = new IdentifyFile().Identify(result, "Paste");
731 Alignment sequences = null;
732 if (FormatAdapter.isValidFormat(format))
737 sequences = new FormatAdapter().readFile(result.toString(),
739 } catch (Exception ex)
743 if (sequences != null)
745 return parseResult(sequences, title, format);
750 showErrorMessage("Error retrieving " + textArea.getText() + " from "
751 + database.getSelectedItem());
759 * @return a standard title for any results retrieved using the currently
760 * selected source and settings
762 public String getDefaultRetrievalTitle()
764 return "Retrieved from " + database.getSelectedItem();
767 AlignmentI parseResult(AlignmentI al, String title,
768 String currentFileFormat)
771 if (al != null && al.getHeight() > 0)
773 if (alignFrame == null)
775 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
776 AlignFrame.DEFAULT_HEIGHT);
777 if (currentFileFormat != null)
779 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
781 // NON-FormatAdapter Sourced
787 title = getDefaultRetrievalTitle();
789 SequenceFeature[] sfs = null;
790 List<SequenceI> alsqs;
791 synchronized (alsqs = al.getSequences())
793 for (SequenceI sq : alsqs)
795 if ((sfs = (sq).getDatasetSequence().getSequenceFeatures()) != null)
799 af.setShowSeqFeatures(true);
806 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
807 AlignFrame.DEFAULT_HEIGHT);
809 af.statusBar.setText(MessageManager.getString("label.successfully_pasted_alignment_file"));
813 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
815 } catch (Exception ex)
821 for (int i = 0; i < al.getHeight(); i++)
823 alignFrame.viewport.getAlignment().addSequence(
824 al.getSequenceAt(i)); // this
831 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
833 alignFrame.viewport.getAlignment().getWidth();
834 alignFrame.viewport.firePropertyChange("alignment", null,
835 alignFrame.viewport.getAlignment().getSequences());
841 void showErrorMessage(final String error)
844 javax.swing.SwingUtilities.invokeLater(new Runnable()
849 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
850 MessageManager.getString("label.error_retrieving_data"), JOptionPane.WARNING_MESSAGE);