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 MessageManager.getString("status.waiting_sequence_database_fetchers_init"),
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 MessageManager.getString("status.waiting_sequence_database_fetchers_init"),
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(MessageManager.getString("status.init_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(MessageManager.getString("status.init_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 MessageManager.getString("warn.couldnt_create_sequence_fetcher_client"),
165 MessageManager.getString("label.couldnt_create_sequence_fetcher"),
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(MessageManager.formatMessage("status.fetching_sequence_queries_from", new String[]{Integer.valueOf(nqueries).toString(),proxy.getDbName()}), Thread
498 .currentThread().hashCode());
499 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
500 if (proxy.getAccessionSeparator() == null)
504 String item = en.next();
511 // give the server a chance to breathe
513 } catch (Exception e)
520 AlignmentI indres = null;
523 indres = proxy.getSequenceRecords(item);
524 } catch (OutOfMemoryError oome)
526 new OOMWarning("fetching " + item + " from "
527 + proxy.getDbName(), oome, this);
538 } catch (Exception e)
540 jalview.bin.Cache.log.info("Error retrieving " + item
541 + " from " + proxy.getDbName(), e);
548 StringBuffer multiacc = new StringBuffer();
549 ArrayList<String> tosend = new ArrayList<String>();
552 String nel = en.next();
554 multiacc.append(nel);
557 multiacc.append(proxy.getAccessionSeparator());
564 List<String> nores = new ArrayList<String>();
565 rslt = proxy.getSequenceRecords(multiacc.toString());
566 if (rslt == null || rslt.getHeight() == 0)
568 // no results - pass on all queries to next source
569 nextfetch.addAll(tosend);
573 aresultq.add(multiacc.toString());
576 rs = rslt.getSequencesArray();
577 // search for each query in the dbrefs associated with each
580 // ones we do not find will be used to query next source (if any)
581 for (String q : tosend)
583 DBRefEntry dbr = new DBRefEntry(), found[] = null;
584 dbr.setSource(proxy.getDbSource());
585 dbr.setVersion(null);
586 if (proxy.getAccessionValidator() != null)
588 Regex vgr = proxy.getAccessionValidator();
590 if (vgr.numSubs() > 0)
592 dbr.setAccessionId(vgr.stringMatched(1));
596 dbr.setAccessionId(vgr.stringMatched());
601 dbr.setAccessionId(q);
603 boolean rfound = false;
604 for (int r = 0; r < rs.length; r++)
607 && (found = DBRefUtils.searchRefs(
608 rs[r].getDBRef(), dbr)) != null
622 } catch (OutOfMemoryError oome)
624 new OOMWarning("fetching " + multiacc + " from "
625 + database.getSelectedItem(), oome, this);
629 } catch (Exception e)
631 showErrorMessage("Error retrieving " + textArea.getText()
632 + " from " + database.getSelectedItem());
634 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
635 System.err.println("Retrieval failed for source ='"
636 + database.getSelectedItem() + "' and query\n'"
637 + textArea.getText() + "'\n");
639 } catch (OutOfMemoryError e)
641 // resets dialog box - so we don't use OOMwarning here.
642 showErrorMessage("Out of Memory when retrieving "
645 + database.getSelectedItem()
646 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
650 showErrorMessage("Serious Error retrieving " + textArea.getText()
651 + " from " + database.getSelectedItem());
654 // Stack results ready for opening in alignment windows
655 if (aresult != null && aresult.size() > 0)
657 AlignmentI ar = null;
661 // new window for each result
662 while (aresult.size() > 0)
664 presult.add(aresult.remove(0));
665 presultTitle.add(aresultq.remove(0) + " "
666 + getDefaultRetrievalTitle());
672 if (addToLast && presult.size() > 0)
674 ar = presult.remove(presult.size() - 1);
675 titl = presultTitle.remove(presultTitle.size() - 1);
677 // concatenate all results in one window
678 while (aresult.size() > 0)
682 ar = aresult.remove(0);
686 ar.append(aresult.remove(0));
692 presultTitle.add(titl);
695 guiWindow.setProgressBar(MessageManager.getString("status.finshed_querying"), Thread.currentThread()
698 guiWindow.setProgressBar((presult.size() > 0) ? MessageManager.getString("status.parsing_results")
699 : MessageManager.getString("status.processing"), Thread.currentThread().hashCode());
701 while (presult.size() > 0)
703 parseResult(presult.remove(0), presultTitle.remove(0), null);
705 // only remove visual delay after we finished parsing.
706 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
707 if (nextfetch.size() > 0)
709 StringBuffer sb = new StringBuffer();
710 sb.append("Didn't retrieve the following "
711 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
712 + " queries") + ": \n");
713 int l = sb.length(), lr = 0;
714 for (String s : nextfetch)
716 if (l != sb.length())
720 if (lr - sb.length() > 40)
726 showErrorMessage(sb.toString());
731 AlignmentI parseResult(String result, String title)
733 String format = new IdentifyFile().Identify(result, "Paste");
734 Alignment sequences = null;
735 if (FormatAdapter.isValidFormat(format))
740 sequences = new FormatAdapter().readFile(result.toString(),
742 } catch (Exception ex)
746 if (sequences != null)
748 return parseResult(sequences, title, format);
753 showErrorMessage("Error retrieving " + textArea.getText() + " from "
754 + database.getSelectedItem());
762 * @return a standard title for any results retrieved using the currently
763 * selected source and settings
765 public String getDefaultRetrievalTitle()
767 return "Retrieved from " + database.getSelectedItem();
770 AlignmentI parseResult(AlignmentI al, String title,
771 String currentFileFormat)
774 if (al != null && al.getHeight() > 0)
776 if (alignFrame == null)
778 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
779 AlignFrame.DEFAULT_HEIGHT);
780 if (currentFileFormat != null)
782 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
784 // NON-FormatAdapter Sourced
790 title = getDefaultRetrievalTitle();
792 SequenceFeature[] sfs = null;
793 List<SequenceI> alsqs;
794 synchronized (alsqs = al.getSequences())
796 for (SequenceI sq : alsqs)
798 if ((sfs = (sq).getDatasetSequence().getSequenceFeatures()) != null)
802 af.setShowSeqFeatures(true);
809 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
810 AlignFrame.DEFAULT_HEIGHT);
812 af.statusBar.setText(MessageManager
813 .getString("label.successfully_pasted_alignment_file"));
817 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
819 } catch (Exception ex)
825 for (int i = 0; i < al.getHeight(); i++)
827 alignFrame.viewport.getAlignment().addSequence(
828 al.getSequenceAt(i)); // this
835 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
837 alignFrame.viewport.getAlignment().getWidth();
838 alignFrame.viewport.firePropertyChange("alignment", null,
839 alignFrame.viewport.getAlignment().getSequences());
845 void showErrorMessage(final String error)
848 javax.swing.SwingUtilities.invokeLater(new Runnable()
853 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
854 MessageManager.getString("label.error_retrieving_data"),
855 JOptionPane.WARNING_MESSAGE);