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