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.ws.dbsources.das.api.DasSourceRegistryI;
35 import jalview.ws.seqfetcher.DbSourceProxy;
37 import java.awt.BorderLayout;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.KeyAdapter;
42 import java.awt.event.KeyEvent;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Iterator;
46 import java.util.List;
48 import javax.swing.JButton;
49 import javax.swing.JCheckBox;
50 import javax.swing.JInternalFrame;
51 import javax.swing.JLabel;
52 import javax.swing.JOptionPane;
53 import javax.swing.JPanel;
54 import javax.swing.JScrollPane;
55 import javax.swing.JTextArea;
56 import javax.swing.SwingConstants;
57 import javax.swing.tree.DefaultMutableTreeNode;
59 public class SequenceFetcher extends JPanel implements Runnable
61 JLabel dbeg = new JLabel();
63 JDatabaseTree database;
67 JLabel jLabel1 = new JLabel();
69 JCheckBox replacePunctuation = new JCheckBox();
71 JButton ok = new JButton();
73 JButton clear = new JButton();
75 JButton example = new JButton();
77 JButton close = new JButton();
79 JPanel jPanel1 = new JPanel();
81 JTextArea textArea = new JTextArea();
83 JScrollPane jScrollPane1 = new JScrollPane();
85 JPanel jPanel2 = new JPanel();
87 JPanel jPanel3 = new JPanel();
89 JPanel jPanel4 = new JPanel();
91 BorderLayout borderLayout1 = new BorderLayout();
93 BorderLayout borderLayout2 = new BorderLayout();
95 BorderLayout borderLayout3 = new BorderLayout();
99 IProgressIndicator guiWindow;
101 AlignFrame alignFrame;
105 final String noDbSelected = "-- Select Database --";
107 private static jalview.ws.SequenceFetcher sfetch = null;
109 private static long lastDasSourceRegistry = -3;
111 private static DasSourceRegistryI dasRegistry = null;
113 private static boolean _initingFetcher = false;
115 private static Thread initingThread = null;
117 int debounceTrap = 0;
119 public JTextArea getTextArea()
125 * Blocking method that initialises and returns the shared instance of the
126 * SequenceFetcher client
129 * - where the initialisation delay message should be shown
130 * @return the singleton instance of the sequence fetcher client
132 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
133 final IProgressIndicator guiWindow)
135 if (_initingFetcher && initingThread != null && initingThread.isAlive())
137 if (guiWindow != null)
142 .getString("status.waiting_sequence_database_fetchers_init"),
143 Thread.currentThread().hashCode());
145 // initting happening on another thread - so wait around to see if it
147 while (_initingFetcher && initingThread != null
148 && initingThread.isAlive())
153 } catch (Exception e)
158 if (guiWindow != null)
163 .getString("status.waiting_sequence_database_fetchers_init"),
164 Thread.currentThread().hashCode());
168 || dasRegistry != Cache.getDasSourceRegistry()
169 || lastDasSourceRegistry != (Cache.getDasSourceRegistry()
170 .getDasRegistryURL() + Cache
171 .getDasSourceRegistry().getLocalSourceString())
174 _initingFetcher = true;
175 initingThread = Thread.currentThread();
177 * give a visual indication that sequence fetcher construction is occuring
179 if (guiWindow != null)
181 guiWindow.setProgressBar(MessageManager
182 .getString("status.init_sequence_database_fetchers"),
183 Thread.currentThread().hashCode());
185 dasRegistry = Cache.getDasSourceRegistry();
186 dasRegistry.refreshSources();
188 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
189 if (guiWindow != null)
191 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
193 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
194 .getLocalSourceString()).hashCode();
196 _initingFetcher = false;
197 initingThread = null;
202 private IProgressIndicator progressIndicator;
204 public SequenceFetcher(IProgressIndicator guiIndic)
206 this.progressIndicator = guiIndic;
207 final SequenceFetcher us = this;
208 // launch initialiser thread
209 Thread sf = new Thread(new Runnable()
215 if (getSequenceFetcherSingleton(progressIndicator) != null)
217 us.initGui(progressIndicator);
221 javax.swing.SwingUtilities.invokeLater(new Runnable()
227 .showInternalMessageDialog(
230 .getString("warn.couldnt_create_sequence_fetcher_client"),
232 .getString("label.couldnt_create_sequence_fetcher"),
233 JOptionPane.ERROR_MESSAGE);
237 // raise warning dialog
244 private class DatabaseAuthority extends DefaultMutableTreeNode
249 private class DatabaseSource extends DefaultMutableTreeNode
255 * called by thread spawned by constructor
259 private void initGui(IProgressIndicator guiWindow)
261 this.guiWindow = guiWindow;
262 if (guiWindow instanceof AlignFrame)
264 alignFrame = (AlignFrame) guiWindow;
266 database = new JDatabaseTree(sfetch);
270 } catch (Exception ex)
272 ex.printStackTrace();
275 frame = new JInternalFrame();
276 frame.setContentPane(this);
277 if (new jalview.util.Platform().isAMac())
279 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
283 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
287 private String getFrameTitle()
289 return ((alignFrame == null) ? MessageManager
290 .getString("label.new_sequence_fetcher") : MessageManager
291 .getString("label.additional_sequence_fetcher"));
294 private void jbInit() throws Exception
296 this.setLayout(borderLayout2);
298 database.setFont(JvSwingUtils.getLabelFont());
299 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
300 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
301 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
302 jLabel1.setText(MessageManager
303 .getString("label.separate_multiple_accession_ids"));
305 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
307 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
308 replacePunctuation.setText(MessageManager
309 .getString("label.replace_commas_semicolons"));
310 ok.setText(MessageManager.getString("action.ok"));
311 ok.addActionListener(new ActionListener()
314 public void actionPerformed(ActionEvent e)
316 ok_actionPerformed();
319 clear.setText(MessageManager.getString("action.clear"));
320 clear.addActionListener(new ActionListener()
323 public void actionPerformed(ActionEvent e)
325 clear_actionPerformed();
329 example.setText(MessageManager.getString("label.example"));
330 example.addActionListener(new ActionListener()
333 public void actionPerformed(ActionEvent e)
335 example_actionPerformed();
338 close.setText(MessageManager.getString("action.close"));
339 close.addActionListener(new ActionListener()
342 public void actionPerformed(ActionEvent e)
344 close_actionPerformed(e);
347 textArea.setFont(JvSwingUtils.getLabelFont());
348 textArea.setLineWrap(true);
349 textArea.addKeyListener(new KeyAdapter()
352 public void keyPressed(KeyEvent e)
354 if (e.getKeyCode() == KeyEvent.VK_ENTER)
356 ok_actionPerformed();
360 jPanel3.setLayout(borderLayout1);
361 borderLayout1.setVgap(5);
363 jPanel1.add(example);
366 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
367 jPanel2.setLayout(borderLayout3);
368 databaseButt = database.getDatabaseSelectorButton();
369 databaseButt.setFont(JvSwingUtils.getLabelFont());
370 database.addActionListener(new ActionListener()
373 public void actionPerformed(ActionEvent e)
376 String currentSelection = database.getSelectedItem();
378 if (currentSelection.equalsIgnoreCase("pdb")
379 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
383 else if (currentSelection.equalsIgnoreCase("uniprot")
384 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
386 uniprotSourceAction();
392 database.action = -1;
397 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
398 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
399 JPanel jPanel2a = new JPanel(new BorderLayout());
400 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
401 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
402 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
403 // jPanel2.setPreferredSize(new Dimension())
404 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
405 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
406 this.add(jPanel3, java.awt.BorderLayout.CENTER);
407 this.add(jPanel2, java.awt.BorderLayout.NORTH);
408 jScrollPane1.getViewport().add(textArea);
411 * open the database tree
413 database.waitForInput();
416 private void pdbSourceAction()
418 databaseButt.setText(database.getSelectedItem());
419 new PDBFTSPanel(this);
423 private void uniprotSourceAction()
425 databaseButt.setText(database.getSelectedItem());
426 new UniprotFTSPanel(this);
429 private void otherSourceAction()
433 databaseButt.setText(database.getSelectedItem()
434 + (database.getSelectedSources().size() > 1 ? " (and "
435 + database.getSelectedSources().size() + " others)"
437 String eq = database.getExampleQueries();
438 dbeg.setText(MessageManager.formatMessage(
439 "label.example_query_param", new String[] { eq }));
440 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
441 for (DbSourceProxy dbs : database.getSelectedSources())
443 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
449 replacePunctuation.setEnabled(enablePunct);
451 } catch (Exception ex)
454 replacePunctuation.setEnabled(true);
459 protected void example_actionPerformed()
461 DbSourceProxy db = null;
464 textArea.setText(database.getExampleQueries());
465 } catch (Exception ex)
471 protected void clear_actionPerformed()
473 textArea.setText("");
477 public void close_actionPerformed(ActionEvent e)
481 frame.setClosed(true);
482 } catch (Exception ex)
487 public void ok_actionPerformed()
489 databaseButt.setEnabled(false);
490 example.setEnabled(false);
491 textArea.setEnabled(false);
492 ok.setEnabled(false);
493 close.setEnabled(false);
495 Thread worker = new Thread(this);
499 private void resetDialog()
501 databaseButt.setEnabled(true);
502 example.setEnabled(true);
503 textArea.setEnabled(true);
505 close.setEnabled(true);
512 if (!database.hasSelection())
514 error += "Please select the source database\n";
516 // TODO: make this transformation more configurable
517 com.stevesoft.pat.Regex empty;
518 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
520 empty = new com.stevesoft.pat.Regex(
521 // replace commas and spaces with a semicolon
522 "(\\s|[,; ])+", ";");
526 // just turn spaces and semicolons into single semicolons
527 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
529 textArea.setText(empty.replaceAll(textArea.getText()));
530 // see if there's anthing to search with
531 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
534 error += "Please enter a (semi-colon separated list of) database id(s)";
536 if (error.length() > 0)
538 showErrorMessage(error);
542 // TODO: Refactor to GUI independent code and write tests.
543 // indicate if successive sources should be merged into one alignment.
544 boolean addToLast = false;
545 List<String> aresultq = new ArrayList<String>();
546 List<String> presultTitle = new ArrayList<String>();
547 List<AlignmentI> presult = new ArrayList<AlignmentI>();
548 List<AlignmentI> aresult = new ArrayList<AlignmentI>();
549 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
552 List<String> nextFetch = Arrays.asList(qries = textArea.getText()
554 Iterator<String> en = Arrays.asList(new String[0]).iterator();
555 int nqueries = qries.length;
557 FeatureSettingsModelI preferredFeatureColours = null;
558 while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
560 if (!en.hasNext() && nextFetch.size() > 0)
562 en = nextFetch.iterator();
563 nqueries = nextFetch.size();
564 // save the remaining queries in the original array
565 qries = nextFetch.toArray(new String[nqueries]);
566 nextFetch = new ArrayList<String>();
569 DbSourceProxy proxy = proxies.next();
574 .setProgressBar(MessageManager.formatMessage(
575 "status.fetching_sequence_queries_from",
577 Integer.valueOf(nqueries).toString(),
578 proxy.getDbName() }), Thread.currentThread()
580 if (proxy.getMaximumQueryCount() == 1)
583 * proxy only handles one accession id at a time
587 String acc = en.next();
588 if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
597 * proxy can fetch multiple accessions at one time
599 fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
601 } catch (Exception e)
603 showErrorMessage("Error retrieving " + textArea.getText()
604 + " from " + database.getSelectedItem());
606 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
607 System.err.println("Retrieval failed for source ='"
608 + database.getSelectedItem() + "' and query\n'"
609 + textArea.getText() + "'\n");
611 } catch (OutOfMemoryError e)
613 showErrorMessage("Out of Memory when retrieving "
616 + database.getSelectedItem()
617 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
621 showErrorMessage("Serious Error retrieving " + textArea.getText()
622 + " from " + database.getSelectedItem());
626 // Stack results ready for opening in alignment windows
627 if (aresult != null && aresult.size() > 0)
629 FeatureSettingsModelI proxyColourScheme = proxy
630 .getFeatureColourScheme();
631 if (proxyColourScheme != null)
633 preferredFeatureColours = proxyColourScheme;
636 AlignmentI ar = null;
637 if (proxy.isAlignmentSource())
640 // new window for each result
641 while (aresult.size() > 0)
643 presult.add(aresult.remove(0));
644 presultTitle.add(aresultq.remove(0) + " "
645 + getDefaultRetrievalTitle());
651 if (addToLast && presult.size() > 0)
653 ar = presult.remove(presult.size() - 1);
654 titl = presultTitle.remove(presultTitle.size() - 1);
656 // concatenate all results in one window
657 while (aresult.size() > 0)
661 ar = aresult.remove(0);
665 ar.append(aresult.remove(0));
670 presultTitle.add(titl);
673 guiWindow.setProgressBar(MessageManager
674 .getString("status.finshed_querying"), Thread.currentThread()
677 guiWindow.setProgressBar(
678 (presult.size() > 0) ? MessageManager
679 .getString("status.parsing_results") : MessageManager
680 .getString("status.processing"), Thread.currentThread()
683 while (presult.size() > 0)
685 parseResult(presult.remove(0), presultTitle.remove(0), null,
686 preferredFeatureColours);
688 // only remove visual delay after we finished parsing.
689 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
690 if (nextFetch.size() > 0)
692 StringBuffer sb = new StringBuffer();
693 sb.append("Didn't retrieve the following "
694 + (nextFetch.size() == 1 ? "query" : nextFetch.size()
695 + " queries") + ": \n");
696 int l = sb.length(), lr = 0;
697 for (String s : nextFetch)
699 if (l != sb.length())
703 if (lr - sb.length() > 40)
709 showErrorMessage(sb.toString());
715 * Tries to fetch one or more accession ids from the database proxy
719 * the queries to fetch
721 * a successful queries list to add to
723 * a list of retrieved alignments to add to
725 * failed queries are added to this list
728 void fetchMultipleAccessions(DbSourceProxy proxy,
729 Iterator<String> accessions, List<String> aresultq,
730 List<AlignmentI> aresult, List<String> nextFetch)
733 StringBuilder multiacc = new StringBuilder();
734 List<String> tosend = new ArrayList<String>();
735 while (accessions.hasNext())
737 String nel = accessions.next();
739 multiacc.append(nel);
740 if (accessions.hasNext())
742 multiacc.append(proxy.getAccessionSeparator());
748 String query = multiacc.toString();
749 AlignmentI rslt = proxy.getSequenceRecords(query);
750 if (rslt == null || rslt.getHeight() == 0)
752 // no results - pass on all queries to next source
753 nextFetch.addAll(tosend);
759 if (tosend.size() > 1)
761 checkResultForQueries(rslt, tosend, nextFetch, proxy);
764 } catch (OutOfMemoryError oome)
766 new OOMWarning("fetching " + multiacc + " from "
767 + database.getSelectedItem(), oome, this);
772 * Query for a single accession id via the database proxy
777 * a list of successful queries to add to
779 * a list of retrieved alignments to add to
780 * @return true if the fetch was successful, else false
782 boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
783 List<String> aresultq, List<AlignmentI> aresult)
785 boolean success = false;
792 // give the server a chance to breathe
794 } catch (Exception e)
800 AlignmentI indres = null;
803 indres = proxy.getSequenceRecords(accession);
804 } catch (OutOfMemoryError oome)
806 new OOMWarning("fetching " + accession + " from "
807 + proxy.getDbName(), oome, this);
811 aresultq.add(accession);
815 } catch (Exception e)
818 "Error retrieving " + accession
819 + " from " + proxy.getDbName(), e);
827 * Checks which of the queries were successfully retrieved by searching the
828 * DBRefs of the retrieved sequences for a match. Any not found are added to
829 * the 'nextFetch' list.
836 void checkResultForQueries(AlignmentI rslt, List<String> queries,
837 List<String> nextFetch, DbSourceProxy proxy)
839 SequenceI[] rs = rslt.getSequencesArray();
841 for (String q : queries)
843 DBRefEntry[] found = null;
844 DBRefEntry dbr = new DBRefEntry();
845 dbr.setSource(proxy.getDbSource());
846 dbr.setVersion(null);
847 String accId = proxy.getAccessionIdFromQuery(q);
848 dbr.setAccessionId(accId);
849 boolean rfound = false;
850 for (int r = 0; r < rs.length; r++)
854 found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
855 if (found != null && found.length > 0)
871 * @return a standard title for any results retrieved using the currently
872 * selected source and settings
874 public String getDefaultRetrievalTitle()
876 return "Retrieved from " + database.getSelectedItem();
879 AlignmentI parseResult(AlignmentI al, String title,
880 String currentFileFormat,
881 FeatureSettingsModelI preferredFeatureColours)
884 if (al != null && al.getHeight() > 0)
888 title = getDefaultRetrievalTitle();
890 if (alignFrame == null)
892 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
893 AlignFrame.DEFAULT_HEIGHT);
894 if (currentFileFormat != null)
896 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
898 // NON-FormatAdapter Sourced
902 SequenceFeature[] sfs = null;
903 List<SequenceI> alsqs;
904 synchronized (alsqs = al.getSequences())
906 for (SequenceI sq : alsqs)
908 if ((sfs = sq.getSequenceFeatures()) != null)
912 af.setShowSeqFeatures(true);
920 if (preferredFeatureColours != null)
922 af.getViewport().applyFeaturesStyle(preferredFeatureColours);
924 if (Cache.getDefault("HIDE_INTRONS", true))
926 af.hideFeatureColumns(SequenceOntologyI.EXON, false);
929 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
930 AlignFrame.DEFAULT_HEIGHT);
932 af.statusBar.setText(MessageManager
933 .getString("label.successfully_pasted_alignment_file"));
937 af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
939 } catch (Exception ex)
945 alignFrame.viewport.addAlignment(al, title);
951 void showErrorMessage(final String error)
954 javax.swing.SwingUtilities.invokeLater(new Runnable()
959 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
960 MessageManager.getString("label.error_retrieving_data"),
961 JOptionPane.WARNING_MESSAGE);
966 public IProgressIndicator getProgressIndicator()
968 return progressIndicator;
971 public void setProgressIndicator(IProgressIndicator progressIndicator)
973 this.progressIndicator = progressIndicator;