6 import jalview.bin.Cache;
7 import jalview.datamodel.DBRefEntry;
8 import jalview.datamodel.SequenceGroup;
9 import jalview.datamodel.SequenceI;
10 import jalview.gui.AlignFrame;
11 import jalview.gui.Desktop;
12 import jalview.util.GroupUrlLink;
14 import java.awt.Cursor;
15 import java.awt.event.ActionEvent;
16 import java.awt.event.ActionListener;
17 import java.awt.event.ItemEvent;
18 import java.awt.event.ItemListener;
19 import java.io.BufferedReader;
20 import java.io.InputStreamReader;
22 import java.util.Hashtable;
23 import java.util.Vector;
25 import javax.swing.JMenu;
26 import javax.swing.JMenuItem;
27 import javax.swing.JOptionPane;
28 import javax.swing.event.MenuEvent;
29 import javax.swing.event.MenuListener;
30 import javax.xml.parsers.SAXParser;
31 import javax.xml.parsers.SAXParserFactory;
33 import org.xml.sax.Attributes;
34 import org.xml.sax.SAXException;
35 import org.xml.sax.helpers.DefaultHandler;
38 * Lightweight runnable to discover dynamic 'one way' group URL services
42 public class EnfinEnvision2OneWay extends DefaultHandler implements Runnable,WSMenuEntryProviderI
44 private static EnfinEnvision2OneWay groupURLLinksGatherer=null;
45 public static EnfinEnvision2OneWay getInstance() {
46 if (groupURLLinksGatherer==null) {
47 groupURLLinksGatherer = new EnfinEnvision2OneWay();
49 return groupURLLinksGatherer;
51 private void waitForCompletion() {
52 if (groupURLLinksGatherer.isRunning())
54 // wait around and show a visual delay indicator
55 Cursor oldCursor = Desktop.instance.getCursor();
56 Desktop.instance.setCursor(new Cursor(Cursor.WAIT_CURSOR));
57 while (groupURLLinksGatherer.isRunning())
61 } catch (InterruptedException e ){};
63 Desktop.instance.setCursor(oldCursor);
66 public Vector getEnvisionServiceGroupURLS() {
73 private static String BACKGROUND="BACKGROUNDPARAM";
75 * contains null strings or one of the above constants - indicate if this URL is a special case.
77 private Vector additionalPar = new Vector();
79 * the enfin service URL
81 private String enfinService=null;
82 private String description=null;
83 private String wfname;
85 * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
87 public void endElement(String uri, String localName, String qName)
91 // System.err.println("End element: : '"+uri+" "+localName+" "+qName);
92 if (qName.equalsIgnoreCase("workflow") && description!=null && description.length()>0)
94 //groupURLLinks.addElement("UNIPROT|EnVision2|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?tool=Jalview&workflow=Default&datasetName=JalviewIDs$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,");
95 //groupURLLinks.addElement("Seqs|EnVision2|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?tool=Jalview&workflow=Default&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/([A-Za-z]+)+/=$&inputType=1|,");
96 System.err.println("Adding entry for "+wfname+" "+description);
97 if (wfname.toLowerCase().indexOf("funcnet")==-1)
99 groupURLdescr.addElement(description);
100 groupURLdescr.addElement(description);
101 groupURLLinks.addElement(wfname+"|"+"http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?tool=Jalview&workflow="+wfname+"&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,"); // #"+description+"#");
102 groupURLLinks.addElement(wfname+"|"+"http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?tool=Jalview&workflow="+wfname+"&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/([A-Za-z]+)+/=$&inputType=1|,"); // #"+description+"#");
108 * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
110 public void characters(char[] ch, int start, int length)
113 if (description!=null) {
114 for (int i=start; i<start+length; i++) {
121 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
123 public void startElement(String uri, String localName, String qName,
124 Attributes attributes) throws SAXException
126 if (qName.equalsIgnoreCase("workflow"))
129 wfname = attributes.getValue("name");
131 if (qName.equalsIgnoreCase("description"))
137 //System.err.println("Start element: : '"+uri+" "+localName+" "+qName+" attributes"+attributes);
138 // super.startElement(uri,localName,qname,attributes);
141 private boolean started=false;
142 private boolean running=false;
143 private Vector groupURLLinks = null;
144 private Vector groupURLdescr = null;
145 private static String[] allowedDb=new String[] {"UNIPROT","EMBL","PDB"} ;
147 public EnfinEnvision2OneWay() {
148 groupURLLinks = new Vector();
149 groupURLdescr = new Vector();
151 enfinService = Cache.getDefault("ENVISION2_WORKFLOWSERVICE", "http://www.ebi.ac.uk/enfin-srv/envision2/pages/workflows.xml");
152 new Thread(this).start();
160 SAXParserFactory spf = SAXParserFactory.newInstance();
161 SAXParser sp = spf.newSAXParser();
162 sp.parse(new URL(enfinService).openStream(), this);
163 } catch (Exception e)
165 Cache.log.warn("Exception when discovering One Way services: ",e);
169 Cache.log.warn("Error when discovering One Way services: ",e);
172 Cache.log.debug("Finished running.");
176 * have we finished running yet ?
177 * @return false if we have been run.
179 public boolean isRunning()
182 // TODO Auto-generated method stub
183 return !started || running;
185 public static void main(String[] args){
187 EnfinEnvision2OneWay ow = new EnfinEnvision2OneWay();
188 while (ow.isRunning())
192 } catch (Exception e){};
195 for (int i=0;i<ow.groupURLLinks.size();i++) {
196 System.err.println("Description"+ow.groupURLdescr.elementAt(i)+"Service URL: "+ow.groupURLLinks.elementAt(i));
199 /// Copied from jalview.gui.PopupMenu
201 * add a late bound URL service item to the given menu
206 * @param urlgenerator GroupURLLink used to generate URL
207 * @param urlstub Object array returned from the makeUrlStubs function.
209 private void addshowLink(JMenu linkMenu, String label, String descr, final GroupUrlLink urlgenerator, final Object[] urlstub)
211 JMenuItem item = new JMenuItem(label);
212 item.setToolTipText("Submit ("+urlgenerator.getNumberInvolved(urlstub)+" seqs) to workflow: "+descr);
213 item.addActionListener(new java.awt.event.ActionListener()
215 public void actionPerformed(ActionEvent e)
217 new Thread(new Runnable()
222 showLink(urlgenerator.constructFrom(urlstub));
233 * open the given link in a new browser window
236 public void showLink(String url)
240 jalview.util.BrowserLauncher.openURL(url);
241 } catch (Exception ex)
244 .showInternalMessageDialog(
246 "Unixers: Couldn't find default web browser."
247 + "\nAdd the full path to your browser in Preferences.",
248 "Web browser not found", JOptionPane.WARNING_MESSAGE);
250 ex.printStackTrace();
254 * called by a web service menu instance when it is opened.
255 * @param enfinServiceMenu
258 private void buildGroupLinkMenu(JMenu enfinServiceMenu,
259 AlignFrame alignFrame)
261 SequenceI[] seqs = alignFrame.getViewport().getSelectionAsNewSequence();
262 SequenceGroup sg = alignFrame.getViewport().getSelectionGroup();
264 // consider visible regions here/
266 enfinServiceMenu.removeAll();
267 JMenu entries = buildGroupURLMenu(seqs,sg);
270 for (int i=0,iSize=entries.getMenuComponentCount();i<iSize;i++)
272 // transfer - menu component is removed from entries automatically
273 enfinServiceMenu.add(entries.getMenuComponent(0));
275 // entries.removeAll();
276 enfinServiceMenu.setEnabled(true);
278 enfinServiceMenu.setEnabled(false);
283 * construct a dynamic enfin services menu given a sequence selection
289 private JMenu buildGroupURLMenu(SequenceI[] seqs, SequenceGroup sg)
292 // TODO: usability: thread off the generation of group url content so root menu appears asap
293 // sequence only URLs
294 // ID/regex match URLs
295 JMenu groupLinksMenu = new JMenu("Group Link");
296 JMenu[] linkMenus = new JMenu[] { null, new JMenu("IDS"), new JMenu("Sequences"), new JMenu("IDS and Sequences")}; // three types of url that might be created.
297 String[][] idandseqs = GroupUrlLink.formStrings(seqs);
298 Hashtable commonDbrefs = new Hashtable();
299 for (int sq = 0; sq<seqs.length;sq++) {
303 start = seqs[sq].findPosition(sg.getStartRes());
304 end=seqs[sq].findPosition(sg.getEndRes());
306 // get total width of alignment.
307 start = seqs[sq].getStart();
308 end = seqs[sq].findPosition(seqs[sq].getLength());
310 // we skip sequences which do not have any non-gaps in the region of interest
315 // just collect ids from dataset sequence
316 // TODO: check if IDs collected from selecton group intersects with the current selection, too
317 SequenceI sqi = seqs[sq];
318 while (sqi.getDatasetSequence()!=null) {
319 sqi = sqi.getDatasetSequence(); }
320 DBRefEntry[] dbr = sqi.getDBRef();
321 if (dbr!=null && dbr.length>0)
323 for (int d=0;d<dbr.length;d++)
325 String src =dbr[d].getSource(); // jalview.util.DBRefUtils.getCanonicalName(dbr[d].getSource()).toUpperCase();
326 Object[] sarray = (Object[]) commonDbrefs.get(src);
329 sarray = new Object[2];
330 sarray[0] = new int[] { 0 };
331 sarray[1] = new String[seqs.length];
333 commonDbrefs.put(src,sarray);
336 if (((String[])sarray[1])[sq]==null) {
337 if (!dbr[d].hasMap() || (dbr[d].getMap().locateMappedRange(start, end)!=null)) {
338 ((String[])sarray[1])[sq] = dbr[d].getAccessionId();
339 ((int[])sarray[0])[0]++;
345 // now create group links for all distinct ID/sequence sets.
346 boolean addMenu = false; // indicates if there are any group links to give to user
347 for (int i = 0; i < groupURLLinks.size(); i++) {
348 String link = groupURLLinks.elementAt(i).toString();
349 String descr = groupURLdescr.elementAt(i).toString();
350 // boolean specialCase = additionalPar.elementAt(i).toString().equals(BACKGROUND);
351 GroupUrlLink urlLink = null;
354 urlLink = new GroupUrlLink(link);
355 } catch (Exception foo)
357 jalview.bin.Cache.log.error("Exception for GroupURLLink '" + link
362 if (!urlLink.isValid())
364 jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
367 final String label = urlLink.getLabel();
368 boolean usingNames = false;
369 // Now see which parts of the group apply for this URL
371 String[] seqstr,ids; // input to makeUrl
372 for (int t=0;t<allowedDb.length; t++) {
373 ltarget = allowedDb[t]; // jalview.util.DBRefUtils.getCanonicalName(urlLink.getTarget());
374 Object[] idset = (Object[]) commonDbrefs.get(ltarget.toUpperCase());
377 int numinput = ((int[])idset[0])[0];
378 String[] allids = ((String[])idset[1]);
379 seqstr = new String[numinput];
380 ids = new String[numinput];
381 for (int sq=0,idcount=0;sq<seqs.length;sq++)
383 if (allids[sq]!=null) {
384 ids[idcount] = allids[sq];
385 seqstr[idcount++] = idandseqs[1][sq];
388 addMenu = addMenu | createAndAddLinks(linkMenus,false,urlLink,label,ltarget,descr, ids,seqstr);
391 // also do names only.
392 seqstr = idandseqs[1];
394 addMenu = addMenu | createAndAddLinks(linkMenus,true,urlLink,label,"Names",descr, ids,seqstr);
398 groupLinksMenu = new JMenu("Group Links");
399 for (int m=0;m<linkMenus.length; m++)
401 if (linkMenus[m]!=null && linkMenus[m].getMenuComponentCount()>0)
403 groupLinksMenu.add(linkMenus[m]);
407 return groupLinksMenu;
412 private boolean createAndAddLinks(JMenu[] linkMenus, boolean usingNames,
413 GroupUrlLink urlLink, String label, String ltarget, String descr, String[] ids,
416 Object[] urlset = urlLink.makeUrlStubs(ids,seqstr, "FromJalview"+System.currentTimeMillis(),false);
419 int type = urlLink.getGroupURLType() & 3;
420 //System.out.println(urlLink.getGroupURLType() +" "+((String[])urlset[3])[0]);
421 // first two bits ofurlLink type bitfield are sequenceids and sequences
422 // TODO: FUTURE: ensure the groupURL menu structure can be generalised
423 addshowLink(linkMenus[type], label + (((type & 1)==1) ? ("("+(usingNames ? "Names" : ltarget)+")") : ""), descr, urlLink, urlset);
428 /// end of stuff copied from popupmenu
429 public void attachWSMenuEntry(final JMenu wsmenu, final AlignFrame alignFrame)
431 final JMenu enfinServiceMenu = new JMenu("Envision 2");
432 wsmenu.add(enfinServiceMenu);
433 enfinServiceMenu.setEnabled(false);
434 wsmenu.addMenuListener(new MenuListener()
436 // this listener remembers when the menu was first selected, and
437 // doesn't rebuild the session list until it has been cleared and
439 boolean refresh = true;
441 public void menuCanceled(MenuEvent e)
446 public void menuDeselected(MenuEvent e)
451 public void menuSelected(MenuEvent e)
456 buildGroupLinkMenu(enfinServiceMenu,alignFrame);
457 } catch (OutOfMemoryError ex)
459 Cache.log.error("Out of memory when calculating the Envision2 links.",ex);
460 enfinServiceMenu.setEnabled(false);