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