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.FeatureSettingsI;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MessageManager;
30 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
31 import jalview.ws.seqfetcher.DbSourceProxy;
33 import java.awt.BorderLayout;
35 import java.awt.event.ActionEvent;
36 import java.awt.event.ActionListener;
37 import java.awt.event.KeyAdapter;
38 import java.awt.event.KeyEvent;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.Iterator;
42 import java.util.List;
44 import javax.swing.JButton;
45 import javax.swing.JCheckBox;
46 import javax.swing.JInternalFrame;
47 import javax.swing.JLabel;
48 import javax.swing.JOptionPane;
49 import javax.swing.JPanel;
50 import javax.swing.JScrollPane;
51 import javax.swing.JTextArea;
52 import javax.swing.SwingConstants;
53 import javax.swing.tree.DefaultMutableTreeNode;
55 public class SequenceFetcher extends JPanel implements Runnable
57 JLabel dbeg = new JLabel();
59 JDatabaseTree database;
63 JLabel jLabel1 = new JLabel();
65 JCheckBox replacePunctuation = new JCheckBox();
67 JButton ok = new JButton();
69 JButton clear = new JButton();
71 JButton example = new JButton();
73 JButton close = new JButton();
75 JPanel jPanel1 = new JPanel();
77 JTextArea textArea = new JTextArea();
79 JScrollPane jScrollPane1 = new JScrollPane();
81 JPanel jPanel2 = new JPanel();
83 JPanel jPanel3 = new JPanel();
85 JPanel jPanel4 = new JPanel();
87 BorderLayout borderLayout1 = new BorderLayout();
89 BorderLayout borderLayout2 = new BorderLayout();
91 BorderLayout borderLayout3 = new BorderLayout();
95 IProgressIndicator guiWindow;
97 AlignFrame alignFrame;
101 final String noDbSelected = "-- Select Database --";
103 private static jalview.ws.SequenceFetcher sfetch = null;
105 private static long lastDasSourceRegistry = -3;
107 private static DasSourceRegistryI dasRegistry = null;
109 private static boolean _initingFetcher = false;
111 private static Thread initingThread = null;
113 int debounceTrap = 0;
116 * Blocking method that initialises and returns the shared instance of the
117 * SequenceFetcher client
120 * - where the initialisation delay message should be shown
121 * @return the singleton instance of the sequence fetcher client
123 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
124 final IProgressIndicator guiWindow)
126 if (_initingFetcher && initingThread != null && initingThread.isAlive())
128 if (guiWindow != null)
133 .getString("status.waiting_sequence_database_fetchers_init"),
134 Thread.currentThread().hashCode());
136 // initting happening on another thread - so wait around to see if it
138 while (_initingFetcher && initingThread != null
139 && initingThread.isAlive())
144 } catch (Exception e)
149 if (guiWindow != null)
154 .getString("status.waiting_sequence_database_fetchers_init"),
155 Thread.currentThread().hashCode());
159 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
160 || lastDasSourceRegistry != (jalview.bin.Cache
161 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
162 .getDasSourceRegistry().getLocalSourceString())
165 _initingFetcher = true;
166 initingThread = Thread.currentThread();
168 * give a visual indication that sequence fetcher construction is occuring
170 if (guiWindow != null)
172 guiWindow.setProgressBar(MessageManager
173 .getString("status.init_sequence_database_fetchers"),
174 Thread.currentThread().hashCode());
176 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
177 dasRegistry.refreshSources();
179 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
180 if (guiWindow != null)
182 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
184 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
185 .getLocalSourceString()).hashCode();
187 _initingFetcher = false;
188 initingThread = null;
193 private IProgressIndicator progressIndicator;
195 public SequenceFetcher(IProgressIndicator guiIndic)
197 this.progressIndicator = guiIndic;
198 final SequenceFetcher us = this;
199 // launch initialiser thread
200 Thread sf = new Thread(new Runnable()
206 if (getSequenceFetcherSingleton(progressIndicator) != null)
208 us.initGui(progressIndicator);
212 javax.swing.SwingUtilities.invokeLater(new Runnable()
218 .showInternalMessageDialog(
221 .getString("warn.couldnt_create_sequence_fetcher_client"),
223 .getString("label.couldnt_create_sequence_fetcher"),
224 JOptionPane.ERROR_MESSAGE);
228 // raise warning dialog
235 private class DatabaseAuthority extends DefaultMutableTreeNode
240 private class DatabaseSource extends DefaultMutableTreeNode
246 * called by thread spawned by constructor
250 private void initGui(IProgressIndicator guiWindow)
252 this.guiWindow = guiWindow;
253 if (guiWindow instanceof AlignFrame)
255 alignFrame = (AlignFrame) guiWindow;
257 database = new JDatabaseTree(sfetch);
261 } catch (Exception ex)
263 ex.printStackTrace();
266 frame = new JInternalFrame();
267 frame.setContentPane(this);
268 if (new jalview.util.Platform().isAMac())
270 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
274 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
278 private String getFrameTitle()
280 return ((alignFrame == null) ? MessageManager
281 .getString("label.new_sequence_fetcher") : MessageManager
282 .getString("label.additional_sequence_fetcher"));
285 private void jbInit() throws Exception
287 this.setLayout(borderLayout2);
289 database.setFont(JvSwingUtils.getLabelFont());
290 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
291 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
292 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
293 jLabel1.setText(MessageManager
294 .getString("label.separate_multiple_accession_ids"));
296 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
298 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
299 replacePunctuation.setText(MessageManager
300 .getString("label.replace_commas_semicolons"));
301 ok.setText(MessageManager.getString("action.ok"));
302 ok.addActionListener(new ActionListener()
305 public void actionPerformed(ActionEvent e)
307 ok_actionPerformed();
310 clear.setText(MessageManager.getString("action.clear"));
311 clear.addActionListener(new ActionListener()
314 public void actionPerformed(ActionEvent e)
316 clear_actionPerformed();
320 example.setText(MessageManager.getString("label.example"));
321 example.addActionListener(new ActionListener()
324 public void actionPerformed(ActionEvent e)
326 example_actionPerformed();
329 close.setText(MessageManager.getString("action.close"));
330 close.addActionListener(new ActionListener()
333 public void actionPerformed(ActionEvent e)
335 close_actionPerformed(e);
338 textArea.setFont(JvSwingUtils.getLabelFont());
339 textArea.setLineWrap(true);
340 textArea.addKeyListener(new KeyAdapter()
343 public void keyPressed(KeyEvent e)
345 if (e.getKeyCode() == KeyEvent.VK_ENTER)
347 ok_actionPerformed();
351 jPanel3.setLayout(borderLayout1);
352 borderLayout1.setVgap(5);
354 jPanel1.add(example);
357 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
358 jPanel2.setLayout(borderLayout3);
359 databaseButt = database.getDatabaseSelectorButton();
360 databaseButt.setFont(JvSwingUtils.getLabelFont());
361 database.addActionListener(new ActionListener()
364 public void actionPerformed(ActionEvent e)
367 String currentSelection = database.getSelectedItem();
368 if (!currentSelection.equalsIgnoreCase("pdb"))
372 if (currentSelection.equalsIgnoreCase("pdb")
373 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
377 database.action = -1;
382 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
383 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
384 JPanel jPanel2a = new JPanel(new BorderLayout());
385 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
386 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
387 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
388 // jPanel2.setPreferredSize(new Dimension())
389 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
390 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
391 this.add(jPanel3, java.awt.BorderLayout.CENTER);
392 this.add(jPanel2, java.awt.BorderLayout.NORTH);
393 jScrollPane1.getViewport().add(textArea);
397 private void pdbSourceAction()
399 databaseButt.setText(database.getSelectedItem());
400 new PDBSearchPanel(this);
404 private void otherSourceAction()
408 databaseButt.setText(database.getSelectedItem()
409 + (database.getSelectedSources().size() > 1 ? " (and "
410 + database.getSelectedSources().size() + " others)"
412 String eq = database.getExampleQueries();
413 dbeg.setText(MessageManager.formatMessage(
414 "label.example_query_param", new String[] { eq }));
415 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
416 for (DbSourceProxy dbs : database.getSelectedSources())
418 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
424 replacePunctuation.setEnabled(enablePunct);
426 } catch (Exception ex)
429 replacePunctuation.setEnabled(true);
434 protected void example_actionPerformed()
436 DbSourceProxy db = null;
439 textArea.setText(database.getExampleQueries());
440 } catch (Exception ex)
446 protected void clear_actionPerformed()
448 textArea.setText("");
452 public void close_actionPerformed(ActionEvent e)
456 frame.setClosed(true);
457 } catch (Exception ex)
462 public void ok_actionPerformed()
464 databaseButt.setEnabled(false);
465 example.setEnabled(false);
466 textArea.setEnabled(false);
467 ok.setEnabled(false);
468 close.setEnabled(false);
470 Thread worker = new Thread(this);
474 private void resetDialog()
476 databaseButt.setEnabled(true);
477 example.setEnabled(true);
478 textArea.setEnabled(true);
480 close.setEnabled(true);
487 if (!database.hasSelection())
489 error += "Please select the source database\n";
491 // TODO: make this transformation more configurable
492 com.stevesoft.pat.Regex empty;
493 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
495 empty = new com.stevesoft.pat.Regex(
496 // replace commas and spaces with a semicolon
497 "(\\s|[,; ])+", ";");
501 // just turn spaces and semicolons into single semicolons
502 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
504 textArea.setText(empty.replaceAll(textArea.getText()));
505 // see if there's anthing to search with
506 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
509 error += "Please enter a (semi-colon separated list of) database id(s)";
511 if (error.length() > 0)
513 showErrorMessage(error);
517 // TODO: Refactor to GUI independent code and write tests.
518 // indicate if successive sources should be merged into one alignment.
519 boolean addToLast = false;
520 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
521 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
522 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
525 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
527 Iterator<String> en = Arrays.asList(new String[0]).iterator();
528 int nqueries = qries.length;
530 FeatureSettingsI preferredFeatureColours = null;
531 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
533 if (!en.hasNext() && nextfetch.size() > 0)
535 en = nextfetch.iterator();
536 nqueries = nextfetch.size();
537 // save the remaining queries in the original array
538 qries = nextfetch.toArray(new String[nqueries]);
539 nextfetch = new ArrayList<String>();
542 DbSourceProxy proxy = proxies.next();
543 boolean isAliSource = false;
548 .setProgressBar(MessageManager.formatMessage(
549 "status.fetching_sequence_queries_from",
551 Integer.valueOf(nqueries).toString(),
552 proxy.getDbName() }), Thread.currentThread()
554 isAliSource = proxy.isAlignmentSource();
555 if (proxy.getAccessionSeparator() == null)
559 String item = en.next();
566 // give the server a chance to breathe
568 } catch (Exception e)
575 AlignmentI indres = null;
578 indres = proxy.getSequenceRecords(item);
579 } catch (OutOfMemoryError oome)
581 new OOMWarning("fetching " + item + " from "
582 + proxy.getDbName(), oome, this);
593 } catch (Exception e)
595 jalview.bin.Cache.log.info("Error retrieving " + item
596 + " from " + proxy.getDbName(), e);
603 StringBuffer multiacc = new StringBuffer();
604 ArrayList<String> tosend = new ArrayList<String>();
607 String nel = en.next();
609 multiacc.append(nel);
612 multiacc.append(proxy.getAccessionSeparator());
619 List<String> nores = new ArrayList<String>();
620 rslt = proxy.getSequenceRecords(multiacc.toString());
621 if (rslt == null || rslt.getHeight() == 0)
623 // no results - pass on all queries to next source
624 nextfetch.addAll(tosend);
628 aresultq.add(multiacc.toString());
631 rs = rslt.getSequencesArray();
632 // search for each query in the dbrefs associated with each
635 // ones we do not find will be used to query next source (if any)
636 for (String q : tosend)
638 DBRefEntry dbr = new DBRefEntry(), found[] = null;
639 dbr.setSource(proxy.getDbSource());
640 dbr.setVersion(null);
641 String accId = proxy.getAccessionIdFromQuery(q);
642 dbr.setAccessionId(accId);
643 boolean rfound = false;
644 for (int r = 0; r < rs.length; r++)
648 found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
649 if (found != null && found.length > 0)
662 } catch (OutOfMemoryError oome)
664 new OOMWarning("fetching " + multiacc + " from "
665 + database.getSelectedItem(), oome, this);
669 } catch (Exception e)
671 showErrorMessage("Error retrieving " + textArea.getText()
672 + " from " + database.getSelectedItem());
674 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
675 System.err.println("Retrieval failed for source ='"
676 + database.getSelectedItem() + "' and query\n'"
677 + textArea.getText() + "'\n");
679 } catch (OutOfMemoryError e)
681 // resets dialog box - so we don't use OOMwarning here.
682 showErrorMessage("Out of Memory when retrieving "
685 + database.getSelectedItem()
686 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
690 showErrorMessage("Serious Error retrieving " + textArea.getText()
691 + " from " + database.getSelectedItem());
694 // Stack results ready for opening in alignment windows
695 if (aresult != null && aresult.size() > 0)
697 FeatureSettingsI proxyColourScheme = proxy.getFeatureColourScheme();
698 if (proxyColourScheme != null)
700 preferredFeatureColours = proxyColourScheme;
703 AlignmentI ar = null;
707 // new window for each result
708 while (aresult.size() > 0)
710 presult.add(aresult.remove(0));
711 presultTitle.add(aresultq.remove(0) + " "
712 + getDefaultRetrievalTitle());
718 if (addToLast && presult.size() > 0)
720 ar = presult.remove(presult.size() - 1);
721 titl = presultTitle.remove(presultTitle.size() - 1);
723 // concatenate all results in one window
724 while (aresult.size() > 0)
728 ar = aresult.remove(0);
732 ar.append(aresult.remove(0));
738 presultTitle.add(titl);
741 guiWindow.setProgressBar(MessageManager
742 .getString("status.finshed_querying"), Thread.currentThread()
745 guiWindow.setProgressBar(
746 (presult.size() > 0) ? MessageManager
747 .getString("status.parsing_results") : MessageManager
748 .getString("status.processing"), Thread.currentThread()
751 while (presult.size() > 0)
753 parseResult(presult.remove(0), presultTitle.remove(0), null,
754 preferredFeatureColours);
756 // only remove visual delay after we finished parsing.
757 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
758 if (nextfetch.size() > 0)
760 StringBuffer sb = new StringBuffer();
761 sb.append("Didn't retrieve the following "
762 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
763 + " queries") + ": \n");
764 int l = sb.length(), lr = 0;
765 for (String s : nextfetch)
767 if (l != sb.length())
771 if (lr - sb.length() > 40)
777 showErrorMessage(sb.toString());
784 * @return a standard title for any results retrieved using the currently
785 * selected source and settings
787 public String getDefaultRetrievalTitle()
789 return "Retrieved from " + database.getSelectedItem();
792 AlignmentI parseResult(AlignmentI al, String title,
793 String currentFileFormat, FeatureSettingsI preferredFeatureColours)
796 if (al != null && al.getHeight() > 0)
800 title = getDefaultRetrievalTitle();
802 if (alignFrame == null)
804 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
805 AlignFrame.DEFAULT_HEIGHT);
806 if (currentFileFormat != null)
808 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
810 // NON-FormatAdapter Sourced
814 SequenceFeature[] sfs = null;
815 List<SequenceI> alsqs;
816 synchronized (alsqs = al.getSequences())
818 for (SequenceI sq : alsqs)
820 if ((sfs = sq.getSequenceFeatures()) != null)
824 af.setShowSeqFeatures(true);
832 if (preferredFeatureColours != null)
834 af.viewport.applyFeaturesStyle(preferredFeatureColours);
836 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
837 AlignFrame.DEFAULT_HEIGHT);
839 af.statusBar.setText(MessageManager
840 .getString("label.successfully_pasted_alignment_file"));
844 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
846 } catch (Exception ex)
852 alignFrame.viewport.addAlignment(al, title);
858 void showErrorMessage(final String error)
861 javax.swing.SwingUtilities.invokeLater(new Runnable()
866 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
867 MessageManager.getString("label.error_retrieving_data"),
868 JOptionPane.WARNING_MESSAGE);
873 public IProgressIndicator getProgressIndicator()
875 return progressIndicator;
878 public void setProgressIndicator(IProgressIndicator progressIndicator)
880 this.progressIndicator = progressIndicator;