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