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
235 .getString("label.separate_multiple_accession_ids"));
237 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
239 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
240 replacePunctuation.setText(MessageManager
241 .getString("label.replace_commas_semicolons"));
242 ok.setText(MessageManager.getString("action.ok"));
243 ok.addActionListener(new ActionListener()
246 public void actionPerformed(ActionEvent e)
248 ok_actionPerformed();
251 clear.setText(MessageManager.getString("action.clear"));
252 clear.addActionListener(new ActionListener()
255 public void actionPerformed(ActionEvent e)
257 clear_actionPerformed();
261 example.setText(MessageManager.getString("label.example"));
262 example.addActionListener(new ActionListener()
265 public void actionPerformed(ActionEvent e)
267 example_actionPerformed();
270 close.setText(MessageManager.getString("action.close"));
271 close.addActionListener(new ActionListener()
274 public void actionPerformed(ActionEvent e)
276 close_actionPerformed(e);
279 textArea.setFont(JvSwingUtils.getLabelFont());
280 textArea.setLineWrap(true);
281 textArea.addKeyListener(new KeyAdapter()
284 public void keyPressed(KeyEvent e)
286 if (e.getKeyCode() == KeyEvent.VK_ENTER)
287 ok_actionPerformed();
290 jPanel3.setLayout(borderLayout1);
291 borderLayout1.setVgap(5);
293 jPanel1.add(example);
296 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
297 jPanel2.setLayout(borderLayout3);
298 databaseButt = database.getDatabaseSelectorButton();
299 databaseButt.setFont(JvSwingUtils.getLabelFont());
300 database.addActionListener(new ActionListener()
304 public void actionPerformed(ActionEvent e)
308 databaseButt.setText(database.getSelectedItem()
309 + (database.getSelectedSources().size() > 1 ? " (and "
310 + database.getSelectedSources().size()
312 String eq = database.getExampleQueries();
313 dbeg.setText(MessageManager.formatMessage(
314 "label.example_query_param", new String[]
316 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
317 for (DbSourceProxy dbs : database.getSelectedSources())
319 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
325 replacePunctuation.setEnabled(enablePunct);
327 } catch (Exception ex)
330 replacePunctuation.setEnabled(true);
336 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
337 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
338 JPanel jPanel2a = new JPanel(new BorderLayout());
339 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
340 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
341 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
342 // jPanel2.setPreferredSize(new Dimension())
343 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
344 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
345 this.add(jPanel3, java.awt.BorderLayout.CENTER);
346 this.add(jPanel2, java.awt.BorderLayout.NORTH);
347 jScrollPane1.getViewport().add(textArea);
351 protected void example_actionPerformed()
353 DbSourceProxy db = null;
356 textArea.setText(database.getExampleQueries());
357 } catch (Exception ex)
363 protected void clear_actionPerformed()
365 textArea.setText("");
369 JLabel dbeg = new JLabel();
371 JDatabaseTree database;
373 JButton databaseButt;
375 JLabel jLabel1 = new JLabel();
377 JCheckBox replacePunctuation = new JCheckBox();
379 JButton ok = new JButton();
381 JButton clear = new JButton();
383 JButton example = new JButton();
385 JButton close = new JButton();
387 JPanel jPanel1 = new JPanel();
389 JTextArea textArea = new JTextArea();
391 JScrollPane jScrollPane1 = new JScrollPane();
393 JPanel jPanel2 = new JPanel();
395 JPanel jPanel3 = new JPanel();
397 JPanel jPanel4 = new JPanel();
399 BorderLayout borderLayout1 = new BorderLayout();
401 BorderLayout borderLayout2 = new BorderLayout();
403 BorderLayout borderLayout3 = new BorderLayout();
405 public void close_actionPerformed(ActionEvent e)
409 frame.setClosed(true);
410 } catch (Exception ex)
415 public void ok_actionPerformed()
417 databaseButt.setEnabled(false);
418 example.setEnabled(false);
419 textArea.setEnabled(false);
420 ok.setEnabled(false);
421 close.setEnabled(false);
423 Thread worker = new Thread(this);
427 private void resetDialog()
429 databaseButt.setEnabled(true);
430 example.setEnabled(true);
431 textArea.setEnabled(true);
433 close.setEnabled(true);
440 if (!database.hasSelection())
442 error += "Please select the source database\n";
444 // TODO: make this transformation more configurable
445 com.stevesoft.pat.Regex empty;
446 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
448 empty = new com.stevesoft.pat.Regex(
449 // replace commas and spaces with a semicolon
450 "(\\s|[,; ])+", ";");
454 // just turn spaces and semicolons into single semicolons
455 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
457 textArea.setText(empty.replaceAll(textArea.getText()));
458 // see if there's anthing to search with
459 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
462 error += "Please enter a (semi-colon separated list of) database id(s)";
464 if (error.length() > 0)
466 showErrorMessage(error);
470 // indicate if successive sources should be merged into one alignment.
471 boolean addToLast = false;
472 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
473 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
474 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
477 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
479 Iterator<String> en = Arrays.asList(new String[0]).iterator();
480 int nqueries = qries.length;
481 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
483 if (!en.hasNext() && nextfetch.size() > 0)
485 en = nextfetch.iterator();
486 nqueries = nextfetch.size();
487 // save the remaining queries in the original array
488 qries = nextfetch.toArray(new String[nqueries]);
489 nextfetch = new ArrayList<String>();
492 DbSourceProxy proxy = proxies.next();
493 boolean isAliSource = false;
497 guiWindow.setProgressBar("Fetching " + nqueries
498 + " sequence queries from " + proxy.getDbName(), Thread
499 .currentThread().hashCode());
500 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
501 if (proxy.getAccessionSeparator() == null)
505 String item = en.next();
512 // give the server a chance to breathe
514 } catch (Exception e)
521 AlignmentI indres = null;
524 indres = proxy.getSequenceRecords(item);
525 } catch (OutOfMemoryError oome)
527 new OOMWarning("fetching " + item + " from "
528 + proxy.getDbName(), oome, this);
539 } catch (Exception e)
541 jalview.bin.Cache.log.info("Error retrieving " + item
542 + " from " + proxy.getDbName(), e);
549 StringBuffer multiacc = new StringBuffer();
550 ArrayList<String> tosend = new ArrayList<String>();
553 String nel = en.next();
555 multiacc.append(nel);
558 multiacc.append(proxy.getAccessionSeparator());
565 List<String> nores = new ArrayList<String>();
566 rslt = proxy.getSequenceRecords(multiacc.toString());
567 if (rslt == null || rslt.getHeight() == 0)
569 // no results - pass on all queries to next source
570 nextfetch.addAll(tosend);
574 aresultq.add(multiacc.toString());
577 rs = rslt.getSequencesArray();
578 // search for each query in the dbrefs associated with each
581 // ones we do not find will be used to query next source (if any)
582 for (String q : tosend)
584 DBRefEntry dbr = new DBRefEntry(), found[] = null;
585 dbr.setSource(proxy.getDbSource());
586 dbr.setVersion(null);
587 if (proxy.getAccessionValidator() != null)
589 Regex vgr = proxy.getAccessionValidator();
591 if (vgr.numSubs() > 0)
593 dbr.setAccessionId(vgr.stringMatched(1));
597 dbr.setAccessionId(vgr.stringMatched());
602 dbr.setAccessionId(q);
604 boolean rfound = false;
605 for (int r = 0; r < rs.length; r++)
608 && (found = DBRefUtils.searchRefs(
609 rs[r].getDBRef(), dbr)) != null
623 } catch (OutOfMemoryError oome)
625 new OOMWarning("fetching " + multiacc + " from "
626 + database.getSelectedItem(), oome, this);
630 } catch (Exception e)
632 showErrorMessage("Error retrieving " + textArea.getText()
633 + " from " + database.getSelectedItem());
635 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
636 System.err.println("Retrieval failed for source ='"
637 + database.getSelectedItem() + "' and query\n'"
638 + textArea.getText() + "'\n");
640 } catch (OutOfMemoryError e)
642 // resets dialog box - so we don't use OOMwarning here.
643 showErrorMessage("Out of Memory when retrieving "
646 + database.getSelectedItem()
647 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
651 showErrorMessage("Serious Error retrieving " + textArea.getText()
652 + " from " + database.getSelectedItem());
655 // Stack results ready for opening in alignment windows
656 if (aresult != null && aresult.size() > 0)
658 AlignmentI ar = null;
662 // new window for each result
663 while (aresult.size() > 0)
665 presult.add(aresult.remove(0));
666 presultTitle.add(aresultq.remove(0) + " "
667 + getDefaultRetrievalTitle());
673 if (addToLast && presult.size() > 0)
675 ar = presult.remove(presult.size() - 1);
676 titl = presultTitle.remove(presultTitle.size() - 1);
678 // concatenate all results in one window
679 while (aresult.size() > 0)
683 ar = aresult.remove(0);
687 ar.append(aresult.remove(0));
693 presultTitle.add(titl);
696 guiWindow.setProgressBar("Finished querying", Thread.currentThread()
699 guiWindow.setProgressBar((presult.size() > 0) ? "Parsing results."
700 : "Processing ..", Thread.currentThread().hashCode());
702 while (presult.size() > 0)
704 parseResult(presult.remove(0), presultTitle.remove(0), null);
706 // only remove visual delay after we finished parsing.
707 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
708 if (nextfetch.size() > 0)
710 StringBuffer sb = new StringBuffer();
711 sb.append("Didn't retrieve the following "
712 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
713 + " queries") + ": \n");
714 int l = sb.length(), lr = 0;
715 for (String s : nextfetch)
717 if (l != sb.length())
721 if (lr - sb.length() > 40)
727 showErrorMessage(sb.toString());
732 AlignmentI parseResult(String result, String title)
734 String format = new IdentifyFile().Identify(result, "Paste");
735 Alignment sequences = null;
736 if (FormatAdapter.isValidFormat(format))
741 sequences = new FormatAdapter().readFile(result.toString(),
743 } catch (Exception ex)
747 if (sequences != null)
749 return parseResult(sequences, title, format);
754 showErrorMessage("Error retrieving " + textArea.getText() + " from "
755 + database.getSelectedItem());
763 * @return a standard title for any results retrieved using the currently
764 * selected source and settings
766 public String getDefaultRetrievalTitle()
768 return "Retrieved from " + database.getSelectedItem();
771 AlignmentI parseResult(AlignmentI al, String title,
772 String currentFileFormat)
775 if (al != null && al.getHeight() > 0)
777 if (alignFrame == null)
779 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
780 AlignFrame.DEFAULT_HEIGHT);
781 if (currentFileFormat != null)
783 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
785 // NON-FormatAdapter Sourced
791 title = getDefaultRetrievalTitle();
793 SequenceFeature[] sfs = null;
794 List<SequenceI> alsqs;
795 synchronized (alsqs = al.getSequences())
797 for (SequenceI sq : alsqs)
799 if ((sfs = (sq).getDatasetSequence().getSequenceFeatures()) != null)
803 af.setShowSeqFeatures(true);
810 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
811 AlignFrame.DEFAULT_HEIGHT);
813 af.statusBar.setText(MessageManager
814 .getString("label.successfully_pasted_alignment_file"));
818 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
820 } catch (Exception ex)
826 for (int i = 0; i < al.getHeight(); i++)
828 alignFrame.viewport.getAlignment().addSequence(
829 al.getSequenceAt(i)); // this
836 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
838 alignFrame.viewport.getAlignment().getWidth();
839 alignFrame.viewport.firePropertyChange("alignment", null,
840 alignFrame.viewport.getAlignment().getSequences());
846 void showErrorMessage(final String error)
849 javax.swing.SwingUtilities.invokeLater(new Runnable()
854 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
855 MessageManager.getString("label.error_retrieving_data"),
856 JOptionPane.WARNING_MESSAGE);