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