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