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 public JTextArea getTextArea()
124 * Blocking method that initialises and returns the shared instance of the
125 * SequenceFetcher client
128 * - where the initialisation delay message should be shown
129 * @return the singleton instance of the sequence fetcher client
131 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
132 final IProgressIndicator guiWindow)
134 if (_initingFetcher && initingThread != null && initingThread.isAlive())
136 if (guiWindow != null)
141 .getString("status.waiting_sequence_database_fetchers_init"),
142 Thread.currentThread().hashCode());
144 // initting happening on another thread - so wait around to see if it
146 while (_initingFetcher && initingThread != null
147 && initingThread.isAlive())
152 } catch (Exception e)
157 if (guiWindow != null)
162 .getString("status.waiting_sequence_database_fetchers_init"),
163 Thread.currentThread().hashCode());
167 || dasRegistry != Cache.getDasSourceRegistry()
168 || lastDasSourceRegistry != (Cache.getDasSourceRegistry()
169 .getDasRegistryURL() + Cache
170 .getDasSourceRegistry().getLocalSourceString())
173 _initingFetcher = true;
174 initingThread = Thread.currentThread();
176 * give a visual indication that sequence fetcher construction is occuring
178 if (guiWindow != null)
180 guiWindow.setProgressBar(MessageManager
181 .getString("status.init_sequence_database_fetchers"),
182 Thread.currentThread().hashCode());
184 dasRegistry = Cache.getDasSourceRegistry();
185 dasRegistry.refreshSources();
187 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
188 if (guiWindow != null)
190 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
192 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
193 .getLocalSourceString()).hashCode();
195 _initingFetcher = false;
196 initingThread = null;
201 private IProgressIndicator progressIndicator;
203 public SequenceFetcher(IProgressIndicator guiIndic)
205 this.progressIndicator = guiIndic;
206 final SequenceFetcher us = this;
207 // launch initialiser thread
208 Thread sf = new Thread(new Runnable()
214 if (getSequenceFetcherSingleton(progressIndicator) != null)
216 us.initGui(progressIndicator);
220 javax.swing.SwingUtilities.invokeLater(new Runnable()
226 .showInternalMessageDialog(
229 .getString("warn.couldnt_create_sequence_fetcher_client"),
231 .getString("label.couldnt_create_sequence_fetcher"),
232 JOptionPane.ERROR_MESSAGE);
236 // raise warning dialog
243 private class DatabaseAuthority extends DefaultMutableTreeNode
248 private class DatabaseSource extends DefaultMutableTreeNode
254 * called by thread spawned by constructor
258 private void initGui(IProgressIndicator guiWindow)
260 this.guiWindow = guiWindow;
261 if (guiWindow instanceof AlignFrame)
263 alignFrame = (AlignFrame) guiWindow;
265 database = new JDatabaseTree(sfetch);
269 } catch (Exception ex)
271 ex.printStackTrace();
274 frame = new JInternalFrame();
275 frame.setContentPane(this);
276 if (Platform.isAMac())
278 Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 240);
282 Desktop.addInternalFrame(frame, getFrameTitle(), false, 400, 180);
286 private String getFrameTitle()
288 return ((alignFrame == null) ? MessageManager
289 .getString("label.new_sequence_fetcher") : MessageManager
290 .getString("label.additional_sequence_fetcher"));
293 private void jbInit() throws Exception
295 this.setLayout(borderLayout2);
297 database.setFont(JvSwingUtils.getLabelFont());
298 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
299 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
300 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
301 jLabel1.setText(MessageManager
302 .getString("label.separate_multiple_accession_ids"));
304 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
306 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
307 replacePunctuation.setText(MessageManager
308 .getString("label.replace_commas_semicolons"));
309 ok.setText(MessageManager.getString("action.ok"));
310 ok.addActionListener(new ActionListener()
313 public void actionPerformed(ActionEvent e)
315 ok_actionPerformed();
318 clear.setText(MessageManager.getString("action.clear"));
319 clear.addActionListener(new ActionListener()
322 public void actionPerformed(ActionEvent e)
324 clear_actionPerformed();
328 example.setText(MessageManager.getString("label.example"));
329 example.addActionListener(new ActionListener()
332 public void actionPerformed(ActionEvent e)
334 example_actionPerformed();
337 close.setText(MessageManager.getString("action.close"));
338 close.addActionListener(new ActionListener()
341 public void actionPerformed(ActionEvent e)
343 close_actionPerformed(e);
346 textArea.setFont(JvSwingUtils.getLabelFont());
347 textArea.setLineWrap(true);
348 textArea.addKeyListener(new KeyAdapter()
351 public void keyPressed(KeyEvent e)
353 if (e.getKeyCode() == KeyEvent.VK_ENTER)
355 ok_actionPerformed();
359 jPanel3.setLayout(borderLayout1);
360 borderLayout1.setVgap(5);
362 jPanel1.add(example);
365 jPanel2.setLayout(borderLayout3);
366 databaseButt = /*database.getDatabaseSelectorButton();
367 final JButton viewdbs =*/new JButton(
368 MessageManager.getString("action.select_ddbb"));
369 databaseButt.addActionListener(new ActionListener()
373 public void actionPerformed(ActionEvent arg0)
376 database.showDialog();
379 databaseButt.setFont(JvSwingUtils.getLabelFont());
380 database.addActionListener(new ActionListener()
383 public void actionPerformed(ActionEvent e)
385 String currentSelection = database.getSelectedItem();
386 if (currentSelection == null)
388 close_actionPerformed(null);
393 if ("pdb".equalsIgnoreCase(currentSelection))
397 else if ("uniprot".equalsIgnoreCase(currentSelection))
399 uniprotSourceAction();
405 database.action = -1;
410 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
411 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
412 JPanel jPanel2a = new JPanel(new BorderLayout());
413 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
414 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
415 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
416 // jPanel2.setPreferredSize(new Dimension())
417 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
418 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
419 this.add(jPanel3, java.awt.BorderLayout.CENTER);
420 this.add(jPanel2, java.awt.BorderLayout.NORTH);
421 jScrollPane1.getViewport().add(textArea);
424 * open the database tree
426 database.waitForInput();
429 private void pdbSourceAction()
431 databaseButt.setText(database.getSelectedItem());
432 new PDBFTSPanel(this);
436 private void uniprotSourceAction()
438 databaseButt.setText(database.getSelectedItem());
439 new UniprotFTSPanel(this);
442 private void otherSourceAction()
446 databaseButt.setText(database.getSelectedItem()
447 + (database.getSelectedSources().size() > 1 ? " (and "
448 + database.getSelectedSources().size() + " others)"
450 String eq = database.getExampleQueries();
451 dbeg.setText(MessageManager.formatMessage(
452 "label.example_query_param", new String[] { eq }));
453 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
454 for (DbSourceProxy dbs : database.getSelectedSources())
456 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
462 replacePunctuation.setEnabled(enablePunct);
464 } catch (Exception ex)
467 replacePunctuation.setEnabled(true);
472 protected void example_actionPerformed()
474 DbSourceProxy db = null;
477 textArea.setText(database.getExampleQueries());
478 } catch (Exception ex)
484 protected void clear_actionPerformed()
486 textArea.setText("");
490 public void close_actionPerformed(ActionEvent e)
494 frame.setClosed(true);
495 } catch (Exception ex)
500 public void ok_actionPerformed()
502 databaseButt.setEnabled(false);
503 example.setEnabled(false);
504 textArea.setEnabled(false);
505 ok.setEnabled(false);
506 close.setEnabled(false);
508 Thread worker = new Thread(this);
512 private void resetDialog()
514 databaseButt.setEnabled(true);
515 example.setEnabled(true);
516 textArea.setEnabled(true);
518 close.setEnabled(true);
525 if (!database.hasSelection())
527 error += "Please select the source database\n";
529 // TODO: make this transformation more configurable
530 com.stevesoft.pat.Regex empty;
531 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
533 empty = new com.stevesoft.pat.Regex(
534 // replace commas and spaces with a semicolon
535 "(\\s|[,; ])+", ";");
539 // just turn spaces and semicolons into single semicolons
540 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
542 textArea.setText(empty.replaceAll(textArea.getText()));
543 // see if there's anthing to search with
544 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
547 error += "Please enter a (semi-colon separated list of) database id(s)";
549 if (error.length() > 0)
551 showErrorMessage(error);
555 // TODO: Refactor to GUI independent code and write tests.
556 // indicate if successive sources should be merged into one alignment.
557 boolean addToLast = false;
558 List<String> aresultq = new ArrayList<String>();
559 List<String> presultTitle = new ArrayList<String>();
560 List<AlignmentI> presult = new ArrayList<AlignmentI>();
561 List<AlignmentI> aresult = new ArrayList<AlignmentI>();
562 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
565 List<String> nextFetch = Arrays.asList(qries = textArea.getText()
567 Iterator<String> en = Arrays.asList(new String[0]).iterator();
568 int nqueries = qries.length;
570 FeatureSettingsModelI preferredFeatureColours = null;
571 while (proxies.hasNext() && (en.hasNext() || nextFetch.size() > 0))
573 if (!en.hasNext() && nextFetch.size() > 0)
575 en = nextFetch.iterator();
576 nqueries = nextFetch.size();
577 // save the remaining queries in the original array
578 qries = nextFetch.toArray(new String[nqueries]);
579 nextFetch = new ArrayList<String>();
582 DbSourceProxy proxy = proxies.next();
587 .setProgressBar(MessageManager.formatMessage(
588 "status.fetching_sequence_queries_from",
590 Integer.valueOf(nqueries).toString(),
591 proxy.getDbName() }), Thread.currentThread()
593 if (proxy.getMaximumQueryCount() == 1)
596 * proxy only handles one accession id at a time
600 String acc = en.next();
601 if (!fetchSingleAccession(proxy, acc, aresultq, aresult))
610 * proxy can fetch multiple accessions at one time
612 fetchMultipleAccessions(proxy, en, aresultq, aresult, nextFetch);
614 } catch (Exception e)
616 showErrorMessage("Error retrieving " + textArea.getText()
617 + " from " + database.getSelectedItem());
619 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
620 System.err.println("Retrieval failed for source ='"
621 + database.getSelectedItem() + "' and query\n'"
622 + textArea.getText() + "'\n");
624 } catch (OutOfMemoryError e)
626 showErrorMessage("Out of Memory when retrieving "
629 + database.getSelectedItem()
630 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
634 showErrorMessage("Serious Error retrieving " + textArea.getText()
635 + " from " + database.getSelectedItem());
639 // Stack results ready for opening in alignment windows
640 if (aresult != null && aresult.size() > 0)
642 FeatureSettingsModelI proxyColourScheme = proxy
643 .getFeatureColourScheme();
644 if (proxyColourScheme != null)
646 preferredFeatureColours = proxyColourScheme;
649 AlignmentI ar = null;
650 if (proxy.isAlignmentSource())
653 // new window for each result
654 while (aresult.size() > 0)
656 presult.add(aresult.remove(0));
657 presultTitle.add(aresultq.remove(0) + " "
658 + getDefaultRetrievalTitle());
664 if (addToLast && presult.size() > 0)
666 ar = presult.remove(presult.size() - 1);
667 titl = presultTitle.remove(presultTitle.size() - 1);
669 // concatenate all results in one window
670 while (aresult.size() > 0)
674 ar = aresult.remove(0);
678 ar.append(aresult.remove(0));
683 presultTitle.add(titl);
686 guiWindow.setProgressBar(MessageManager
687 .getString("status.finshed_querying"), Thread.currentThread()
690 guiWindow.setProgressBar(
691 (presult.size() > 0) ? MessageManager
692 .getString("status.parsing_results") : MessageManager
693 .getString("status.processing"), Thread.currentThread()
696 while (presult.size() > 0)
698 parseResult(presult.remove(0), presultTitle.remove(0), null,
699 preferredFeatureColours);
701 // only remove visual delay after we finished parsing.
702 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
703 if (nextFetch.size() > 0)
705 StringBuffer sb = new StringBuffer();
706 sb.append("Didn't retrieve the following "
707 + (nextFetch.size() == 1 ? "query" : nextFetch.size()
708 + " queries") + ": \n");
709 int l = sb.length(), lr = 0;
710 for (String s : nextFetch)
712 if (l != sb.length())
716 if (lr - sb.length() > 40)
722 showErrorMessage(sb.toString());
728 * Tries to fetch one or more accession ids from the database proxy
732 * the queries to fetch
734 * a successful queries list to add to
736 * a list of retrieved alignments to add to
738 * failed queries are added to this list
741 void fetchMultipleAccessions(DbSourceProxy proxy,
742 Iterator<String> accessions, List<String> aresultq,
743 List<AlignmentI> aresult, List<String> nextFetch)
746 StringBuilder multiacc = new StringBuilder();
747 List<String> tosend = new ArrayList<String>();
748 while (accessions.hasNext())
750 String nel = accessions.next();
752 multiacc.append(nel);
753 if (accessions.hasNext())
755 multiacc.append(proxy.getAccessionSeparator());
761 String query = multiacc.toString();
762 AlignmentI rslt = proxy.getSequenceRecords(query);
763 if (rslt == null || rslt.getHeight() == 0)
765 // no results - pass on all queries to next source
766 nextFetch.addAll(tosend);
772 if (tosend.size() > 1)
774 checkResultForQueries(rslt, tosend, nextFetch, proxy);
777 } catch (OutOfMemoryError oome)
779 new OOMWarning("fetching " + multiacc + " from "
780 + database.getSelectedItem(), oome, this);
785 * Query for a single accession id via the database proxy
790 * a list of successful queries to add to
792 * a list of retrieved alignments to add to
793 * @return true if the fetch was successful, else false
795 boolean fetchSingleAccession(DbSourceProxy proxy, String accession,
796 List<String> aresultq, List<AlignmentI> aresult)
798 boolean success = false;
805 // give the server a chance to breathe
807 } catch (Exception e)
813 AlignmentI indres = null;
816 indres = proxy.getSequenceRecords(accession);
817 } catch (OutOfMemoryError oome)
819 new OOMWarning("fetching " + accession + " from "
820 + proxy.getDbName(), oome, this);
824 aresultq.add(accession);
828 } catch (Exception e)
831 "Error retrieving " + accession
832 + " from " + proxy.getDbName(), e);
838 * Checks which of the queries were successfully retrieved by searching the
839 * DBRefs of the retrieved sequences for a match. Any not found are added to
840 * the 'nextFetch' list.
847 void checkResultForQueries(AlignmentI rslt, List<String> queries,
848 List<String> nextFetch, DbSourceProxy proxy)
850 SequenceI[] rs = rslt.getSequencesArray();
852 for (String q : queries)
854 DBRefEntry dbr = new DBRefEntry();
855 dbr.setSource(proxy.getDbSource());
856 dbr.setVersion(null);
857 String accId = proxy.getAccessionIdFromQuery(q);
858 dbr.setAccessionId(accId);
859 boolean rfound = false;
860 for (int r = 0; r < rs.length; r++)
864 List<DBRefEntry> found = DBRefUtils.searchRefs(rs[r].getDBRefs(),
866 if (!found.isEmpty())
882 * @return a standard title for any results retrieved using the currently
883 * selected source and settings
885 public String getDefaultRetrievalTitle()
887 return "Retrieved from " + database.getSelectedItem();
890 AlignmentI parseResult(AlignmentI al, String title,
891 String currentFileFormat,
892 FeatureSettingsModelI preferredFeatureColours)
895 if (al != null && al.getHeight() > 0)
899 title = getDefaultRetrievalTitle();
901 if (alignFrame == null)
903 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
904 AlignFrame.DEFAULT_HEIGHT);
905 if (currentFileFormat != null)
907 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
909 // NON-FormatAdapter Sourced
913 SequenceFeature[] sfs = null;
914 List<SequenceI> alsqs;
915 synchronized (alsqs = al.getSequences())
917 for (SequenceI sq : alsqs)
919 if ((sfs = sq.getSequenceFeatures()) != null)
923 af.setShowSeqFeatures(true);
931 if (preferredFeatureColours != null)
933 af.getViewport().applyFeaturesStyle(preferredFeatureColours);
935 if (Cache.getDefault("HIDE_INTRONS", true))
937 af.hideFeatureColumns(SequenceOntologyI.EXON, false);
940 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
941 AlignFrame.DEFAULT_HEIGHT);
943 af.statusBar.setText(MessageManager
944 .getString("label.successfully_pasted_alignment_file"));
948 af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
950 } catch (Exception ex)
956 alignFrame.viewport.addAlignment(al, title);
962 void showErrorMessage(final String error)
965 javax.swing.SwingUtilities.invokeLater(new Runnable()
970 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
971 MessageManager.getString("label.error_retrieving_data"),
972 JOptionPane.WARNING_MESSAGE);
977 public IProgressIndicator getProgressIndicator()
979 return progressIndicator;
982 public void setProgressIndicator(IProgressIndicator progressIndicator)
984 this.progressIndicator = progressIndicator;
988 * Make this panel visible (after a selection has been made in the database
993 frame.setVisible(true);
997 * Hide this panel (on clicking the database button to open the database
1002 frame.setVisible(false);