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