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