2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
21 import java.util.List;
24 import java.awt.event.*;
27 import javax.swing.tree.DefaultMutableTreeNode;
28 import javax.swing.tree.MutableTreeNode;
29 import javax.swing.tree.TreeModel;
31 import jalview.datamodel.*;
33 import jalview.util.DBRefUtils;
34 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
35 import jalview.ws.seqfetcher.DbSourceProxy;
37 import java.awt.BorderLayout;
39 public class SequenceFetcher extends JPanel implements Runnable
41 // ASequenceFetcher sfetch;
44 IProgressIndicator guiWindow;
46 AlignFrame alignFrame;
50 final String noDbSelected = "-- Select Database --";
52 private static jalview.ws.SequenceFetcher sfetch = null;
54 private static long lastDasSourceRegistry = -3;
56 private static DasSourceRegistryI dasRegistry = null;
58 private static boolean _initingFetcher = false;
60 private static Thread initingThread = null;
63 * Blocking method that initialises and returns the shared instance of the
64 * SequenceFetcher client
67 * - where the initialisation delay message should be shown
68 * @return the singleton instance of the sequence fetcher client
70 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
71 final IProgressIndicator guiWindow)
73 if (_initingFetcher && initingThread != null && initingThread.isAlive())
75 if (guiWindow != null)
77 guiWindow.setProgressBar(
78 "Waiting for Sequence Database Fetchers to initialise",
79 Thread.currentThread().hashCode());
81 // initting happening on another thread - so wait around to see if it
83 while (_initingFetcher && initingThread != null
84 && initingThread.isAlive())
94 if (guiWindow != null)
96 guiWindow.setProgressBar(
97 "Waiting for Sequence Database Fetchers to initialise",
98 Thread.currentThread().hashCode());
102 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
103 || lastDasSourceRegistry != (jalview.bin.Cache
104 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
105 .getDasSourceRegistry().getLocalSourceString())
108 _initingFetcher = true;
109 initingThread = Thread.currentThread();
111 * give a visual indication that sequence fetcher construction is occuring
113 if (guiWindow != null)
115 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
116 Thread.currentThread().hashCode());
118 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
119 dasRegistry.refreshSources();
121 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
122 if (guiWindow != null)
124 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
125 Thread.currentThread().hashCode());
127 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
128 .getLocalSourceString()).hashCode();
130 _initingFetcher = false;
131 initingThread = null;
136 public SequenceFetcher(IProgressIndicator guiIndic)
138 final IProgressIndicator guiWindow = guiIndic;
139 final SequenceFetcher us = this;
140 // launch initialiser thread
141 Thread sf = new Thread(new Runnable()
146 if (getSequenceFetcherSingleton(guiWindow) != null)
148 us.initGui(guiWindow);
152 javax.swing.SwingUtilities.invokeLater(new Runnable()
157 .showInternalMessageDialog(
159 "Could not create the sequence fetcher client. Check error logs for details.",
160 "Couldn't create SequenceFetcher",
161 JOptionPane.ERROR_MESSAGE);
165 // raise warning dialog
172 private class DatabaseAuthority extends DefaultMutableTreeNode
177 private class DatabaseSource extends DefaultMutableTreeNode
183 * called by thread spawned by constructor
187 private void initGui(IProgressIndicator guiWindow)
189 this.guiWindow = guiWindow;
190 if (guiWindow instanceof AlignFrame)
192 alignFrame = (AlignFrame) guiWindow;
194 database = new JDatabaseTree(sfetch);
198 } catch (Exception ex)
200 ex.printStackTrace();
203 frame = new JInternalFrame();
204 frame.setContentPane(this);
205 if (new jalview.util.Platform().isAMac())
207 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
211 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
215 private String getFrameTitle()
217 return ((alignFrame == null) ? "New " : "Additional ")
218 + "Sequence Fetcher";
221 private void jbInit() throws Exception
223 this.setLayout(borderLayout2);
225 database.setFont(JvSwingUtils.getLabelFont());
226 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
227 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
228 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
229 jLabel1.setText("Separate multiple accession ids with semi colon \";\"");
231 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
233 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
234 replacePunctuation.setText("Replace commas with semi-colons");
236 ok.addActionListener(new ActionListener()
238 public void actionPerformed(ActionEvent e)
240 ok_actionPerformed();
243 clear.setText("Clear");
244 clear.addActionListener(new ActionListener()
246 public void actionPerformed(ActionEvent e)
248 clear_actionPerformed();
252 example.setText("Example");
253 example.addActionListener(new ActionListener()
255 public void actionPerformed(ActionEvent e)
257 example_actionPerformed();
260 close.setText("Close");
261 close.addActionListener(new ActionListener()
263 public void actionPerformed(ActionEvent e)
265 close_actionPerformed(e);
268 textArea.setFont(JvSwingUtils.getLabelFont());
269 textArea.setLineWrap(true);
270 textArea.addKeyListener(new KeyAdapter()
272 public void keyPressed(KeyEvent e)
274 if (e.getKeyCode() == KeyEvent.VK_ENTER)
275 ok_actionPerformed();
278 jPanel3.setLayout(borderLayout1);
279 borderLayout1.setVgap(5);
281 jPanel1.add(example);
284 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
285 jPanel2.setLayout(borderLayout3);
286 databaseButt = database.getDatabaseSelectorButton();
287 databaseButt.setFont(JvSwingUtils.getLabelFont());
288 database.addActionListener(new ActionListener()
291 public void actionPerformed(ActionEvent e)
293 DbSourceProxy db = null;
296 databaseButt.setText(database.getSelectedItem()
297 + (database.getSelectedSources().size() > 1 ? " (and "
298 + database.getSelectedSources().size()
300 String eq = database.getExampleQueries();
301 dbeg.setText("Example query: " + eq);
302 replacePunctuation.setEnabled(!(eq != null && eq.indexOf(",") > -1));
303 } catch (Exception ex)
306 replacePunctuation.setEnabled(true);
312 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
313 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
314 JPanel jPanel2a = new JPanel(new BorderLayout());
315 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
316 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
317 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
318 // jPanel2.setPreferredSize(new Dimension())
319 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
320 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
321 this.add(jPanel3, java.awt.BorderLayout.CENTER);
322 this.add(jPanel2, java.awt.BorderLayout.NORTH);
323 jScrollPane1.getViewport().add(textArea);
327 protected void example_actionPerformed()
329 DbSourceProxy db = null;
332 textArea.setText(database.getExampleQueries());
333 } catch (Exception ex)
339 protected void clear_actionPerformed()
341 textArea.setText("");
345 JLabel dbeg = new JLabel();
347 JDatabaseTree database;
349 JButton databaseButt;
351 JLabel jLabel1 = new JLabel();
353 JCheckBox replacePunctuation = new JCheckBox();
355 JButton ok = new JButton();
357 JButton clear = new JButton();
359 JButton example = new JButton();
361 JButton close = new JButton();
363 JPanel jPanel1 = new JPanel();
365 JTextArea textArea = new JTextArea();
367 JScrollPane jScrollPane1 = new JScrollPane();
369 JPanel jPanel2 = new JPanel();
371 JPanel jPanel3 = new JPanel();
373 JPanel jPanel4 = new JPanel();
375 BorderLayout borderLayout1 = new BorderLayout();
377 BorderLayout borderLayout2 = new BorderLayout();
379 BorderLayout borderLayout3 = new BorderLayout();
381 public void close_actionPerformed(ActionEvent e)
385 frame.setClosed(true);
386 } catch (Exception ex)
391 public void ok_actionPerformed()
393 database.setEnabled(false);
394 textArea.setEnabled(false);
395 ok.setEnabled(false);
396 close.setEnabled(false);
398 Thread worker = new Thread(this);
402 private void resetDialog()
404 database.setEnabled(true);
405 textArea.setEnabled(true);
407 close.setEnabled(true);
413 if (!database.hasSelection())
415 error += "Please select the source database\n";
417 // TODO: make this transformation more configurable
418 com.stevesoft.pat.Regex empty;
419 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
421 empty = new com.stevesoft.pat.Regex(
422 // replace commas and spaces with a semicolon
423 "(\\s|[,; ])+", ";");
427 // just turn spaces and semicolons into single semicolons
428 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
430 textArea.setText(empty.replaceAll(textArea.getText()));
431 // see if there's anthing to search with
432 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
435 error += "Please enter a (semi-colon separated list of) database id(s)";
437 if (error.length() > 0)
439 showErrorMessage(error);
443 // indicate if successive sources should be merged into one alignment.
444 boolean addToLast=false;
445 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
446 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
447 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
450 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
452 Iterator<String> en = Arrays.asList(new String[0]).iterator();
453 int nqueries = qries.length;
454 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
456 if (!en.hasNext() && nextfetch.size() > 0)
458 en = nextfetch.iterator();
459 nqueries = nextfetch.size();
460 // save the remaining queries in the original array
461 qries = nextfetch.toArray(new String[nqueries]);
462 nextfetch = new ArrayList<String>();
465 DbSourceProxy proxy = proxies.next();
466 boolean isAliSource = false;
470 guiWindow.setProgressBar("Fetching " + nqueries
471 + " sequence queries from " + proxy.getDbName(), Thread
472 .currentThread().hashCode());
473 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
474 if (proxy.getAccessionSeparator() == null)
478 String item = en.next();
485 // give the server a chance to breathe
487 } catch (Exception e)
494 AlignmentI indres = null;
497 indres = proxy.getSequenceRecords(item);
498 } catch (OutOfMemoryError oome)
500 new OOMWarning("fetching " + item + " from "
501 + proxy.getDbName(), oome, this);
512 } catch (Exception e)
514 jalview.bin.Cache.log.info("Error retrieving " + item
515 + " from " + proxy.getDbName(), e);
522 StringBuffer multiacc = new StringBuffer();
523 ArrayList<String> tosend = new ArrayList<String>();
526 String nel = en.next();
528 multiacc.append(nel);
531 multiacc.append(proxy.getAccessionSeparator());
538 List<String> nores = new ArrayList<String>();
539 rslt = proxy.getSequenceRecords(multiacc.toString());
540 if (rslt == null || rslt.getHeight() == 0)
542 // no results - pass on all queries to next source
543 nextfetch.addAll(tosend);
547 aresultq.add(multiacc.toString());
550 rs = rslt.getSequencesArray();
551 // search for each query in the dbrefs associated with each
554 // ones we do not find will be used to query next source (if any)
555 for (String q : tosend)
557 DBRefEntry dbr = new DBRefEntry(), found[] = null;
558 dbr.setSource(proxy.getDbSource());
559 boolean rfound = false;
560 for (int r = 0; r < rs.length; r++)
563 && (found = DBRefUtils.searchRefs(
564 rs[r].getDBRef(), dbr)) != null
578 } catch (OutOfMemoryError oome)
580 new OOMWarning("fetching " + multiacc + " from "
581 + database.getSelectedItem(), oome, this);
585 } catch (Exception e)
587 showErrorMessage("Error retrieving " + textArea.getText()
588 + " from " + database.getSelectedItem());
590 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
591 System.err.println("Retrieval failed for source ='"
592 + database.getSelectedItem() + "' and query\n'"
593 + textArea.getText() + "'\n");
595 } catch (OutOfMemoryError e)
597 // resets dialog box - so we don't use OOMwarning here.
598 showErrorMessage("Out of Memory when retrieving "
601 + database.getSelectedItem()
602 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
606 showErrorMessage("Serious Error retrieving " + textArea.getText()
607 + " from " + database.getSelectedItem());
610 // Stack results ready for opening in alignment windows
611 if (aresult != null && aresult.size() > 0)
613 AlignmentI ar = null;
617 // new window for each result
618 while (aresult.size() > 0)
620 presult.add(aresult.remove(0));
621 presultTitle.add(aresultq.remove(0) + " "
622 + getDefaultRetrievalTitle());
628 if (addToLast && presult.size()>0)
630 ar=presult.remove(presult.size()-1);
631 titl=presultTitle.remove(presultTitle.size()-1);
633 // concatenate all results in one window
634 while (aresult.size() > 0)
638 ar = aresult.remove(0);
642 ar.append(aresult.remove(0));
648 presultTitle.add(titl);
651 guiWindow.setProgressBar("Finished querying", Thread.currentThread().hashCode());
653 guiWindow.setProgressBar((presult.size()>0) ? "Parsing results.":"Processing ..", Thread.currentThread().hashCode());
655 while (presult.size() > 0)
657 parseResult(presult.remove(0), presultTitle.remove(0), null);
659 // only remove visual delay after we finished parsing.
660 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
661 if (nextfetch.size() > 0)
663 StringBuffer sb = new StringBuffer();
664 sb.append("Didn't retrieve the following "
665 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
666 + " queries") + ": \n");
667 int l = sb.length(),lr=0;
668 for (String s : nextfetch)
670 if (l != sb.length())
674 if (lr-sb.length()>40)
680 showErrorMessage(sb.toString());
685 AlignmentI parseResult(String result, String title)
687 String format = new IdentifyFile().Identify(result, "Paste");
688 Alignment sequences = null;
689 if (FormatAdapter.isValidFormat(format))
694 sequences = new FormatAdapter().readFile(result.toString(),
696 } catch (Exception ex)
700 if (sequences != null)
702 return parseResult(sequences, title, format);
707 showErrorMessage("Error retrieving " + textArea.getText() + " from "
708 + database.getSelectedItem());
716 * @return a standard title for any results retrieved using the currently
717 * selected source and settings
719 public String getDefaultRetrievalTitle()
721 return "Retrieved from " + database.getSelectedItem();
724 AlignmentI parseResult(AlignmentI al, String title,
725 String currentFileFormat)
728 if (al != null && al.getHeight() > 0)
730 if (alignFrame == null)
732 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
733 AlignFrame.DEFAULT_HEIGHT);
734 if (currentFileFormat != null)
736 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
738 // NON-FormatAdapter Sourced
744 title = getDefaultRetrievalTitle();
746 SequenceFeature[] sfs = null;
747 for (Enumeration sq = al.getSequences().elements(); sq
750 if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
751 .getSequenceFeatures()) != null)
755 af.setShowSeqFeatures(true);
761 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
762 AlignFrame.DEFAULT_HEIGHT);
764 af.statusBar.setText("Successfully pasted alignment file");
768 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
770 } catch (Exception ex)
776 for (int i = 0; i < al.getHeight(); i++)
778 alignFrame.viewport.getAlignment().addSequence(
779 al.getSequenceAt(i)); // this
786 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
788 alignFrame.viewport.getAlignment().getWidth();
789 alignFrame.viewport.firePropertyChange("alignment", null,
790 alignFrame.viewport.getAlignment().getSequences());
796 void showErrorMessage(final String error)
799 javax.swing.SwingUtilities.invokeLater(new Runnable()
803 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
804 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);