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