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