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.datamodel.AlignmentI;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.FormatAdapter;
29 import jalview.io.IdentifyFile;
30 import jalview.util.DBRefUtils;
31 import jalview.util.MessageManager;
32 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
33 import jalview.ws.seqfetcher.DbSourceProxy;
35 import java.awt.BorderLayout;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.KeyAdapter;
40 import java.awt.event.KeyEvent;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Iterator;
44 import java.util.List;
46 import javax.swing.JButton;
47 import javax.swing.JCheckBox;
48 import javax.swing.JInternalFrame;
49 import javax.swing.JLabel;
50 import javax.swing.JOptionPane;
51 import javax.swing.JPanel;
52 import javax.swing.JScrollPane;
53 import javax.swing.JTextArea;
54 import javax.swing.SwingConstants;
55 import javax.swing.tree.DefaultMutableTreeNode;
57 public class SequenceFetcher extends JPanel implements Runnable
59 JLabel dbeg = new JLabel();
61 JDatabaseTree database;
65 JLabel jLabel1 = new JLabel();
67 JCheckBox replacePunctuation = new JCheckBox();
69 JButton ok = new JButton();
71 JButton clear = new JButton();
73 JButton example = new JButton();
75 JButton close = new JButton();
77 JPanel jPanel1 = new JPanel();
79 JTextArea textArea = new JTextArea();
81 JScrollPane jScrollPane1 = new JScrollPane();
83 JPanel jPanel2 = new JPanel();
85 JPanel jPanel3 = new JPanel();
87 JPanel jPanel4 = new JPanel();
89 BorderLayout borderLayout1 = new BorderLayout();
91 BorderLayout borderLayout2 = new BorderLayout();
93 BorderLayout borderLayout3 = new BorderLayout();
97 IProgressIndicator guiWindow;
99 AlignFrame alignFrame;
103 final String noDbSelected = "-- Select Database --";
105 private static jalview.ws.SequenceFetcher sfetch = null;
107 private static long lastDasSourceRegistry = -3;
109 private static DasSourceRegistryI dasRegistry = null;
111 private static boolean _initingFetcher = false;
113 private static Thread initingThread = null;
115 int debounceTrap = 0;
118 * Blocking method that initialises and returns the shared instance of the
119 * SequenceFetcher client
122 * - where the initialisation delay message should be shown
123 * @return the singleton instance of the sequence fetcher client
125 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
126 final IProgressIndicator guiWindow)
128 if (_initingFetcher && initingThread != null && initingThread.isAlive())
130 if (guiWindow != null)
135 .getString("status.waiting_sequence_database_fetchers_init"),
136 Thread.currentThread().hashCode());
138 // initting happening on another thread - so wait around to see if it
140 while (_initingFetcher && initingThread != null
141 && initingThread.isAlive())
146 } catch (Exception e)
151 if (guiWindow != null)
156 .getString("status.waiting_sequence_database_fetchers_init"),
157 Thread.currentThread().hashCode());
161 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
162 || lastDasSourceRegistry != (jalview.bin.Cache
163 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
164 .getDasSourceRegistry().getLocalSourceString())
167 _initingFetcher = true;
168 initingThread = Thread.currentThread();
170 * give a visual indication that sequence fetcher construction is occuring
172 if (guiWindow != null)
174 guiWindow.setProgressBar(MessageManager
175 .getString("status.init_sequence_database_fetchers"),
176 Thread.currentThread().hashCode());
178 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
179 dasRegistry.refreshSources();
181 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
182 if (guiWindow != null)
184 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
186 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
187 .getLocalSourceString()).hashCode();
189 _initingFetcher = false;
190 initingThread = null;
195 private IProgressIndicator progressIndicator;
197 public SequenceFetcher(IProgressIndicator guiIndic)
199 this.progressIndicator = guiIndic;
200 final SequenceFetcher us = this;
201 // launch initialiser thread
202 Thread sf = new Thread(new Runnable()
208 if (getSequenceFetcherSingleton(progressIndicator) != null)
210 us.initGui(progressIndicator);
214 javax.swing.SwingUtilities.invokeLater(new Runnable()
220 .showInternalMessageDialog(
223 .getString("warn.couldnt_create_sequence_fetcher_client"),
225 .getString("label.couldnt_create_sequence_fetcher"),
226 JOptionPane.ERROR_MESSAGE);
230 // raise warning dialog
237 private class DatabaseAuthority extends DefaultMutableTreeNode
242 private class DatabaseSource extends DefaultMutableTreeNode
248 * called by thread spawned by constructor
252 private void initGui(IProgressIndicator guiWindow)
254 this.guiWindow = guiWindow;
255 if (guiWindow instanceof AlignFrame)
257 alignFrame = (AlignFrame) guiWindow;
259 database = new JDatabaseTree(sfetch);
263 } catch (Exception ex)
265 ex.printStackTrace();
268 frame = new JInternalFrame();
269 frame.setContentPane(this);
270 if (new jalview.util.Platform().isAMac())
272 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
276 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
280 private String getFrameTitle()
282 return ((alignFrame == null) ? MessageManager
283 .getString("label.new_sequence_fetcher") : MessageManager
284 .getString("label.additional_sequence_fetcher"));
287 private void jbInit() throws Exception
289 this.setLayout(borderLayout2);
291 database.setFont(JvSwingUtils.getLabelFont());
292 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
293 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
294 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
295 jLabel1.setText(MessageManager
296 .getString("label.separate_multiple_accession_ids"));
298 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
300 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
301 replacePunctuation.setText(MessageManager
302 .getString("label.replace_commas_semicolons"));
303 ok.setText(MessageManager.getString("action.ok"));
304 ok.addActionListener(new ActionListener()
307 public void actionPerformed(ActionEvent e)
309 ok_actionPerformed();
312 clear.setText(MessageManager.getString("action.clear"));
313 clear.addActionListener(new ActionListener()
316 public void actionPerformed(ActionEvent e)
318 clear_actionPerformed();
322 example.setText(MessageManager.getString("label.example"));
323 example.addActionListener(new ActionListener()
326 public void actionPerformed(ActionEvent e)
328 example_actionPerformed();
331 close.setText(MessageManager.getString("action.close"));
332 close.addActionListener(new ActionListener()
335 public void actionPerformed(ActionEvent e)
337 close_actionPerformed(e);
340 textArea.setFont(JvSwingUtils.getLabelFont());
341 textArea.setLineWrap(true);
342 textArea.addKeyListener(new KeyAdapter()
345 public void keyPressed(KeyEvent e)
347 if (e.getKeyCode() == KeyEvent.VK_ENTER)
349 ok_actionPerformed();
353 jPanel3.setLayout(borderLayout1);
354 borderLayout1.setVgap(5);
356 jPanel1.add(example);
359 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
360 jPanel2.setLayout(borderLayout3);
361 databaseButt = database.getDatabaseSelectorButton();
362 databaseButt.setFont(JvSwingUtils.getLabelFont());
363 database.addActionListener(new ActionListener()
366 public void actionPerformed(ActionEvent e)
369 String currentSelection = database.getSelectedItem();
370 if (!currentSelection.equalsIgnoreCase("pdb"))
374 if (currentSelection.equalsIgnoreCase("pdb")
375 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
379 database.action = -1;
384 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
385 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
386 JPanel jPanel2a = new JPanel(new BorderLayout());
387 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
388 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
389 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
390 // jPanel2.setPreferredSize(new Dimension())
391 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
392 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
393 this.add(jPanel3, java.awt.BorderLayout.CENTER);
394 this.add(jPanel2, java.awt.BorderLayout.NORTH);
395 jScrollPane1.getViewport().add(textArea);
399 private void pdbSourceAction()
401 databaseButt.setText(database.getSelectedItem());
402 new PDBSearchPanel(this);
406 private void otherSourceAction()
410 databaseButt.setText(database.getSelectedItem()
411 + (database.getSelectedSources().size() > 1 ? " (and "
412 + database.getSelectedSources().size() + " others)"
414 String eq = database.getExampleQueries();
415 dbeg.setText(MessageManager.formatMessage(
416 "label.example_query_param", new String[] { eq }));
417 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
418 for (DbSourceProxy dbs : database.getSelectedSources())
420 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
426 replacePunctuation.setEnabled(enablePunct);
428 } catch (Exception ex)
431 replacePunctuation.setEnabled(true);
436 protected void example_actionPerformed()
438 DbSourceProxy db = null;
441 textArea.setText(database.getExampleQueries());
442 } catch (Exception ex)
448 protected void clear_actionPerformed()
450 textArea.setText("");
454 public void close_actionPerformed(ActionEvent e)
458 frame.setClosed(true);
459 } catch (Exception ex)
464 public void ok_actionPerformed()
466 databaseButt.setEnabled(false);
467 example.setEnabled(false);
468 textArea.setEnabled(false);
469 ok.setEnabled(false);
470 close.setEnabled(false);
472 Thread worker = new Thread(this);
476 private void resetDialog()
478 databaseButt.setEnabled(true);
479 example.setEnabled(true);
480 textArea.setEnabled(true);
482 close.setEnabled(true);
489 if (!database.hasSelection())
491 error += "Please select the source database\n";
493 // TODO: make this transformation more configurable
494 com.stevesoft.pat.Regex empty;
495 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
497 empty = new com.stevesoft.pat.Regex(
498 // replace commas and spaces with a semicolon
499 "(\\s|[,; ])+", ";");
503 // just turn spaces and semicolons into single semicolons
504 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
506 textArea.setText(empty.replaceAll(textArea.getText()));
507 // see if there's anthing to search with
508 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
511 error += "Please enter a (semi-colon separated list of) database id(s)";
513 if (error.length() > 0)
515 showErrorMessage(error);
519 // TODO: Refactor to GUI independent code and write tests.
520 // indicate if successive sources should be merged into one alignment.
521 boolean addToLast = false;
522 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
523 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
524 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
527 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
529 Iterator<String> en = Arrays.asList(new String[0]).iterator();
530 int nqueries = qries.length;
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.isA(DBRefSource.ALIGNMENTDB);
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 = DBRefUtils.processQueryToAccessionFor(proxy,
643 dbr.setAccessionId(accId);
644 boolean rfound = false;
645 for (int r = 0; r < rs.length; r++)
648 && (found = DBRefUtils.searchRefs(
649 rs[r].getDBRef(), dbr)) != null
663 } catch (OutOfMemoryError oome)
665 new OOMWarning("fetching " + multiacc + " from "
666 + database.getSelectedItem(), oome, this);
670 } catch (Exception e)
672 showErrorMessage("Error retrieving " + textArea.getText()
673 + " from " + database.getSelectedItem());
675 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
676 System.err.println("Retrieval failed for source ='"
677 + database.getSelectedItem() + "' and query\n'"
678 + textArea.getText() + "'\n");
680 } catch (OutOfMemoryError e)
682 // resets dialog box - so we don't use OOMwarning here.
683 showErrorMessage("Out of Memory when retrieving "
686 + database.getSelectedItem()
687 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
691 showErrorMessage("Serious Error retrieving " + textArea.getText()
692 + " from " + database.getSelectedItem());
695 // Stack results ready for opening in alignment windows
696 if (aresult != null && aresult.size() > 0)
698 AlignmentI ar = null;
702 // new window for each result
703 while (aresult.size() > 0)
705 presult.add(aresult.remove(0));
706 presultTitle.add(aresultq.remove(0) + " "
707 + getDefaultRetrievalTitle());
713 if (addToLast && presult.size() > 0)
715 ar = presult.remove(presult.size() - 1);
716 titl = presultTitle.remove(presultTitle.size() - 1);
718 // concatenate all results in one window
719 while (aresult.size() > 0)
723 ar = aresult.remove(0);
727 ar.append(aresult.remove(0));
733 presultTitle.add(titl);
736 guiWindow.setProgressBar(MessageManager
737 .getString("status.finshed_querying"), Thread.currentThread()
740 guiWindow.setProgressBar(
741 (presult.size() > 0) ? MessageManager
742 .getString("status.parsing_results") : MessageManager
743 .getString("status.processing"), Thread.currentThread()
746 while (presult.size() > 0)
748 parseResult(presult.remove(0), presultTitle.remove(0), null);
750 // only remove visual delay after we finished parsing.
751 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
752 if (nextfetch.size() > 0)
754 StringBuffer sb = new StringBuffer();
755 sb.append("Didn't retrieve the following "
756 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
757 + " queries") + ": \n");
758 int l = sb.length(), lr = 0;
759 for (String s : nextfetch)
761 if (l != sb.length())
765 if (lr - sb.length() > 40)
771 showErrorMessage(sb.toString());
776 AlignmentI parseResult(String result, String title)
778 String format = new IdentifyFile().identify(result, "Paste");
779 AlignmentI sequences = null;
780 if (FormatAdapter.isValidFormat(format))
785 sequences = new FormatAdapter().readFile(result.toString(),
787 } catch (Exception ex)
791 if (sequences != null)
793 return parseResult(sequences, title, format);
798 showErrorMessage("Error retrieving " + textArea.getText() + " from "
799 + database.getSelectedItem());
807 * @return a standard title for any results retrieved using the currently
808 * selected source and settings
810 public String getDefaultRetrievalTitle()
812 return "Retrieved from " + database.getSelectedItem();
815 AlignmentI parseResult(AlignmentI al, String title,
816 String currentFileFormat)
819 if (al != null && al.getHeight() > 0)
823 title = getDefaultRetrievalTitle();
825 if (alignFrame == null)
827 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
828 AlignFrame.DEFAULT_HEIGHT);
829 if (currentFileFormat != null)
831 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
833 // NON-FormatAdapter Sourced
837 SequenceFeature[] sfs = null;
838 List<SequenceI> alsqs;
839 synchronized (alsqs = al.getSequences())
841 for (SequenceI sq : alsqs)
843 if ((sfs = sq.getSequenceFeatures()) != null)
847 af.setShowSeqFeatures(true);
854 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
855 AlignFrame.DEFAULT_HEIGHT);
857 af.statusBar.setText(MessageManager
858 .getString("label.successfully_pasted_alignment_file"));
862 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
864 } catch (Exception ex)
870 alignFrame.viewport.addAlignment(al, title);
876 void showErrorMessage(final String error)
879 javax.swing.SwingUtilities.invokeLater(new Runnable()
884 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
885 MessageManager.getString("label.error_retrieving_data"),
886 JOptionPane.WARNING_MESSAGE);
891 public IProgressIndicator getProgressIndicator()
893 return progressIndicator;
896 public void setProgressIndicator(IProgressIndicator progressIndicator)
898 this.progressIndicator = progressIndicator;