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