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