2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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.
23 import jalview.api.FeatureSettingsModelI;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.service.pdb.PDBFTSPanel;
30 import jalview.fts.service.uniprot.UniprotFTSPanel;
31 import jalview.io.gff.SequenceOntologyI;
32 import jalview.util.DBRefUtils;
33 import jalview.util.MessageManager;
34 import jalview.util.Platform;
35 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
36 import jalview.ws.seqfetcher.DbSourceProxy;
38 import java.awt.BorderLayout;
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.KeyAdapter;
43 import java.awt.event.KeyEvent;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Iterator;
47 import java.util.List;
49 import javax.swing.JButton;
50 import javax.swing.JCheckBox;
51 import javax.swing.JInternalFrame;
52 import javax.swing.JLabel;
53 import javax.swing.JOptionPane;
54 import javax.swing.JPanel;
55 import javax.swing.JScrollPane;
56 import javax.swing.JTextArea;
57 import javax.swing.SwingConstants;
58 import javax.swing.tree.DefaultMutableTreeNode;
60 public class SequenceFetcher extends JPanel implements Runnable
62 JLabel dbeg = new JLabel();
64 JDatabaseTree database;
68 JLabel jLabel1 = new JLabel();
70 JCheckBox replacePunctuation = new JCheckBox();
72 JButton ok = new JButton();
74 JButton clear = new JButton();
76 JButton example = new JButton();
78 JButton close = new JButton();
80 JPanel jPanel1 = new JPanel();
82 JTextArea textArea = new JTextArea();
84 JScrollPane jScrollPane1 = new JScrollPane();
86 JPanel jPanel2 = new JPanel();
88 JPanel jPanel3 = new JPanel();
90 JPanel jPanel4 = new JPanel();
92 BorderLayout borderLayout1 = new BorderLayout();
94 BorderLayout borderLayout2 = new BorderLayout();
96 BorderLayout borderLayout3 = new BorderLayout();
100 IProgressIndicator guiWindow;
102 AlignFrame alignFrame;
106 final String noDbSelected = "-- Select Database --";
108 private static jalview.ws.SequenceFetcher sfetch = null;
110 private static long lastDasSourceRegistry = -3;
112 private static DasSourceRegistryI dasRegistry = null;
114 private static boolean _initingFetcher = false;
116 private static Thread initingThread = null;
118 int debounceTrap = 0;
120 public JTextArea getTextArea()
126 * Blocking method that initialises and returns the shared instance of the
127 * SequenceFetcher client
130 * - where the initialisation delay message should be shown
131 * @return the singleton instance of the sequence fetcher client
133 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
134 final IProgressIndicator guiWindow)
136 if (_initingFetcher && initingThread != null && initingThread.isAlive())
138 if (guiWindow != null)
143 .getString("status.waiting_sequence_database_fetchers_init"),
144 Thread.currentThread().hashCode());
146 // initting happening on another thread - so wait around to see if it
148 while (_initingFetcher && initingThread != null
149 && initingThread.isAlive())
154 } catch (Exception e)
159 if (guiWindow != null)
164 .getString("status.waiting_sequence_database_fetchers_init"),
165 Thread.currentThread().hashCode());
169 || dasRegistry != Cache.getDasSourceRegistry()
170 || lastDasSourceRegistry != (Cache.getDasSourceRegistry()
171 .getDasRegistryURL() + Cache
172 .getDasSourceRegistry().getLocalSourceString())
175 _initingFetcher = true;
176 initingThread = Thread.currentThread();
178 * give a visual indication that sequence fetcher construction is occuring
180 if (guiWindow != null)
182 guiWindow.setProgressBar(MessageManager
183 .getString("status.init_sequence_database_fetchers"),
184 Thread.currentThread().hashCode());
186 dasRegistry = Cache.getDasSourceRegistry();
187 dasRegistry.refreshSources();
189 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
190 if (guiWindow != null)
192 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
194 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
195 .getLocalSourceString()).hashCode();
197 _initingFetcher = false;
198 initingThread = null;
203 private IProgressIndicator progressIndicator;
205 public SequenceFetcher(IProgressIndicator guiIndic)
207 this.progressIndicator = guiIndic;
208 final SequenceFetcher us = this;
209 // launch initialiser thread
210 Thread sf = new Thread(new Runnable()
216 if (getSequenceFetcherSingleton(progressIndicator) != null)
218 us.initGui(progressIndicator);
222 javax.swing.SwingUtilities.invokeLater(new Runnable()
228 .showInternalMessageDialog(
231 .getString("warn.couldnt_create_sequence_fetcher_client"),
233 .getString("label.couldnt_create_sequence_fetcher"),
234 JOptionPane.ERROR_MESSAGE);
238 // raise warning dialog
245 private class DatabaseAuthority extends DefaultMutableTreeNode
250 private class DatabaseSource extends DefaultMutableTreeNode
256 * called by thread spawned by constructor
260 private void initGui(IProgressIndicator guiWindow)
262 this.guiWindow = guiWindow;
263 if (guiWindow instanceof AlignFrame)
265 alignFrame = (AlignFrame) guiWindow;
267 database = new JDatabaseTree(sfetch);
271 } catch (Exception ex)
273 ex.printStackTrace();
276 frame = new JInternalFrame();
277 frame.setContentPane(this);
278 if (Platform.isAMac())
280 Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 240);
284 Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 180);
288 private String getFrameTitle()
290 return ((alignFrame == null) ? MessageManager
291 .getString("label.new_sequence_fetcher") : MessageManager
292 .getString("label.additional_sequence_fetcher"));
295 private void jbInit() throws Exception
297 this.setLayout(borderLayout2);
299 database.setFont(JvSwingUtils.getLabelFont());
300 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
301 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
302 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
303 jLabel1.setText(MessageManager
304 .getString("label.separate_multiple_accession_ids"));
306 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
308 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
309 replacePunctuation.setText(MessageManager
310 .getString("label.replace_commas_semicolons"));
311 ok.setText(MessageManager.getString("action.ok"));
312 ok.addActionListener(new ActionListener()
315 public void actionPerformed(ActionEvent e)
317 ok_actionPerformed();
320 clear.setText(MessageManager.getString("action.clear"));
321 clear.addActionListener(new ActionListener()
324 public void actionPerformed(ActionEvent e)
326 clear_actionPerformed();
330 example.setText(MessageManager.getString("label.example"));
331 example.addActionListener(new ActionListener()
334 public void actionPerformed(ActionEvent e)
336 example_actionPerformed();
339 close.setText(MessageManager.getString("action.close"));
340 close.addActionListener(new ActionListener()
343 public void actionPerformed(ActionEvent e)
345 close_actionPerformed(e);
348 textArea.setFont(JvSwingUtils.getLabelFont());
349 textArea.setLineWrap(true);
350 textArea.addKeyListener(new KeyAdapter()
353 public void keyPressed(KeyEvent e)
355 if (e.getKeyCode() == KeyEvent.VK_ENTER)
357 ok_actionPerformed();
361 jPanel3.setLayout(borderLayout1);
362 borderLayout1.setVgap(5);
364 jPanel1.add(example);
367 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
368 jPanel2.setLayout(borderLayout3);
369 databaseButt = database.getDatabaseSelectorButton();
370 databaseButt.setFont(JvSwingUtils.getLabelFont());
371 database.addActionListener(new ActionListener()
374 public void actionPerformed(ActionEvent e)
377 String currentSelection = database.getSelectedItem();
378 if (currentSelection == null)
380 close_actionPerformed(null);
385 if (currentSelection.equalsIgnoreCase("pdb")
386 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
390 else if (currentSelection.equalsIgnoreCase("uniprot")
391 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
393 uniprotSourceAction();
399 database.action = -1;
404 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
405 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
406 JPanel jPanel2a = new JPanel(new BorderLayout());
407 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
408 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
409 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
410 // jPanel2.setPreferredSize(new Dimension())
411 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
412 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
413 this.add(jPanel3, java.awt.BorderLayout.CENTER);
414 this.add(jPanel2, java.awt.BorderLayout.NORTH);
415 jScrollPane1.getViewport().add(textArea);
418 * open the database tree
420 database.waitForInput();
423 private void pdbSourceAction()
425 databaseButt.setText(database.getSelectedItem());
426 new PDBFTSPanel(this);
430 private void uniprotSourceAction()
432 databaseButt.setText(database.getSelectedItem());
433 new UniprotFTSPanel(this);
436 private void otherSourceAction()
440 databaseButt.setText(database.getSelectedItem()
441 + (database.getSelectedSources().size() > 1 ? " (and "
442 + database.getSelectedSources().size() + " others)"
444 String eq = database.getExampleQueries();
445 dbeg.setText(MessageManager.formatMessage(
446 "label.example_query_param", new String[] { eq }));
447 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
448 for (DbSourceProxy dbs : database.getSelectedSources())
450 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
456 replacePunctuation.setEnabled(enablePunct);
458 } catch (Exception ex)
461 replacePunctuation.setEnabled(true);
466 protected void example_actionPerformed()
468 DbSourceProxy db = null;
471 textArea.setText(database.getExampleQueries());
472 } catch (Exception ex)
478 protected void clear_actionPerformed()
480 textArea.setText("");
484 public void close_actionPerformed(ActionEvent e)
488 frame.setClosed(true);
489 } catch (Exception ex)
494 public void ok_actionPerformed()
496 databaseButt.setEnabled(false);
497 example.setEnabled(false);
498 textArea.setEnabled(false);
499 ok.setEnabled(false);
500 close.setEnabled(false);
502 Thread worker = new Thread(this);
506 private void resetDialog()
508 databaseButt.setEnabled(true);
509 example.setEnabled(true);
510 textArea.setEnabled(true);
512 close.setEnabled(true);
519 if (!database.hasSelection())
521 error += "Please select the source database\n";
523 // TODO: make this transformation more configurable
524 com.stevesoft.pat.Regex empty;
525 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
527 empty = new com.stevesoft.pat.Regex(
528 // replace commas and spaces with a semicolon
529 "(\\s|[,; ])+", ";");
533 // just turn spaces and semicolons into single semicolons
534 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
536 textArea.setText(empty.replaceAll(textArea.getText()));
537 // see if there's anthing to search with
538 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
541 error += "Please enter a (semi-colon separated list of) database id(s)";
543 if (error.length() > 0)
545 showErrorMessage(error);
549 // TODO: Refactor to GUI independent code and write tests.
550 // indicate if successive sources should be merged into one alignment.
551 boolean addToLast = false;
552 List<String> aresultq = new ArrayList<String>();
553 List<String> presultTitle = new ArrayList<String>();
554 List<AlignmentI> presult = new ArrayList<AlignmentI>();
555 List<AlignmentI> aresult = new ArrayList<AlignmentI>();
556 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
559 List<String> nextFetch = Arrays.asList(qries = textArea.getText()
561 Iterator<String> en = Arrays.asList(new String[0]).iterator();
562 int nqueries = qries.length;
564 FeatureSettingsModelI preferredFeatureColours = null;
565 while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
567 if (!en.hasNext() && nextFetch.size() > 0)
569 en = nextFetch.iterator();
570 nqueries = nextFetch.size();
571 // save the remaining queries in the original array
572 qries = nextFetch.toArray(new String[nqueries]);
573 nextFetch = new ArrayList<String>();
576 DbSourceProxy proxy = proxies.next();
581 .setProgressBar(MessageManager.formatMessage(
582 "status.fetching_sequence_queries_from",
584 Integer.valueOf(nqueries).toString(),
585 proxy.getDbName() }), Thread.currentThread()
587 if (proxy.getMaximumQueryCount() == 1)
590 * proxy only handles one accession id at a time
594 String acc = en.next();
595 if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
604 * proxy can fetch multiple accessions at one time
606 fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
608 } catch (Exception e)
610 showErrorMessage("Error retrieving " + textArea.getText()
611 + " from " + database.getSelectedItem());
613 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
614 System.err.println("Retrieval failed for source ='"
615 + database.getSelectedItem() + "' and query\n'"
616 + textArea.getText() + "'\n");
618 } catch (OutOfMemoryError e)
620 showErrorMessage("Out of Memory when retrieving "
623 + database.getSelectedItem()
624 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
628 showErrorMessage("Serious Error retrieving " + textArea.getText()
629 + " from " + database.getSelectedItem());
633 // Stack results ready for opening in alignment windows
634 if (aresult != null && aresult.size() > 0)
636 FeatureSettingsModelI proxyColourScheme = proxy
637 .getFeatureColourScheme();
638 if (proxyColourScheme != null)
640 preferredFeatureColours = proxyColourScheme;
643 AlignmentI ar = null;
644 if (proxy.isAlignmentSource())
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));
677 presultTitle.add(titl);
680 guiWindow.setProgressBar(MessageManager
681 .getString("status.finshed_querying"), Thread.currentThread()
684 guiWindow.setProgressBar(
685 (presult.size() > 0) ? MessageManager
686 .getString("status.parsing_results") : MessageManager
687 .getString("status.processing"), Thread.currentThread()
690 while (presult.size() > 0)
692 parseResult(presult.remove(0), presultTitle.remove(0), null,
693 preferredFeatureColours);
695 // only remove visual delay after we finished parsing.
696 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
697 if (nextFetch.size() > 0)
699 StringBuffer sb = new StringBuffer();
700 sb.append("Didn't retrieve the following "
701 + (nextFetch.size() == 1 ? "query" : nextFetch.size()
702 + " queries") + ": \n");
703 int l = sb.length(), lr = 0;
704 for (String s : nextFetch)
706 if (l != sb.length())
710 if (lr - sb.length() > 40)
716 showErrorMessage(sb.toString());
722 * Tries to fetch one or more accession ids from the database proxy
726 * the queries to fetch
728 * a successful queries list to add to
730 * a list of retrieved alignments to add to
732 * failed queries are added to this list
735 void fetchMultipleAccessions(DbSourceProxy proxy,
736 Iterator<String> accessions, List<String> aresultq,
737 List<AlignmentI> aresult, List<String> nextFetch)
740 StringBuilder multiacc = new StringBuilder();
741 List<String> tosend = new ArrayList<String>();
742 while (accessions.hasNext())
744 String nel = accessions.next();
746 multiacc.append(nel);
747 if (accessions.hasNext())
749 multiacc.append(proxy.getAccessionSeparator());
755 String query = multiacc.toString();
756 AlignmentI rslt = proxy.getSequenceRecords(query);
757 if (rslt == null || rslt.getHeight() == 0)
759 // no results - pass on all queries to next source
760 nextFetch.addAll(tosend);
766 if (tosend.size() > 1)
768 checkResultForQueries(rslt, tosend, nextFetch, proxy);
771 } catch (OutOfMemoryError oome)
773 new OOMWarning("fetching " + multiacc + " from "
774 + database.getSelectedItem(), oome, this);
779 * Query for a single accession id via the database proxy
784 * a list of successful queries to add to
786 * a list of retrieved alignments to add to
787 * @return true if the fetch was successful, else false
789 boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
790 List<String> aresultq, List<AlignmentI> aresult)
792 boolean success = false;
799 // give the server a chance to breathe
801 } catch (Exception e)
807 AlignmentI indres = null;
810 indres = proxy.getSequenceRecords(accession);
811 } catch (OutOfMemoryError oome)
813 new OOMWarning("fetching " + accession + " from "
814 + proxy.getDbName(), oome, this);
818 aresultq.add(accession);
822 } catch (Exception e)
825 "Error retrieving " + accession
826 + " from " + proxy.getDbName(), e);
834 * Checks which of the queries were successfully retrieved by searching the
835 * DBRefs of the retrieved sequences for a match. Any not found are added to
836 * the 'nextFetch' list.
843 void checkResultForQueries(AlignmentI rslt, List<String> queries,
844 List<String> nextFetch, DbSourceProxy proxy)
846 SequenceI[] rs = rslt.getSequencesArray();
848 for (String q : queries)
850 DBRefEntry[] found = null;
851 DBRefEntry dbr = new DBRefEntry();
852 dbr.setSource(proxy.getDbSource());
853 dbr.setVersion(null);
854 String accId = proxy.getAccessionIdFromQuery(q);
855 dbr.setAccessionId(accId);
856 boolean rfound = false;
857 for (int r = 0; r < rs.length; r++)
861 found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
862 if (found != null && found.length > 0)
878 * @return a standard title for any results retrieved using the currently
879 * selected source and settings
881 public String getDefaultRetrievalTitle()
883 return "Retrieved from " + database.getSelectedItem();
886 AlignmentI parseResult(AlignmentI al, String title,
887 String currentFileFormat,
888 FeatureSettingsModelI preferredFeatureColours)
891 if (al != null && al.getHeight() > 0)
895 title = getDefaultRetrievalTitle();
897 if (alignFrame == null)
899 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
900 AlignFrame.DEFAULT_HEIGHT);
901 if (currentFileFormat != null)
903 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
905 // NON-FormatAdapter Sourced
909 SequenceFeature[] sfs = null;
910 List<SequenceI> alsqs;
911 synchronized (alsqs = al.getSequences())
913 for (SequenceI sq : alsqs)
915 if ((sfs = sq.getSequenceFeatures()) != null)
919 af.setShowSeqFeatures(true);
927 if (preferredFeatureColours != null)
929 af.getViewport().applyFeaturesStyle(preferredFeatureColours);
931 if (Cache.getDefault("HIDE_INTRONS", true))
933 af.hideFeatureColumns(SequenceOntologyI.EXON, false);
936 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
937 AlignFrame.DEFAULT_HEIGHT);
939 af.statusBar.setText(MessageManager
940 .getString("label.successfully_pasted_alignment_file"));
944 af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
946 } catch (Exception ex)
952 alignFrame.viewport.addAlignment(al, title);
958 void showErrorMessage(final String error)
961 javax.swing.SwingUtilities.invokeLater(new Runnable()
966 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
967 MessageManager.getString("label.error_retrieving_data"),
968 JOptionPane.WARNING_MESSAGE);
973 public IProgressIndicator getProgressIndicator()
975 return progressIndicator;
978 public void setProgressIndicator(IProgressIndicator progressIndicator)
980 this.progressIndicator = progressIndicator;
984 * Make this panel visible (after a selection has been made in the database
989 frame.setVisible(true);