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