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 java.awt.BorderLayout;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.awt.event.KeyAdapter;
28 import java.awt.event.KeyEvent;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Iterator;
32 import java.util.List;
34 import javax.swing.JButton;
35 import javax.swing.JCheckBox;
36 import javax.swing.JInternalFrame;
37 import javax.swing.JLabel;
38 import javax.swing.JOptionPane;
39 import javax.swing.JPanel;
40 import javax.swing.JScrollPane;
41 import javax.swing.JTextArea;
42 import javax.swing.SwingConstants;
43 import javax.swing.tree.DefaultMutableTreeNode;
45 import com.stevesoft.pat.Regex;
47 import jalview.datamodel.Alignment;
48 import jalview.datamodel.AlignmentI;
49 import jalview.datamodel.DBRefEntry;
50 import jalview.datamodel.DBRefSource;
51 import jalview.datamodel.SequenceFeature;
52 import jalview.datamodel.SequenceI;
53 import jalview.io.FormatAdapter;
54 import jalview.io.IdentifyFile;
55 import jalview.util.DBRefUtils;
56 import jalview.util.MessageManager;
57 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
58 import jalview.ws.seqfetcher.DbSourceProxy;
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;
118 int debounceTrap = 0;
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(null, Thread.currentThread().hashCode());
183 lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
184 .getLocalSourceString()).hashCode();
186 _initingFetcher = false;
187 initingThread = null;
192 private IProgressIndicator progressIndicator;
193 public SequenceFetcher(IProgressIndicator guiIndic)
195 this.progressIndicator = guiIndic;
196 final SequenceFetcher us = this;
197 // launch initialiser thread
198 Thread sf = new Thread(new Runnable()
204 if (getSequenceFetcherSingleton(progressIndicator) != null)
206 us.initGui(progressIndicator);
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") && ((debounceTrap % 2) == 0))
375 jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
376 jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
377 JPanel jPanel2a = new JPanel(new BorderLayout());
378 jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
379 jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
380 jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
381 // jPanel2.setPreferredSize(new Dimension())
382 jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
383 this.add(jPanel1, java.awt.BorderLayout.SOUTH);
384 this.add(jPanel3, java.awt.BorderLayout.CENTER);
385 this.add(jPanel2, java.awt.BorderLayout.NORTH);
386 jScrollPane1.getViewport().add(textArea);
390 private void pdbSourceAction()
392 databaseButt.setText(database.getSelectedItem());
393 new PDBSearchPanel(this);
397 private void otherSourceAction()
401 databaseButt.setText(database.getSelectedItem()
402 + (database.getSelectedSources().size() > 1 ? " (and "
403 + database.getSelectedSources().size() + " others)"
405 String eq = database.getExampleQueries();
406 dbeg.setText(MessageManager.formatMessage(
407 "label.example_query_param", new String[]
409 boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
410 for (DbSourceProxy dbs : database.getSelectedSources())
412 if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
418 replacePunctuation.setEnabled(enablePunct);
420 } catch (Exception ex)
423 replacePunctuation.setEnabled(true);
428 protected void example_actionPerformed()
430 DbSourceProxy db = null;
433 textArea.setText(database.getExampleQueries());
434 } catch (Exception ex)
440 protected void clear_actionPerformed()
442 textArea.setText("");
448 public void close_actionPerformed(ActionEvent e)
452 frame.setClosed(true);
453 } catch (Exception ex)
458 public void ok_actionPerformed()
460 databaseButt.setEnabled(false);
461 example.setEnabled(false);
462 textArea.setEnabled(false);
463 ok.setEnabled(false);
464 close.setEnabled(false);
466 Thread worker = new Thread(this);
470 private void resetDialog()
472 databaseButt.setEnabled(true);
473 example.setEnabled(true);
474 textArea.setEnabled(true);
476 close.setEnabled(true);
483 if (!database.hasSelection())
485 error += "Please select the source database\n";
487 // TODO: make this transformation more configurable
488 com.stevesoft.pat.Regex empty;
489 if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
491 empty = new com.stevesoft.pat.Regex(
492 // replace commas and spaces with a semicolon
493 "(\\s|[,; ])+", ";");
497 // just turn spaces and semicolons into single semicolons
498 empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
500 textArea.setText(empty.replaceAll(textArea.getText()));
501 // see if there's anthing to search with
502 if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
505 error += "Please enter a (semi-colon separated list of) database id(s)";
507 if (error.length() > 0)
509 showErrorMessage(error);
513 // indicate if successive sources should be merged into one alignment.
514 boolean addToLast = false;
515 ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
516 ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
517 Iterator<DbSourceProxy> proxies = database.getSelectedSources()
520 List<String> nextfetch = Arrays.asList(qries = textArea.getText()
522 Iterator<String> en = Arrays.asList(new String[0]).iterator();
523 int nqueries = qries.length;
524 while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
526 if (!en.hasNext() && nextfetch.size() > 0)
528 en = nextfetch.iterator();
529 nqueries = nextfetch.size();
530 // save the remaining queries in the original array
531 qries = nextfetch.toArray(new String[nqueries]);
532 nextfetch = new ArrayList<String>();
535 DbSourceProxy proxy = proxies.next();
536 boolean isAliSource = false;
540 guiWindow.setProgressBar(MessageManager.formatMessage("status.fetching_sequence_queries_from", new String[]{Integer.valueOf(nqueries).toString(),proxy.getDbName()}), Thread
541 .currentThread().hashCode());
542 isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
543 if (proxy.getAccessionSeparator() == null)
547 String item = en.next();
554 // give the server a chance to breathe
556 } catch (Exception e)
563 AlignmentI indres = null;
566 indres = proxy.getSequenceRecords(item);
567 } catch (OutOfMemoryError oome)
569 new OOMWarning("fetching " + item + " from "
570 + proxy.getDbName(), oome, this);
581 } catch (Exception e)
583 jalview.bin.Cache.log.info("Error retrieving " + item
584 + " from " + proxy.getDbName(), e);
591 StringBuffer multiacc = new StringBuffer();
592 ArrayList<String> tosend = new ArrayList<String>();
595 String nel = en.next();
597 multiacc.append(nel);
600 multiacc.append(proxy.getAccessionSeparator());
607 List<String> nores = new ArrayList<String>();
608 rslt = proxy.getSequenceRecords(multiacc.toString());
609 if (rslt == null || rslt.getHeight() == 0)
611 // no results - pass on all queries to next source
612 nextfetch.addAll(tosend);
616 aresultq.add(multiacc.toString());
619 rs = rslt.getSequencesArray();
620 // search for each query in the dbrefs associated with each
623 // ones we do not find will be used to query next source (if any)
624 for (String q : tosend)
626 DBRefEntry dbr = new DBRefEntry(), found[] = null;
627 dbr.setSource(proxy.getDbSource());
628 dbr.setVersion(null);
629 if (proxy.getAccessionValidator() != null)
631 Regex vgr = proxy.getAccessionValidator();
633 if (vgr.numSubs() > 0)
635 dbr.setAccessionId(vgr.stringMatched(1));
639 dbr.setAccessionId(vgr.stringMatched());
644 dbr.setAccessionId(q);
646 boolean rfound = false;
647 for (int r = 0; r < rs.length; r++)
650 && (found = DBRefUtils.searchRefs(
651 rs[r].getDBRef(), dbr)) != null
665 } catch (OutOfMemoryError oome)
667 new OOMWarning("fetching " + multiacc + " from "
668 + database.getSelectedItem(), oome, this);
672 } catch (Exception e)
674 showErrorMessage("Error retrieving " + textArea.getText()
675 + " from " + database.getSelectedItem());
677 // +="Couldn't retrieve sequences from "+database.getSelectedItem();
678 System.err.println("Retrieval failed for source ='"
679 + database.getSelectedItem() + "' and query\n'"
680 + textArea.getText() + "'\n");
682 } catch (OutOfMemoryError e)
684 // resets dialog box - so we don't use OOMwarning here.
685 showErrorMessage("Out of Memory when retrieving "
688 + database.getSelectedItem()
689 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
693 showErrorMessage("Serious Error retrieving " + textArea.getText()
694 + " from " + database.getSelectedItem());
697 // Stack results ready for opening in alignment windows
698 if (aresult != null && aresult.size() > 0)
700 AlignmentI ar = null;
704 // new window for each result
705 while (aresult.size() > 0)
707 presult.add(aresult.remove(0));
708 presultTitle.add(aresultq.remove(0) + " "
709 + getDefaultRetrievalTitle());
715 if (addToLast && presult.size() > 0)
717 ar = presult.remove(presult.size() - 1);
718 titl = presultTitle.remove(presultTitle.size() - 1);
720 // concatenate all results in one window
721 while (aresult.size() > 0)
725 ar = aresult.remove(0);
729 ar.append(aresult.remove(0));
735 presultTitle.add(titl);
738 guiWindow.setProgressBar(MessageManager.getString("status.finshed_querying"), Thread.currentThread()
741 guiWindow.setProgressBar((presult.size() > 0) ? MessageManager.getString("status.parsing_results")
742 : MessageManager.getString("status.processing"), Thread.currentThread().hashCode());
744 while (presult.size() > 0)
746 parseResult(presult.remove(0), presultTitle.remove(0), null);
748 // only remove visual delay after we finished parsing.
749 guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
750 if (nextfetch.size() > 0)
752 StringBuffer sb = new StringBuffer();
753 sb.append("Didn't retrieve the following "
754 + (nextfetch.size() == 1 ? "query" : nextfetch.size()
755 + " queries") + ": \n");
756 int l = sb.length(), lr = 0;
757 for (String s : nextfetch)
759 if (l != sb.length())
763 if (lr - sb.length() > 40)
769 showErrorMessage(sb.toString());
774 AlignmentI parseResult(String result, String title)
776 String format = new IdentifyFile().Identify(result, "Paste");
777 Alignment sequences = null;
778 if (FormatAdapter.isValidFormat(format))
783 sequences = new FormatAdapter().readFile(result.toString(),
785 } catch (Exception ex)
789 if (sequences != null)
791 return parseResult(sequences, title, format);
796 showErrorMessage("Error retrieving " + textArea.getText() + " from "
797 + database.getSelectedItem());
805 * @return a standard title for any results retrieved using the currently
806 * selected source and settings
808 public String getDefaultRetrievalTitle()
810 return "Retrieved from " + database.getSelectedItem();
813 AlignmentI parseResult(AlignmentI al, String title,
814 String currentFileFormat)
817 if (al != null && al.getHeight() > 0)
821 title = getDefaultRetrievalTitle();
823 if (alignFrame == null)
825 AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
826 AlignFrame.DEFAULT_HEIGHT);
827 if (currentFileFormat != null)
829 af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
831 // NON-FormatAdapter Sourced
835 SequenceFeature[] sfs = null;
836 List<SequenceI> alsqs;
837 synchronized (alsqs = al.getSequences())
839 for (SequenceI sq : alsqs)
841 if ((sfs = sq.getSequenceFeatures()) != null)
845 af.setShowSeqFeatures(true);
852 Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
853 AlignFrame.DEFAULT_HEIGHT);
855 af.statusBar.setText(MessageManager
856 .getString("label.successfully_pasted_alignment_file"));
860 af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
862 } catch (Exception ex)
868 alignFrame.viewport.addAlignment(al, title);
874 void showErrorMessage(final String error)
877 javax.swing.SwingUtilities.invokeLater(new Runnable()
882 JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
883 MessageManager.getString("label.error_retrieving_data"),
884 JOptionPane.WARNING_MESSAGE);
889 public IProgressIndicator getProgressIndicator()
891 return progressIndicator;
894 public void setProgressIndicator(IProgressIndicator progressIndicator)
896 this.progressIndicator = progressIndicator;