2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.FormatAdapter;
30 import jalview.io.IdentifyFile;
31 import jalview.util.DBRefUtils;
32 import jalview.util.MessageManager;
33 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
34 import jalview.ws.seqfetcher.DbSourceProxy;
36 import java.awt.BorderLayout;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.KeyAdapter;
41 import java.awt.event.KeyEvent;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Iterator;
45 import java.util.List;
47 import javax.swing.JButton;
48 import javax.swing.JCheckBox;
49 import javax.swing.JInternalFrame;
50 import javax.swing.JLabel;
51 import javax.swing.JOptionPane;
52 import javax.swing.JPanel;
53 import javax.swing.JScrollPane;
54 import javax.swing.JTextArea;
55 import javax.swing.SwingConstants;
56 import javax.swing.tree.DefaultMutableTreeNode;
58 import com.stevesoft.pat.Regex;
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;
120 * Blocking method that initialises and returns the shared instance of the
121 * SequenceFetcher client
124 * - where the initialisation delay message should be shown
125 * @return the singleton instance of the sequence fetcher client
127 public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
128 final IProgressIndicator guiWindow)
130 if (_initingFetcher && initingThread != null && initingThread.isAlive())
132 if (guiWindow != null)
134 guiWindow.setProgressBar(
135 MessageManager.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)
153 guiWindow.setProgressBar(
154 MessageManager.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.getString("status.init_sequence_database_fetchers"),
173 Thread.currentThread().hashCode());
175 dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
176 dasRegistry.refreshSources();
178 jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
179 if (guiWindow != null)
181 guiWindow.setProgressBar(MessageManager.getString("status.init_sequence_database_fetchers"),
182 Thread.currentThread().hashCode());
184 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
185 .getLocalSourceString()).hashCode();
187 _initingFetcher = false;
188 initingThread = null;
193 public SequenceFetcher(IProgressIndicator guiIndic)
195 final IProgressIndicator guiWindow = guiIndic;
196 final SequenceFetcher us = this;
197 // launch initialiser thread
198 Thread sf = new Thread(new Runnable()
204 if (getSequenceFetcherSingleton(guiWindow) != null)
206 us.initGui(guiWindow);
210 javax.swing.SwingUtilities.invokeLater(new Runnable()
216 .showInternalMessageDialog(
218 MessageManager.getString("warn.couldnt_create_sequence_fetcher_client"),
219 MessageManager.getString("label.couldnt_create_sequence_fetcher"),
220 JOptionPane.ERROR_MESSAGE);
224 // raise warning dialog
231 private class DatabaseAuthority extends DefaultMutableTreeNode
236 private class DatabaseSource extends DefaultMutableTreeNode
242 * called by thread spawned by constructor
246 private void initGui(IProgressIndicator guiWindow)
248 this.guiWindow = guiWindow;
249 if (guiWindow instanceof AlignFrame)
251 alignFrame = (AlignFrame) guiWindow;
253 database = new JDatabaseTree(sfetch);
257 } catch (Exception ex)
259 ex.printStackTrace();
262 frame = new JInternalFrame();
263 frame.setContentPane(this);
264 if (new jalview.util.Platform().isAMac())
266 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
270 Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
274 private String getFrameTitle()
276 return ((alignFrame == null) ? MessageManager.getString("label.new_sequence_fetcher") : MessageManager.getString("label.additional_sequence_fetcher"));
279 private void jbInit() throws Exception
281 this.setLayout(borderLayout2);
283 database.setFont(JvSwingUtils.getLabelFont());
284 dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
285 jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
286 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
287 jLabel1.setText(MessageManager
288 .getString("label.separate_multiple_accession_ids"));
290 replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
292 .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
293 replacePunctuation.setText(MessageManager
294 .getString("label.replace_commas_semicolons"));
295 ok.setText(MessageManager.getString("action.ok"));
296 ok.addActionListener(new ActionListener()
299 public void actionPerformed(ActionEvent e)
301 ok_actionPerformed();
304 clear.setText(MessageManager.getString("action.clear"));
305 clear.addActionListener(new ActionListener()
308 public void actionPerformed(ActionEvent e)
310 clear_actionPerformed();
314 example.setText(MessageManager.getString("label.example"));
315 example.addActionListener(new ActionListener()
318 public void actionPerformed(ActionEvent e)
320 example_actionPerformed();
323 close.setText(MessageManager.getString("action.close"));
324 close.addActionListener(new ActionListener()
327 public void actionPerformed(ActionEvent e)
329 close_actionPerformed(e);
332 textArea.setFont(JvSwingUtils.getLabelFont());
333 textArea.setLineWrap(true);
334 textArea.addKeyListener(new KeyAdapter()
337 public void keyPressed(KeyEvent e)
339 if (e.getKeyCode() == KeyEvent.VK_ENTER)
341 ok_actionPerformed();
345 jPanel3.setLayout(borderLayout1);
346 borderLayout1.setVgap(5);
348 jPanel1.add(example);
351 jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
352 jPanel2.setLayout(borderLayout3);
353 databaseButt = database.getDatabaseSelectorButton();
354 databaseButt.setFont(JvSwingUtils.getLabelFont());
355 database.addActionListener(new ActionListener()
358 public void actionPerformed(ActionEvent e)
361 String currentSelection = database.getSelectedItem();
363 if (!currentSelection.equalsIgnoreCase("pdb"))
367 if (currentSelection.equalsIgnoreCase("pdb") && ((x % 2) == 0))
376 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
377 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
378 JPanel jPanel2a = new JPanel(new BorderLayout());
379 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
380 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
381 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
382 // jPanel2.setPreferredSize(new Dimension())
383 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
384 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
385 this.add(jPanel3, java.awt.BorderLayout.CENTER);
386 this.add(jPanel2, java.awt.BorderLayout.NORTH);
387 jScrollPane1.getViewport().add(textArea);
393 this.setVisible(false);
395 private void otherSourceAction()
399 databaseButt.setText(database.getSelectedItem()
400 + (database.getSelectedSources().size() > 1 ? " (and "
401 + database.getSelectedSources().size() + " others)"
403 String eq = database.getExampleQueries();
404 dbeg.setText(MessageManager.formatMessage(
405 "label.example_query_param", new String[]
407 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
408 for (DbSourceProxy dbs : database.getSelectedSources())
410 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
416 replacePunctuation.setEnabled(enablePunct);
418 } catch (Exception ex)
421 replacePunctuation.setEnabled(true);
426 protected void example_actionPerformed()
428 DbSourceProxy db = null;
431 textArea.setText(database.getExampleQueries());
432 } catch (Exception ex)
438 protected void clear_actionPerformed()
440 textArea.setText("");
446 public void close_actionPerformed(ActionEvent e)
450 frame.setClosed(true);
451 } catch (Exception ex)
456 public void ok_actionPerformed()
458 databaseButt.setEnabled(false);
459 example.setEnabled(false);
460 textArea.setEnabled(false);
461 ok.setEnabled(false);
462 close.setEnabled(false);
464 Thread worker = new Thread(this);
468 private void resetDialog()
470 databaseButt.setEnabled(true);
471 example.setEnabled(true);
472 textArea.setEnabled(true);
474 close.setEnabled(true);
481 if (!database.hasSelection())
483 error += "Please select the source database\n";
485 // TODO: make this transformation more configurable
486 com.stevesoft.pat.Regex empty;
487 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
489 empty = new com.stevesoft.pat.Regex(
490 // replace commas and spaces with a semicolon
491 "(\\s|[,; ])+", ";");
495 // just turn spaces and semicolons into single semicolons
496 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
498 textArea.setText(empty.replaceAll(textArea.getText()));
499 // see if there's anthing to search with
500 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
503 error += "Please enter a (semi-colon separated list of) database id(s)";
505 if (error.length() > 0)
507 showErrorMessage(error);
511 // indicate if successive sources should be merged into one alignment.
512 boolean addToLast = false;
513 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
514 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
515 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
518 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
520 Iterator<String> en = Arrays.asList(new String[0]).iterator();
521 int nqueries = qries.length;
522 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
524 if (!en.hasNext() && nextfetch.size() > 0)
526 en = nextfetch.iterator();
527 nqueries = nextfetch.size();
528 // save the remaining queries in the original array
529 qries = nextfetch.toArray(new String[nqueries]);
530 nextfetch = new ArrayList<String>();
533 DbSourceProxy proxy = proxies.next();
534 boolean isAliSource = false;
538 guiWindow.setProgressBar(MessageManager.formatMessage("status.fetching_sequence_queries_from", new String[]{Integer.valueOf(nqueries).toString(),proxy.getDbName()}), Thread
539 .currentThread().hashCode());
540 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
541 if (proxy.getAccessionSeparator() == null)
545 String item = en.next();
552 // give the server a chance to breathe
554 } catch (Exception e)
561 AlignmentI indres = null;
564 indres = proxy.getSequenceRecords(item);
565 } catch (OutOfMemoryError oome)
567 new OOMWarning("fetching " + item + " from "
568 + proxy.getDbName(), oome, this);
579 } catch (Exception e)
581 jalview.bin.Cache.log.info("Error retrieving " + item
582 + " from " + proxy.getDbName(), e);
589 StringBuffer multiacc = new StringBuffer();
590 ArrayList<String> tosend = new ArrayList<String>();
593 String nel = en.next();
595 multiacc.append(nel);
598 multiacc.append(proxy.getAccessionSeparator());
605 List<String> nores = new ArrayList<String>();
606 rslt = proxy.getSequenceRecords(multiacc.toString());
607 if (rslt == null || rslt.getHeight() == 0)
609 // no results - pass on all queries to next source
610 nextfetch.addAll(tosend);
614 aresultq.add(multiacc.toString());
617 rs = rslt.getSequencesArray();
618 // search for each query in the dbrefs associated with each
621 // ones we do not find will be used to query next source (if any)
622 for (String q : tosend)
624 DBRefEntry dbr = new DBRefEntry(), found[] = null;
625 dbr.setSource(proxy.getDbSource());
626 dbr.setVersion(null);
627 if (proxy.getAccessionValidator() != null)
629 Regex vgr = proxy.getAccessionValidator();
631 if (vgr.numSubs() > 0)
633 dbr.setAccessionId(vgr.stringMatched(1));
637 dbr.setAccessionId(vgr.stringMatched());
642 dbr.setAccessionId(q);
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.getString("status.finshed_querying"), Thread.currentThread()
739 guiWindow.setProgressBar((presult.size() > 0) ? MessageManager.getString("status.parsing_results")
740 : MessageManager.getString("status.processing"), Thread.currentThread().hashCode());
742 while (presult.size() > 0)
744 parseResult(presult.remove(0), presultTitle.remove(0), null);
746 // only remove visual delay after we finished parsing.
747 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
748 if (nextfetch.size() > 0)
750 StringBuffer sb = new StringBuffer();
751 sb.append("Didn't retrieve the following "
752 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
753 + " queries") + ": \n");
754 int l = sb.length(), lr = 0;
755 for (String s : nextfetch)
757 if (l != sb.length())
761 if (lr - sb.length() > 40)
767 showErrorMessage(sb.toString());
772 AlignmentI parseResult(String result, String title)
774 String format = new IdentifyFile().Identify(result, "Paste");
775 Alignment sequences = null;
776 if (FormatAdapter.isValidFormat(format))
781 sequences = new FormatAdapter().readFile(result.toString(),
783 } catch (Exception ex)
787 if (sequences != null)
789 return parseResult(sequences, title, format);
794 showErrorMessage("Error retrieving " + textArea.getText() + " from "
795 + database.getSelectedItem());
803 * @return a standard title for any results retrieved using the currently
804 * selected source and settings
806 public String getDefaultRetrievalTitle()
808 return "Retrieved from " + database.getSelectedItem();
811 AlignmentI parseResult(AlignmentI al, String title,
812 String currentFileFormat)
815 if (al != null && al.getHeight() > 0)
817 if (alignFrame == null)
819 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
820 AlignFrame.DEFAULT_HEIGHT);
821 if (currentFileFormat != null)
823 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
825 // NON-FormatAdapter Sourced
831 title = getDefaultRetrievalTitle();
833 SequenceFeature[] sfs = null;
834 List<SequenceI> alsqs;
835 synchronized (alsqs = al.getSequences())
837 for (SequenceI sq : alsqs)
839 if ((sfs = sq.getSequenceFeatures()) != null)
843 af.setShowSeqFeatures(true);
850 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
851 AlignFrame.DEFAULT_HEIGHT);
853 af.statusBar.setText(MessageManager
854 .getString("label.successfully_pasted_alignment_file"));
858 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
860 } catch (Exception ex)
866 for (int i = 0; i < al.getHeight(); i++)
868 alignFrame.viewport.getAlignment().addSequence(
869 al.getSequenceAt(i)); // this
876 alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
878 alignFrame.viewport.getAlignment().getWidth();
879 alignFrame.viewport.firePropertyChange("alignment", null,
880 alignFrame.viewport.getAlignment().getSequences());
886 void showErrorMessage(final String error)
889 javax.swing.SwingUtilities.invokeLater(new Runnable()
894 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
895 MessageManager.getString("label.error_retrieving_data"),
896 JOptionPane.WARNING_MESSAGE);