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;
36 import jalview.ws.seqfetcher.DbSourceProxyImpl;
38 import java.awt.BorderLayout;
40 public class SequenceFetcher extends JPanel implements Runnable
42 // ASequenceFetcher sfetch;
45 IProgressIndicator guiWindow;
47 AlignFrame alignFrame;
51 final String noDbSelected = "-- Select Database --";
53 private static jalview.ws.SequenceFetcher sfetch = null;
55 private static long lastDasSourceRegistry = -3;
57 private static DasSourceRegistryI dasRegistry = null;
59 private static boolean _initingFetcher = false;
61 private static Thread initingThread = null;
64 * Blocking method that initialises and returns the shared instance of the
65 * SequenceFetcher client
68 * - where the initialisation delay message should be shown
69 * @return the singleton instance of the sequence fetcher client
71 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
72 final IProgressIndicator guiWindow)
74 if (_initingFetcher && initingThread != null && initingThread.isAlive())
76 if (guiWindow != null)
78 guiWindow.setProgressBar(
79 "Waiting for Sequence Database Fetchers to initialise",
80 Thread.currentThread().hashCode());
82 // initting happening on another thread - so wait around to see if it
84 while (_initingFetcher && initingThread != null
85 && initingThread.isAlive())
95 if (guiWindow != null)
97 guiWindow.setProgressBar(
98 "Waiting for Sequence Database Fetchers to initialise",
99 Thread.currentThread().hashCode());
103 || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
104 || lastDasSourceRegistry != (jalview.bin.Cache
105 .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
106 .getDasSourceRegistry().getLocalSourceString())
109 _initingFetcher = true;
110 initingThread = Thread.currentThread();
112 * give a visual indication that sequence fetcher construction is occuring
114 if (guiWindow != null)
116 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
117 Thread.currentThread().hashCode());
119 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
120 dasRegistry.refreshSources();
122 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
123 if (guiWindow != null)
125 guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
126 Thread.currentThread().hashCode());
128 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
129 .getLocalSourceString()).hashCode();
131 _initingFetcher = false;
132 initingThread = null;
137 public SequenceFetcher(IProgressIndicator guiIndic)
139 final IProgressIndicator guiWindow = guiIndic;
140 final SequenceFetcher us = this;
141 // launch initialiser thread
142 Thread sf = new Thread(new Runnable()
147 if (getSequenceFetcherSingleton(guiWindow) != null)
149 us.initGui(guiWindow);
153 javax.swing.SwingUtilities.invokeLater(new Runnable()
158 .showInternalMessageDialog(
160 "Could not create the sequence fetcher client. Check error logs for details.",
161 "Couldn't create SequenceFetcher",
162 JOptionPane.ERROR_MESSAGE);
166 // raise warning dialog
173 private class DatabaseAuthority extends DefaultMutableTreeNode
178 private class DatabaseSource extends DefaultMutableTreeNode
184 * called by thread spawned by constructor
188 private void initGui(IProgressIndicator guiWindow)
190 this.guiWindow = guiWindow;
191 if (guiWindow instanceof AlignFrame)
193 alignFrame = (AlignFrame) guiWindow;
195 database = new JDatabaseTree(sfetch);
199 } catch (Exception ex)
201 ex.printStackTrace();
204 frame = new JInternalFrame();
205 frame.setContentPane(this);
206 if (new jalview.util.Platform().isAMac())
208 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
212 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
216 private String getFrameTitle()
218 return ((alignFrame == null) ? "New " : "Additional ")
219 + "Sequence Fetcher";
222 private void jbInit() throws Exception
224 this.setLayout(borderLayout2);
226 database.setFont(JvSwingUtils.getLabelFont());
227 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
228 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
229 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
230 jLabel1.setText("Separate multiple accession ids with semi colon \";\"");
232 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
234 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
235 replacePunctuation.setText("Replace commas with semi-colons");
237 ok.addActionListener(new ActionListener()
239 public void actionPerformed(ActionEvent e)
241 ok_actionPerformed();
244 clear.setText("Clear");
245 clear.addActionListener(new ActionListener()
247 public void actionPerformed(ActionEvent e)
249 clear_actionPerformed();
253 example.setText("Example");
254 example.addActionListener(new ActionListener()
256 public void actionPerformed(ActionEvent e)
258 example_actionPerformed();
261 close.setText("Close");
262 close.addActionListener(new ActionListener()
264 public void actionPerformed(ActionEvent e)
266 close_actionPerformed(e);
269 textArea.setFont(JvSwingUtils.getLabelFont());
270 textArea.setLineWrap(true);
271 textArea.addKeyListener(new KeyAdapter()
273 public void keyPressed(KeyEvent e)
275 if (e.getKeyCode() == KeyEvent.VK_ENTER)
276 ok_actionPerformed();
279 jPanel3.setLayout(borderLayout1);
280 borderLayout1.setVgap(5);
282 jPanel1.add(example);
285 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
286 jPanel2.setLayout(borderLayout3);
287 databaseButt = database.getDatabaseSelectorButton();
288 databaseButt.setFont(JvSwingUtils.getLabelFont());
289 database.addActionListener(new ActionListener()
292 public void actionPerformed(ActionEvent e)
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 boolean enablePunct=!(eq != null && eq.indexOf(",") > -1);
303 for (DbSourceProxy dbs:database.getSelectedSources()) {
304 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
310 replacePunctuation.setEnabled(enablePunct);
312 } catch (Exception ex)
315 replacePunctuation.setEnabled(true);
321 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
322 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
323 JPanel jPanel2a = new JPanel(new BorderLayout());
324 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
325 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
326 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
327 // jPanel2.setPreferredSize(new Dimension())
328 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
329 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
330 this.add(jPanel3, java.awt.BorderLayout.CENTER);
331 this.add(jPanel2, java.awt.BorderLayout.NORTH);
332 jScrollPane1.getViewport().add(textArea);
336 protected void example_actionPerformed()
338 DbSourceProxy db = null;
341 textArea.setText(database.getExampleQueries());
342 } catch (Exception ex)
348 protected void clear_actionPerformed()
350 textArea.setText("");
354 JLabel dbeg = new JLabel();
356 JDatabaseTree database;
358 JButton databaseButt;
360 JLabel jLabel1 = new JLabel();
362 JCheckBox replacePunctuation = new JCheckBox();
364 JButton ok = new JButton();
366 JButton clear = new JButton();
368 JButton example = new JButton();
370 JButton close = new JButton();
372 JPanel jPanel1 = new JPanel();
374 JTextArea textArea = new JTextArea();
376 JScrollPane jScrollPane1 = new JScrollPane();
378 JPanel jPanel2 = new JPanel();
380 JPanel jPanel3 = new JPanel();
382 JPanel jPanel4 = new JPanel();
384 BorderLayout borderLayout1 = new BorderLayout();
386 BorderLayout borderLayout2 = new BorderLayout();
388 BorderLayout borderLayout3 = new BorderLayout();
390 public void close_actionPerformed(ActionEvent e)
394 frame.setClosed(true);
395 } catch (Exception ex)
400 public void ok_actionPerformed()
402 database.setEnabled(false);
403 textArea.setEnabled(false);
404 ok.setEnabled(false);
405 close.setEnabled(false);
407 Thread worker = new Thread(this);
411 private void resetDialog()
413 database.setEnabled(true);
414 textArea.setEnabled(true);
416 close.setEnabled(true);
422 if (!database.hasSelection())
424 error += "Please select the source database\n";
426 // TODO: make this transformation more configurable
427 com.stevesoft.pat.Regex empty;
428 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
430 empty = new com.stevesoft.pat.Regex(
431 // replace commas and spaces with a semicolon
432 "(\\s|[,; ])+", ";");
436 // just turn spaces and semicolons into single semicolons
437 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
439 textArea.setText(empty.replaceAll(textArea.getText()));
440 // see if there's anthing to search with
441 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
444 error += "Please enter a (semi-colon separated list of) database id(s)";
446 if (error.length() > 0)
448 showErrorMessage(error);
452 // indicate if successive sources should be merged into one alignment.
453 boolean addToLast=false;
454 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
455 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
456 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
459 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
461 Iterator<String> en = Arrays.asList(new String[0]).iterator();
462 int nqueries = qries.length;
463 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
465 if (!en.hasNext() && nextfetch.size() > 0)
467 en = nextfetch.iterator();
468 nqueries = nextfetch.size();
469 // save the remaining queries in the original array
470 qries = nextfetch.toArray(new String[nqueries]);
471 nextfetch = new ArrayList<String>();
474 DbSourceProxy proxy = proxies.next();
475 boolean isAliSource = false;
479 guiWindow.setProgressBar("Fetching " + nqueries
480 + " sequence queries from " + proxy.getDbName(), Thread
481 .currentThread().hashCode());
482 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
483 if (proxy.getAccessionSeparator() == null)
487 String item = en.next();
494 // give the server a chance to breathe
496 } catch (Exception e)
503 AlignmentI indres = null;
506 indres = proxy.getSequenceRecords(item);
507 } catch (OutOfMemoryError oome)
509 new OOMWarning("fetching " + item + " from "
510 + proxy.getDbName(), oome, this);
521 } catch (Exception e)
523 jalview.bin.Cache.log.info("Error retrieving " + item
524 + " from " + proxy.getDbName(), e);
531 StringBuffer multiacc = new StringBuffer();
532 ArrayList<String> tosend = new ArrayList<String>();
535 String nel = en.next();
537 multiacc.append(nel);
540 multiacc.append(proxy.getAccessionSeparator());
547 List<String> nores = new ArrayList<String>();
548 rslt = proxy.getSequenceRecords(multiacc.toString());
549 if (rslt == null || rslt.getHeight() == 0)
551 // no results - pass on all queries to next source
552 nextfetch.addAll(tosend);
556 aresultq.add(multiacc.toString());
559 rs = rslt.getSequencesArray();
560 // search for each query in the dbrefs associated with each
563 // ones we do not find will be used to query next source (if any)
564 for (String q : tosend)
566 DBRefEntry dbr = new DBRefEntry(), found[] = null;
567 dbr.setSource(proxy.getDbSource());
568 boolean rfound = false;
569 for (int r = 0; r < rs.length; r++)
572 && (found = DBRefUtils.searchRefs(
573 rs[r].getDBRef(), dbr)) != null
587 } catch (OutOfMemoryError oome)
589 new OOMWarning("fetching " + multiacc + " from "
590 + database.getSelectedItem(), oome, this);
594 } catch (Exception e)
596 showErrorMessage("Error retrieving " + textArea.getText()
597 + " from " + database.getSelectedItem());
599 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
600 System.err.println("Retrieval failed for source ='"
601 + database.getSelectedItem() + "' and query\n'"
602 + textArea.getText() + "'\n");
604 } catch (OutOfMemoryError e)
606 // resets dialog box - so we don't use OOMwarning here.
607 showErrorMessage("Out of Memory when retrieving "
610 + database.getSelectedItem()
611 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
615 showErrorMessage("Serious Error retrieving " + textArea.getText()
616 + " from " + database.getSelectedItem());
619 // Stack results ready for opening in alignment windows
620 if (aresult != null && aresult.size() > 0)
622 AlignmentI ar = null;
626 // new window for each result
627 while (aresult.size() > 0)
629 presult.add(aresult.remove(0));
630 presultTitle.add(aresultq.remove(0) + " "
631 + getDefaultRetrievalTitle());
637 if (addToLast && presult.size()>0)
639 ar=presult.remove(presult.size()-1);
640 titl=presultTitle.remove(presultTitle.size()-1);
642 // concatenate all results in one window
643 while (aresult.size() > 0)
647 ar = aresult.remove(0);
651 ar.append(aresult.remove(0));
657 presultTitle.add(titl);
660 guiWindow.setProgressBar("Finished querying", Thread.currentThread().hashCode());
662 guiWindow.setProgressBar((presult.size()>0) ? "Parsing results.":"Processing ..", Thread.currentThread().hashCode());
664 while (presult.size() > 0)
666 parseResult(presult.remove(0), presultTitle.remove(0), null);
668 // only remove visual delay after we finished parsing.
669 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
670 if (nextfetch.size() > 0)
672 StringBuffer sb = new StringBuffer();
673 sb.append("Didn't retrieve the following "
674 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
675 + " queries") + ": \n");
676 int l = sb.length(),lr=0;
677 for (String s : nextfetch)
679 if (l != sb.length())
683 if (lr-sb.length()>40)
689 showErrorMessage(sb.toString());
694 AlignmentI parseResult(String result, String title)
696 String format = new IdentifyFile().Identify(result, "Paste");
697 Alignment sequences = null;
698 if (FormatAdapter.isValidFormat(format))
703 sequences = new FormatAdapter().readFile(result.toString(),
705 } catch (Exception ex)
709 if (sequences != null)
711 return parseResult(sequences, title, format);
716 showErrorMessage("Error retrieving " + textArea.getText() + " from "
717 + database.getSelectedItem());
725 * @return a standard title for any results retrieved using the currently
726 * selected source and settings
728 public String getDefaultRetrievalTitle()
730 return "Retrieved from " + database.getSelectedItem();
733 AlignmentI parseResult(AlignmentI al, String title,
734 String currentFileFormat)
737 if (al != null && al.getHeight() > 0)
739 if (alignFrame == null)
741 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
742 AlignFrame.DEFAULT_HEIGHT);
743 if (currentFileFormat != null)
745 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
747 // NON-FormatAdapter Sourced
753 title = getDefaultRetrievalTitle();
755 SequenceFeature[] sfs = null;
756 for (Enumeration sq = al.getSequences().elements(); sq
759 if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
760 .getSequenceFeatures()) != null)
764 af.setShowSeqFeatures(true);
770 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
771 AlignFrame.DEFAULT_HEIGHT);
773 af.statusBar.setText("Successfully pasted alignment file");
777 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
779 } catch (Exception ex)
785 for (int i = 0; i < al.getHeight(); i++)
787 alignFrame.viewport.getAlignment().addSequence(
788 al.getSequenceAt(i)); // this
795 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
797 alignFrame.viewport.getAlignment().getWidth();
798 alignFrame.viewport.firePropertyChange("alignment", null,
799 alignFrame.viewport.getAlignment().getSequences());
805 void showErrorMessage(final String error)
808 javax.swing.SwingUtilities.invokeLater(new Runnable()
812 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
813 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);