437d3b4521a010dfbe035da35e8d2caaa8e35233
[jalview.git] / src / jalview / ws / rest / RestClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
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.
10  *  
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.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.ws.rest;
19
20 import java.awt.event.ActionEvent;
21 import java.awt.event.ActionListener;
22 import java.util.Hashtable;
23 import java.util.Vector;
24
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
31 import jalview.bin.Cache;
32 import jalview.datamodel.AlignmentView;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.AlignmentPanel;
36 import jalview.gui.Desktop;
37 import jalview.gui.WebserviceInfo;
38 import jalview.io.packed.DataProvider.JvDataType;
39 import jalview.ws.WSClient;
40 import jalview.ws.WSClientI;
41 import jalview.ws.WSMenuEntryProviderI;
42
43 /**
44  * @author JimP
45  * 
46  */
47 public class RestClient extends WSClient implements WSClientI,
48         WSMenuEntryProviderI
49 {
50   RestServiceDescription service;
51
52   public RestClient(RestServiceDescription rsd)
53   {
54     service = rsd;
55   }
56
57   /**
58    * parent alignframe for this job
59    */
60   AlignFrame af;
61
62   /**
63    * alignment view which provides data for job.
64    */
65   AlignViewport av;
66
67   /**
68    * get the alignFrame for the associated input data if it exists.
69    * 
70    * @return
71    */
72   protected AlignFrame recoverAlignFrameForView()
73   {
74     return jalview.gui.Desktop.getAlignFrameFor(av);
75   }
76
77   public RestClient(RestServiceDescription service2, AlignFrame alignFrame)
78   {
79     this(service2, alignFrame, false);
80   }
81   boolean headless = false;
82   public RestClient(RestServiceDescription service2, AlignFrame alignFrame, boolean nogui)
83   {
84     service = service2;
85     af = alignFrame;
86     av = alignFrame.getViewport();
87     headless = nogui;
88     constructJob();
89   }
90
91   public void setWebserviceInfo(boolean headless)
92   {
93     WebServiceJobTitle = service.details.Action + " using "
94             + service.details.Name;
95     WebServiceName = service.details.Name;
96     WebServiceReference = "No reference - go to url for more info";
97     if (service.details.description != null)
98     {
99       WebServiceReference = service.details.description;
100     }
101     if (!headless)
102     {
103       wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceName + "\n"
104               + WebServiceReference);
105       wsInfo.setRenderAsHtml(true);
106     }
107
108   }
109
110   @Override
111   public boolean isCancellable()
112   {
113     // TODO define process for cancelling rsbws jobs
114     return false;
115   }
116
117   @Override
118   public boolean canMergeResults()
119   {
120     // TODO process service definition to identify if the results might be
121     // mergeable
122     // TODO: change comparison for annotation merge
123     return false;
124   }
125
126   @Override
127   public void cancelJob()
128   {
129     System.err.println("Cannot cancel this job type: " + service);
130   }
131
132   @Override
133   public void attachWSMenuEntry(final JMenu wsmenu,
134           final AlignFrame alignFrame)
135   {
136     JMenuItem submit = new JMenuItem(service.details.Name);
137     submit.setToolTipText(service.details.Action + " using "
138             + service.details.Name);
139     submit.addActionListener(new ActionListener()
140     {
141
142       @Override
143       public void actionPerformed(ActionEvent e)
144       {
145         new RestClient(service, alignFrame);
146       }
147
148     });
149     wsmenu.add(submit);
150     // TODO: menu listener should enable/disable entry depending upon selection
151     // state of the alignment
152     wsmenu.addMenuListener(new MenuListener()
153     {
154
155       @Override
156       public void menuSelected(MenuEvent e)
157       {
158         // TODO Auto-generated method stub
159
160       }
161
162       @Override
163       public void menuDeselected(MenuEvent e)
164       {
165         // TODO Auto-generated method stub
166
167       }
168
169       @Override
170       public void menuCanceled(MenuEvent e)
171       {
172         // TODO Auto-generated method stub
173
174       }
175
176     });
177
178   }
179
180   /**
181    * record of initial undoredo hash for the alignFrame providing data for this
182    * job.
183    */
184   long[] undoredo = null;
185
186   /**
187    * Compare the original input data to the data currently presented to the
188    * user. // LOGIC: compare undo/redo - if same, merge regardless (coping with
189    * any changes in hidden columns as normal) // if different undo/redo then
190    * compare region that was submitted // if same, then merge as before, if
191    * different then prompt user to open a new window.
192    * 
193    * @return
194    */
195   protected boolean isAlignmentModified()
196   {
197     if (undoredo == null || av == null || av.getAlignment() == null)
198     {
199       // always return modified if we don't have access to live GUI elements
200       // anymore.
201       return true;
202     }
203     if (av.isUndoRedoHashModified(undoredo))
204     {
205       // alignment has been modified in some way.
206       return true;
207     }
208     // TODO: look deeper into modification of selection state, etc that may
209     // affect RestJobThread.realiseResults(boolean merge);
210     return false;
211
212   }
213
214   /**
215    * TODO: combine to form a dataset+alignment+annotation context
216    */
217   AlignmentView _input;
218
219   /**
220    * input data context
221    */
222   jalview.io.packed.JalviewDataset jds;
223
224   /**
225    * informative name for results
226    */
227   public String viewTitle;
228   protected void constructJob()
229   {
230     service.setInvolvesFlags();
231     // record all aspects of alignment view so we can merge back or recreate
232     // later
233     undoredo = av.getUndoRedoHash();
234     /**
235      * delete ? Vector sgs = av.getAlignment().getGroups(); if (sgs!=null) {
236      * _sgs = new SequenceGroup[sgs.size()]; sgs.copyInto(_sgs); } else { _sgs =
237      * new SequenceGroup[0]; }
238      */
239     boolean selExists = (av.getSelectionGroup() != null)
240             && (av.getSelectionGroup().getSize() > 1);
241     // TODO: JAL-715: refactor to alignViewport methods and revise to full
242     // focus+context+dataset input data staging model
243     if (selExists)
244     {
245       if (service.partitiondata)
246       {
247         if (av.getAlignment().getGroups() != null
248                 && av.getAlignment().getGroups().size() > 0)
249         {
250           // intersect groups with selected region
251           _input = new AlignmentView(av.getAlignment(),
252                   av.getColumnSelection(), av.getSelectionGroup(),
253                   av.hasHiddenColumns(), true, true);
254           viewTitle = "selected "
255                   + (av.hasHiddenColumns() ? "visible" : "")
256                   + " region of " + af.getTitle();
257         }
258         else
259         {
260           // use selected region to partition alignment
261           _input = new AlignmentView(av.getAlignment(),
262                   av.getColumnSelection(), av.getSelectionGroup(),
263                   av.hasHiddenColumns(), false, true);
264         }
265         viewTitle = "select and unselected "
266                 + (av.hasHiddenColumns() ? "visible" : "")
267                 + " regions from " + af.getTitle();
268       }
269       else
270       {
271         // just take selected region intersection
272         _input = new AlignmentView(av.getAlignment(),
273                 av.getColumnSelection(), av.getSelectionGroup(),
274                 av.hasHiddenColumns(), true, true);
275         viewTitle = "selected " + (av.hasHiddenColumns() ? "visible" : "")
276                 + " region of " + af.getTitle();
277       }
278     }
279     else
280     {
281       // standard alignment view without selection present
282       _input = new AlignmentView(av.getAlignment(),
283               av.getColumnSelection(), null, av.hasHiddenColumns(), false,
284               true);
285       viewTitle = "" + (av.hasHiddenColumns() ? "visible region of " : "")
286               + af.getTitle();
287     }
288
289     RestJobThread jobsthread = new RestJobThread(this);
290
291     if (jobsthread.isValid())
292     {
293       setWebserviceInfo(headless);
294       if (!headless) {
295         wsInfo.setthisService(this);
296         jobsthread.setWebServiceInfo(wsInfo);
297       }
298       jobsthread.start();
299     }
300     else
301     {
302       // TODO: try to tell the user why the job couldn't be started.
303       JOptionPane
304               .showMessageDialog(
305                       Desktop.desktop,
306                       (jobsthread.hasWarnings() ? jobsthread.getWarnings()
307                               : "The Job couldn't be started. Please check your input, and the Jalview console for any warning messages."),
308                       "Unable to start web service analysis",
309                       JOptionPane.WARNING_MESSAGE);
310     }
311   }
312
313   public static RestClient makeShmmrRestClient()
314   {
315     String action = "Analysis", description = "Sequence Harmony and Multi-Relief (Brandt et al. 2010)", name = "Multi-Harmony";
316     Hashtable<String, InputType> iparams = new Hashtable<String, InputType>();
317     jalview.ws.rest.params.JobConstant toolp;
318     // toolp = new jalview.ws.rest.JobConstant("tool","jalview");
319     // iparams.put(toolp.token, toolp);
320     // toolp = new jalview.ws.rest.params.JobConstant("mbjob[method]","shmr");
321     // iparams.put(toolp.token, toolp);
322     // toolp = new
323     // jalview.ws.rest.params.JobConstant("mbjob[description]","step 1");
324     // iparams.put(toolp.token, toolp);
325     // toolp = new jalview.ws.rest.params.JobConstant("start_search","1");
326     // iparams.put(toolp.token, toolp);
327     // toolp = new jalview.ws.rest.params.JobConstant("blast","0");
328     // iparams.put(toolp.token, toolp);
329
330     jalview.ws.rest.params.Alignment aliinput = new jalview.ws.rest.params.Alignment();
331     // SHMR server has a 65K limit for content pasted into the 'ali' parameter,
332     // so we always upload our files.
333     aliinput.token = "ali_file";
334     aliinput.writeAsFile = true;
335     iparams.put(aliinput.token, aliinput);
336     jalview.ws.rest.params.SeqGroupIndexVector sgroups = new jalview.ws.rest.params.SeqGroupIndexVector();
337     sgroups.setMinsize(2);
338     sgroups.min = 2;// need at least two group defined to make a partition
339     iparams.put("groups", sgroups);
340     sgroups.token = "groups";
341     sgroups.sep = " ";
342     RestServiceDescription shmrService = new RestServiceDescription(
343             action,
344             description,
345             name,
346             "http://zeus.few.vu.nl/programs/shmrwww/index.php?tool=jalview",// ?tool=jalview&mbjob[method]=shmr&mbjob[description]=step1",
347             "?tool=jalview", iparams, true, false, '-');
348     // a priori knowledge of the data returned from the service
349     shmrService.addResultDatatype(JvDataType.ANNOTATION);
350     return new RestClient(shmrService);
351   }
352
353   public AlignmentPanel recoverAlignPanelForView()
354   {
355     AlignmentPanel[] aps = Desktop
356             .getAlignmentPanels(av.getSequenceSetId());
357     for (AlignmentPanel alp : aps)
358     {
359       if (alp.av == av)
360       {
361         return alp;
362       }
363     }
364     return null;
365   }
366
367   public boolean isShowResultsInNewView()
368   {
369     // TODO make this a property of the service
370     return true;
371   }
372
373   protected static Vector<String> services = null;
374
375   public static final String RSBS_SERVICES = "RSBS_SERVICES";
376
377   public static RestClient[] getRestClients()
378   {
379     if (services == null)
380     {
381       services = new Vector<String>();
382       try
383       {
384         for (RestServiceDescription descr : RestServiceDescription
385                 .parseDescriptions(jalview.bin.Cache.getDefault(
386                         RSBS_SERVICES,
387                         makeShmmrRestClient().service.toString())))
388         {
389           services.add(descr.toString());
390         }
391       } catch (Exception ex)
392       {
393         System.err
394                 .println("Serious - RSBS descriptions in user preferences are corrupt!");
395         ex.printStackTrace();
396       }
397
398     }
399     RestClient[] lst = new RestClient[services.size()];
400     int i = 0;
401     for (String svc : services)
402     {
403       lst[i++] = new RestClient(new RestServiceDescription(svc));
404     }
405     return lst;
406   }
407
408   public static void main(String args[])
409   {
410     try
411     {
412       RestClient[] clients = getRestClients();
413       System.out.println("Got " + clients.length + " clients.");
414       int i = 0;
415       Vector<String> urls = new Vector<String>();
416       for (RestClient cl : clients)
417       {
418         System.out.println("" + (++i) + ": " + cl.service.toString());
419         urls.add(cl.service.toString());
420       }
421       setRsbsServices(urls);
422       if (clients.length != getRestClients().length)
423       {
424         System.err
425                 .println("Failed. Differing numbers of clients when stringified and parsed again.");
426       }
427
428     } catch (Throwable x)
429     {
430       System.err.println("Failed. Unexpected exception.");
431       x.printStackTrace();
432     }
433   }
434
435   public String getAction()
436   {
437     return service.details.Action;
438   }
439
440   public RestServiceDescription getRestDescription()
441   {
442     return service;
443   }
444
445   public static Vector<String> getRsbsDescriptions()
446   {
447     Vector<String> rsbsDescrs = new Vector<String>();
448     for (RestClient rsbs : getRestClients())
449     {
450       rsbsDescrs.add(rsbs.getRestDescription().toString());
451     }
452     return rsbsDescrs;
453   }
454
455   public static void setRsbsServices(Vector<String> rsbsUrls)
456   {
457     if (rsbsUrls != null)
458     {
459       // TODO: consider validating services ?
460       services = new Vector<String>(rsbsUrls);
461       StringBuffer sprop = new StringBuffer();
462       for (String s : services)
463       {
464         sprop.append(s);
465       }
466       Cache.setProperty(RSBS_SERVICES, sprop.toString());
467     }
468     else
469     {
470       Cache.removeProperty(RSBS_SERVICES);
471     }
472   }
473
474 }