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 java.awt.BorderLayout;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.awt.event.KeyAdapter;
28 import java.awt.event.KeyEvent;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
35 import javax.swing.JButton;
36 import javax.swing.JCheckBox;
37 import javax.swing.JComboBox;
38 import javax.swing.JInternalFrame;
39 import javax.swing.JLabel;
40 import javax.swing.JPanel;
41 import javax.swing.JScrollPane;
42 import javax.swing.JTextArea;
43 import javax.swing.SwingConstants;
45 import jalview.api.FeatureSettingsModelI;
46 import jalview.bin.Cache;
47 import jalview.bin.Console;
48 import jalview.datamodel.AlignmentI;
49 import jalview.datamodel.DBRefEntry;
50 import jalview.datamodel.SequenceI;
51 import jalview.fts.core.GFTSPanel;
52 import jalview.fts.service.pdb.PDBFTSPanel;
53 import jalview.fts.service.threedbeacons.TDBeaconsFTSPanel;
54 import jalview.fts.service.uniprot.UniprotFTSPanel;
55 import jalview.io.FileFormatI;
56 import jalview.io.gff.SequenceOntologyI;
57 import jalview.util.DBRefUtils;
58 import jalview.util.MessageManager;
59 import jalview.util.Platform;
60 import jalview.ws.seqfetcher.DbSourceProxy;
63 * A panel where the use may choose a database source, and enter one or more
64 * accessions, to retrieve entries from the database.
66 * If the selected source is Uniprot or PDB, a free text search panel is opened
67 * instead to perform the search and selection.
69 public class SequenceFetcher extends JPanel implements Runnable
71 private class StringPair
75 private String display;
77 public StringPair(String s1, String s2)
83 public StringPair(String s)
88 public String getKey()
93 public String getDisplay()
99 public String toString()
104 public boolean equals(StringPair other)
106 return other.key == this.key;
110 private static jalview.ws.SequenceFetcher sfetch = null;
112 JLabel exampleAccession;
114 JComboBox<StringPair> database;
116 JCheckBox replacePunctuation;
128 JInternalFrame frame;
130 IProgressIndicator guiWindow;
132 AlignFrame alignFrame;
134 GFTSPanel parentSearchPanel;
136 IProgressIndicator progressIndicator;
138 volatile boolean _isConstructing = false;
141 * Returns the shared instance of the SequenceFetcher client
145 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton()
149 sfetch = new jalview.ws.SequenceFetcher();
155 * Constructor given a client to receive any status or progress messages
156 * (currently either the Desktop, or an AlignFrame panel)
160 public SequenceFetcher(IProgressIndicator guiIndic)
162 this(guiIndic, null, null);
166 * Constructor with specified database and accession(s) to retrieve
172 public SequenceFetcher(IProgressIndicator guiIndic,
173 final String selectedDb, final String queryString)
175 this.progressIndicator = guiIndic;
176 getSequenceFetcherSingleton();
177 this.guiWindow = progressIndicator;
179 if (progressIndicator instanceof AlignFrame)
181 alignFrame = (AlignFrame) progressIndicator;
185 textArea.setText(queryString);
187 frame = new JInternalFrame();
188 frame.setContentPane(this);
189 Desktop.addInternalFrame(frame, getFrameTitle(), Desktop.FRAME_MAKE_VISIBLE, 400,
190 Platform.isAMacAndNotJS() ? 240 : 180, Desktop.FRAME_ALLOW_RESIZE, Desktop.FRAME_SET_MIN_SIZE_300);
193 private String getFrameTitle()
195 return ((alignFrame == null)
196 ? MessageManager.getString("label.new_sequence_fetcher")
198 .getString("label.additional_sequence_fetcher"));
201 private void jbInit(String selectedDb)
203 this.setLayout(new BorderLayout());
205 database = new JComboBox<>();
206 database.setFont(JvSwingUtils.getLabelFont());
207 StringPair instructionItem = new StringPair(
208 MessageManager.getString("action.select_ddbb"));
209 database.setPrototypeDisplayValue(instructionItem);
210 String[] sources = new jalview.ws.SequenceFetcher().getSupportedDb();
211 Arrays.sort(sources, String.CASE_INSENSITIVE_ORDER);
212 database.addItem(instructionItem);
213 for (String source : sources)
215 List<DbSourceProxy> slist = sfetch.getSourceProxy(source);
216 if (slist.size() == 1 && slist.get(0) != null)
218 database.addItem(new StringPair(source, slist.get(0).getDbName()));
222 database.addItem(new StringPair(source));
225 setDatabaseSelectedItem(selectedDb);
226 if (database.getSelectedIndex() == -1)
228 database.setSelectedIndex(0);
230 database.setMaximumRowCount(database.getItemCount());
231 database.addActionListener(new ActionListener()
234 public void actionPerformed(ActionEvent e)
236 String currentSelection = ((StringPair) database.getSelectedItem())
238 updateExampleQuery(currentSelection);
240 if ("pdb".equalsIgnoreCase(currentSelection))
243 new PDBFTSPanel(SequenceFetcher.this);
245 else if ("uniprot".equalsIgnoreCase(currentSelection))
248 new UniprotFTSPanel(SequenceFetcher.this);
250 else if ("3d-beacons".equalsIgnoreCase(currentSelection))
253 new TDBeaconsFTSPanel(SequenceFetcher.this);
262 exampleAccession = new JLabel("");
263 exampleAccession.setFont(new Font("Verdana", Font.BOLD, 11));
264 JLabel jLabel1 = new JLabel(MessageManager
265 .getString("label.separate_multiple_accession_ids"));
266 jLabel1.setFont(new Font("Verdana", Font.ITALIC, 11));
267 jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
269 replacePunctuation = new JCheckBox(
270 MessageManager.getString("label.replace_commas_semicolons"));
271 replacePunctuation.setHorizontalAlignment(SwingConstants.LEFT);
272 replacePunctuation.setFont(new Font("Verdana", Font.ITALIC, 11));
273 okBtn = new JButton(MessageManager.getString("action.ok"));
274 okBtn.addActionListener(new ActionListener()
277 public void actionPerformed(ActionEvent e)
279 ok_actionPerformed();
282 JButton clear = new JButton(MessageManager.getString("action.clear"));
283 clear.addActionListener(new ActionListener()
286 public void actionPerformed(ActionEvent e)
288 clear_actionPerformed();
292 exampleBtn = new JButton(MessageManager.getString("label.example"));
293 exampleBtn.addActionListener(new ActionListener()
296 public void actionPerformed(ActionEvent e)
298 example_actionPerformed();
301 closeBtn = new JButton(MessageManager.getString("action.cancel"));
302 closeBtn.addActionListener(new ActionListener()
305 public void actionPerformed(ActionEvent e)
307 close_actionPerformed(e);
310 backBtn = new JButton(MessageManager.getString("action.back"));
311 backBtn.addActionListener(new ActionListener()
314 public void actionPerformed(ActionEvent e)
316 parentSearchPanel.btn_back_ActionPerformed();
319 // back not visible unless embedded
320 backBtn.setVisible(false);
322 textArea = new JTextArea();
323 textArea.setFont(JvSwingUtils.getLabelFont());
324 textArea.setLineWrap(true);
325 textArea.addKeyListener(new KeyAdapter()
328 public void keyPressed(KeyEvent e)
330 if (e.getKeyCode() == KeyEvent.VK_ENTER)
332 ok_actionPerformed();
337 JPanel actionPanel = new JPanel();
338 actionPanel.add(backBtn);
339 actionPanel.add(exampleBtn);
340 actionPanel.add(clear);
341 actionPanel.add(okBtn);
342 actionPanel.add(closeBtn);
344 JPanel databasePanel = new JPanel();
345 databasePanel.setLayout(new BorderLayout());
346 databasePanel.add(database, BorderLayout.NORTH);
347 databasePanel.add(exampleAccession, BorderLayout.CENTER);
348 JPanel jPanel2a = new JPanel(new BorderLayout());
349 jPanel2a.add(jLabel1, BorderLayout.NORTH);
350 jPanel2a.add(replacePunctuation, BorderLayout.SOUTH);
351 databasePanel.add(jPanel2a, BorderLayout.SOUTH);
353 JPanel idsPanel = new JPanel();
354 idsPanel.setLayout(new BorderLayout(0, 5));
355 JScrollPane jScrollPane1 = new JScrollPane();
356 jScrollPane1.getViewport().add(textArea);
357 idsPanel.add(jScrollPane1, BorderLayout.CENTER);
359 this.add(actionPanel, BorderLayout.SOUTH);
360 this.add(idsPanel, BorderLayout.CENTER);
361 this.add(databasePanel, BorderLayout.NORTH);
364 private void setDatabaseSelectedItem(String db)
366 for (int i = 0; i < database.getItemCount(); i++)
368 StringPair sp = database.getItemAt(i);
369 if (sp != null && db != null && db.equals(sp.getKey()))
371 database.setSelectedIndex(i);
378 * Answers a semi-colon-delimited string with the example query or queries for
379 * the selected database
384 protected String getExampleQueries(String db)
386 StringBuilder sb = new StringBuilder();
387 HashSet<String> hs = new HashSet<>();
388 for (DbSourceProxy dbs : sfetch.getSourceProxy(db))
390 String tq = dbs.getTestQuery();
391 if (hs.add(tq)) // not a duplicate source
400 return sb.toString();
404 * Action on selecting a database other than Uniprot or PDB is to enable or
405 * disable 'Replace commas', and await input in the query field
407 protected void otherSourceAction()
411 String eq = exampleAccession.getText();
412 // TODO this should be a property of the SequenceFetcher whether commas
413 // are allowed in the IDs...
415 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
416 replacePunctuation.setEnabled(enablePunct);
418 } catch (Exception ex)
420 exampleAccession.setText("");
421 replacePunctuation.setEnabled(true);
427 * Sets the text of the example query to incorporate the example accession
428 * provided by the selected database source
430 * @param selectedDatabase
433 protected String updateExampleQuery(String selectedDatabase)
435 String eq = getExampleQueries(selectedDatabase);
436 exampleAccession.setText(MessageManager
437 .formatMessage("label.example_query_param", new String[]
443 * Action on clicking the 'Example' button is to write the example accession
444 * as the query text field value
446 protected void example_actionPerformed()
448 String eq = getExampleQueries(
449 ((StringPair) database.getSelectedItem()).getKey());
450 textArea.setText(eq);
455 * Clears the query input field
457 protected void clear_actionPerformed()
459 textArea.setText("");
464 * Action on Close button is to close this frame, and also (if it is embedded
465 * in a search panel) to close the search panel
469 protected void close_actionPerformed(ActionEvent e)
473 frame.setClosed(true);
474 if (parentSearchPanel != null)
476 parentSearchPanel.btn_cancel_ActionPerformed();
478 } catch (Exception ex)
484 * Action on OK is to start the fetch for entered accession(s)
486 public void ok_actionPerformed()
489 * tidy inputs and check there is something to search for
491 String t0 = textArea.getText();
492 String text = t0.trim();
493 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
495 text = text.replace(",", ";");
497 text = text.replaceAll("(\\s|[; ])+", ";");
498 if (!t0.equals(text))
500 textArea.setText(text);
506 "Please enter a (semi-colon separated list of) database id(s)");
510 if (database.getSelectedIndex() == 0)
513 showErrorMessage("Please choose a database");
518 exampleBtn.setEnabled(false);
519 textArea.setEnabled(false);
520 okBtn.setEnabled(false);
521 closeBtn.setEnabled(false);
522 backBtn.setEnabled(false);
524 Thread worker = new Thread(this);
528 private void resetDialog()
530 exampleBtn.setEnabled(true);
531 textArea.setEnabled(true);
532 okBtn.setEnabled(true);
533 closeBtn.setEnabled(true);
534 backBtn.setEnabled(parentSearchPanel != null);
540 boolean addToLast = false;
541 List<String> aresultq = new ArrayList<>();
542 List<String> presultTitle = new ArrayList<>();
543 List<AlignmentI> presult = new ArrayList<>();
544 List<AlignmentI> aresult = new ArrayList<>();
545 List<DbSourceProxy> sources = sfetch.getSourceProxy(
546 ((StringPair) database.getSelectedItem()).getKey());
547 Iterator<DbSourceProxy> proxies = sources.iterator();
548 String[] qries = textArea.getText().trim().split(";");
549 List<String> nextFetch = Arrays.asList(qries);
550 Iterator<String> en = Arrays.asList(new String[0]).iterator();
551 int nqueries = qries.length;
553 FeatureSettingsModelI preferredFeatureColours = null;
554 while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
556 if (!en.hasNext() && nextFetch.size() > 0)
558 en = nextFetch.iterator();
559 nqueries = nextFetch.size();
560 // save the remaining queries in the original array
561 qries = nextFetch.toArray(new String[nqueries]);
562 nextFetch = new ArrayList<>();
565 DbSourceProxy proxy = proxies.next();
569 guiWindow.setProgressBar(MessageManager.formatMessage(
570 "status.fetching_sequence_queries_from", new String[]
571 { Integer.valueOf(nqueries).toString(),
572 proxy.getDbName() }),
573 Thread.currentThread().hashCode());
574 if (proxy.getMaximumQueryCount() == 1)
577 * proxy only handles one accession id at a time
581 String acc = en.next();
582 if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
591 * proxy can fetch multiple accessions at one time
593 fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
595 } catch (Exception e)
597 showErrorMessage("Error retrieving " + textArea.getText() + " from "
598 + ((StringPair) database.getSelectedItem()).getDisplay());
600 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
601 System.err.println("Retrieval failed for source ='"
602 + ((StringPair) database.getSelectedItem()).getDisplay()
603 + "' and query\n'" + textArea.getText() + "'\n");
605 } catch (OutOfMemoryError e)
607 showErrorMessage("Out of Memory when retrieving "
608 + textArea.getText() + " from "
609 + ((StringPair) database.getSelectedItem()).getDisplay()
610 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
614 showErrorMessage("Serious Error retrieving " + textArea.getText()
616 + ((StringPair) database.getSelectedItem()).getDisplay());
620 // Stack results ready for opening in alignment windows
621 if (aresult != null && aresult.size() > 0)
623 FeatureSettingsModelI proxyColourScheme = proxy
624 .getFeatureColourScheme();
625 if (proxyColourScheme != null)
627 preferredFeatureColours = proxyColourScheme;
630 AlignmentI ar = null;
631 if (proxy.isAlignmentSource())
634 // new window for each result
635 while (aresult.size() > 0)
637 presult.add(aresult.remove(0));
639 aresultq.remove(0) + " " + getDefaultRetrievalTitle());
645 if (addToLast && presult.size() > 0)
647 ar = presult.remove(presult.size() - 1);
648 titl = presultTitle.remove(presultTitle.size() - 1);
650 // concatenate all results in one window
651 while (aresult.size() > 0)
655 ar = aresult.remove(0);
659 ar.append(aresult.remove(0));
664 presultTitle.add(titl);
667 guiWindow.setProgressBar(
668 MessageManager.getString("status.finshed_querying"),
669 Thread.currentThread().hashCode());
675 .getString("status.parsing_results")
676 : MessageManager.getString("status.processing"),
677 Thread.currentThread().hashCode());
679 while (presult.size() > 0)
681 parseResult(presult.remove(0), presultTitle.remove(0), null,
682 preferredFeatureColours);
684 // only remove visual delay after we finished parsing.
685 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
686 if (nextFetch.size() > 0)
688 StringBuffer sb = new StringBuffer();
689 sb.append("Didn't retrieve the following "
690 + (nextFetch.size() == 1 ? "query"
691 : nextFetch.size() + " queries")
693 int l = sb.length(), lr = 0;
694 for (String s : nextFetch)
696 if (l != sb.length())
700 if (lr - sb.length() > 40)
706 showErrorMessage(sb.toString());
712 * Tries to fetch one or more accession ids from the database proxy
716 * the queries to fetch
718 * a successful queries list to add to
720 * a list of retrieved alignments to add to
722 * failed queries are added to this list
725 void fetchMultipleAccessions(DbSourceProxy proxy,
726 Iterator<String> accessions, List<String> aresultq,
727 List<AlignmentI> aresult, List<String> nextFetch) throws Exception
729 StringBuilder multiacc = new StringBuilder();
730 List<String> tosend = new ArrayList<>();
731 while (accessions.hasNext())
733 String nel = accessions.next();
735 multiacc.append(nel);
736 if (accessions.hasNext())
738 multiacc.append(proxy.getAccessionSeparator());
744 String query = multiacc.toString();
745 AlignmentI rslt = proxy.getSequenceRecords(query);
746 if (rslt == null || rslt.getHeight() == 0)
748 // no results - pass on all queries to next source
749 nextFetch.addAll(tosend);
755 if (tosend.size() > 1)
757 checkResultForQueries(rslt, tosend, nextFetch, proxy);
760 } catch (OutOfMemoryError oome)
762 new OOMWarning("fetching " + multiacc + " from "
763 + ((StringPair) database.getSelectedItem()).getDisplay(),
769 * Query for a single accession id via the database proxy
774 * a list of successful queries to add to
776 * a list of retrieved alignments to add to
777 * @return true if the fetch was successful, else false
779 boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
780 List<String> aresultq, List<AlignmentI> aresult)
782 boolean success = false;
789 // give the server a chance to breathe
791 } catch (Exception e)
797 AlignmentI indres = null;
800 indres = proxy.getSequenceRecords(accession);
801 } catch (OutOfMemoryError oome)
804 "fetching " + accession + " from " + proxy.getDbName(),
809 aresultq.add(accession);
813 } catch (Exception e)
815 Console.info("Error retrieving " + accession + " from "
816 + proxy.getDbName(), e);
822 * Checks which of the queries were successfully retrieved by searching the
823 * DBRefs of the retrieved sequences for a match. Any not found are added to
824 * the 'nextFetch' list.
831 void checkResultForQueries(AlignmentI rslt, List<String> queries,
832 List<String> nextFetch, DbSourceProxy proxy)
834 SequenceI[] rs = rslt.getSequencesArray();
836 for (String q : queries)
838 // BH 2019.01.25 dbr is never used.
839 // DBRefEntry dbr = new DBRefEntry();
840 // dbr.setSource(proxy.getDbSource());
841 // dbr.setVersion(null);
842 String accId = proxy.getAccessionIdFromQuery(q);
843 // dbr.setAccessionId(accId);
844 boolean rfound = false;
845 for (int r = 0, nr = rs.length; r < nr; r++)
849 List<DBRefEntry> found = DBRefUtils.searchRefs(rs[r].getDBRefs(),
851 if (!found.isEmpty())
867 * @return a standard title for any results retrieved using the currently
868 * selected source and settings
870 public String getDefaultRetrievalTitle()
872 return "Retrieved from "
873 + ((StringPair) database.getSelectedItem()).getDisplay();
877 * constructs an alignment frame given the data and metadata
881 * @param currentFileFormat
882 * @param preferredFeatureColours
883 * @return the alignment
885 public AlignmentI parseResult(AlignmentI al, String title,
886 FileFormatI currentFileFormat,
887 FeatureSettingsModelI preferredFeatureColours)
890 if (al != null && al.getHeight() > 0)
894 title = getDefaultRetrievalTitle();
896 if (alignFrame == null)
898 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
899 AlignFrame.DEFAULT_HEIGHT);
900 if (currentFileFormat != null)
902 af.currentFileFormat = currentFileFormat;
905 List<SequenceI> alsqs = al.getSequences();
908 for (SequenceI sq : alsqs)
910 if (sq.getFeatures().hasFeatures())
912 af.setShowSeqFeatures(true);
918 if (preferredFeatureColours != null)
920 af.getViewport().applyFeaturesStyle(preferredFeatureColours);
922 if (Cache.getDefault("HIDE_INTRONS", true))
924 af.hideFeatureColumns(SequenceOntologyI.EXON, false);
926 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
927 AlignFrame.DEFAULT_HEIGHT);
929 af.setStatus(MessageManager
930 .getString("label.successfully_pasted_alignment_file"));
934 af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN", false));
935 } catch (Exception ex)
941 alignFrame.viewport.addAlignment(al, title);
947 void showErrorMessage(final String error)
950 javax.swing.SwingUtilities.invokeLater(new Runnable()
955 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(), error,
956 MessageManager.getString("label.error_retrieving_data"),
957 JvOptionPane.WARNING_MESSAGE);
962 public IProgressIndicator getProgressIndicator()
964 return progressIndicator;
967 public void setProgressIndicator(IProgressIndicator progressIndicator)
969 this.progressIndicator = progressIndicator;
973 * Hide this panel (on clicking the database button to open the database
978 frame.setVisible(false);
981 public void setQuery(String ids)
983 textArea.setText(ids);
987 * Called to modify the search panel for embedding as an alternative tab of a
988 * free text search panel. The database choice list is hidden (since the
989 * choice has been made), and a Back button is made visible (which reopens the
990 * Sequence Fetcher panel).
994 public void embedIn(GFTSPanel parentPanel)
996 database.setVisible(false);
997 backBtn.setVisible(true);
998 parentSearchPanel = parentPanel;