d84206fecd7ab06e3f2a5f988dc46396079bdd1e
[jalview.git] / src / jalview / ws / rest / RestClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.JvOptionPane;
30 import jalview.gui.WebserviceInfo;
31 import jalview.util.MessageManager;
32 import jalview.ws.WSClient;
33 import jalview.ws.WSClientI;
34 import jalview.ws.WSMenuEntryProviderI;
35 import jalview.ws.rest.clientdefs.ShmrRestClient;
36
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.util.Vector;
40
41 import javax.swing.JMenu;
42 import javax.swing.JMenuItem;
43 import javax.swing.event.MenuEvent;
44 import javax.swing.event.MenuListener;
45
46 /**
47  * @author JimP
48  * 
49  */
50 public class RestClient extends WSClient
51         implements WSClientI, 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
85   boolean headless = false;
86
87   public RestClient(RestServiceDescription service2, AlignFrame alignFrame,
88           boolean nogui)
89   {
90     service = service2;
91     af = alignFrame;
92     av = alignFrame.getViewport();
93     headless = nogui;
94     constructJob();
95   }
96
97   public void setWebserviceInfo(boolean headless)
98   {
99     WebServiceJobTitle = MessageManager
100             .formatMessage("label.webservice_job_title", new String[]
101             { service.details.getAction(), service.details.getName() });
102     WebServiceName = service.details.getName();
103     WebServiceReference = "No reference - go to url for more info";
104     if (service.details.getDescription() != null)
105     {
106       WebServiceReference = service.details.getDescription();
107     }
108     if (!headless)
109     {
110       wsInfo = new WebserviceInfo(WebServiceJobTitle,
111               WebServiceName + "\n" + WebServiceReference, true);
112       wsInfo.setRenderAsHtml(true);
113     }
114
115   }
116
117   @Override
118   public boolean isCancellable()
119   {
120     // TODO define process for cancelling rsbws jobs
121     return false;
122   }
123
124   @Override
125   public boolean canMergeResults()
126   {
127     // TODO process service definition to identify if the results might be
128     // mergeable
129     // TODO: change comparison for annotation merge
130     return false;
131   }
132
133   @Override
134   public void cancelJob()
135   {
136     System.err.println("Cannot cancel this job type: " + service);
137   }
138
139   @Override
140   public void attachWSMenuEntry(final JMenu wsmenu,
141           final AlignFrame alignFrame)
142   {
143     JMenuItem submit = new JMenuItem(service.details.getName());
144     submit.setToolTipText(MessageManager
145             .formatMessage("label.rest_client_submit", new String[]
146             { service.details.getAction(), service.details.getName() }));
147     submit.addActionListener(new ActionListener()
148     {
149
150       @Override
151       public void actionPerformed(ActionEvent e)
152       {
153         new RestClient(service, alignFrame);
154       }
155
156     });
157     wsmenu.add(submit);
158     // TODO: menu listener should enable/disable entry depending upon selection
159     // state of the alignment
160     wsmenu.addMenuListener(new MenuListener()
161     {
162
163       @Override
164       public void menuSelected(MenuEvent e)
165       {
166         // TODO Auto-generated method stub
167
168       }
169
170       @Override
171       public void menuDeselected(MenuEvent e)
172       {
173         // TODO Auto-generated method stub
174
175       }
176
177       @Override
178       public void menuCanceled(MenuEvent e)
179       {
180         // TODO Auto-generated method stub
181
182       }
183
184     });
185
186   }
187
188   /**
189    * record of initial undoredo hash for the alignFrame providing data for this
190    * job.
191    */
192   long[] undoredo = null;
193
194   /**
195    * Compare the original input data to the data currently presented to the
196    * user. // LOGIC: compare undo/redo - if same, merge regardless (coping with
197    * any changes in hidden columns as normal) // if different undo/redo then
198    * compare region that was submitted // if same, then merge as before, if
199    * different then prompt user to open a new window.
200    * 
201    * @return
202    */
203   protected boolean isAlignmentModified()
204   {
205     if (undoredo == null || av == null || av.getAlignment() == null)
206     {
207       // always return modified if we don't have access to live GUI elements
208       // anymore.
209       return true;
210     }
211     if (av.isUndoRedoHashModified(undoredo))
212     {
213       // alignment has been modified in some way.
214       return true;
215     }
216     // TODO: look deeper into modification of selection state, etc that may
217     // affect RestJobThread.realiseResults(boolean merge);
218     return false;
219
220   }
221
222   /**
223    * TODO: combine to form a dataset+alignment+annotation context
224    */
225   AlignmentView _input;
226
227   /**
228    * input data context
229    */
230   jalview.io.packed.JalviewDataset jds;
231
232   /**
233    * informative name for results
234    */
235   public String viewTitle;
236
237   protected void constructJob()
238   {
239     service.setInvolvesFlags();
240     // record all aspects of alignment view so we can merge back or recreate
241     // later
242     undoredo = av.getUndoRedoHash();
243     /**
244      * delete ? Vector sgs = av.getAlignment().getGroups(); if (sgs!=null) {
245      * _sgs = new SequenceGroup[sgs.size()]; sgs.copyInto(_sgs); } else { _sgs =
246      * new SequenceGroup[0]; }
247      */
248     boolean selExists = (av.getSelectionGroup() != null)
249             && (av.getSelectionGroup().getSize() > 1);
250     // TODO: JAL-715: refactor to alignViewport methods and revise to full
251     // focus+context+dataset input data staging model
252     if (selExists)
253     {
254       if (service.partitiondata)
255       {
256         if (av.getAlignment().getGroups() != null
257                 && av.getAlignment().getGroups().size() > 0)
258         {
259           // intersect groups with selected region
260           _input = new AlignmentView(av.getAlignment(),
261                   av.getAlignment().getHiddenColumns(),
262                   av.getSelectionGroup(), av.hasHiddenColumns(), true,
263                   true);
264           viewTitle = MessageManager.formatMessage(
265                   "label.select_visible_region_of", new String[]
266                   { (av.hasHiddenColumns()
267                           ? MessageManager.getString("label.visible")
268                           : ""),
269                       af.getTitle() });
270         }
271         else
272         {
273           // use selected region to partition alignment
274           _input = new AlignmentView(av.getAlignment(),
275                   av.getAlignment().getHiddenColumns(),
276                   av.getSelectionGroup(), av.hasHiddenColumns(), false,
277                   true);
278         }
279         viewTitle = MessageManager.formatMessage(
280                 "label.select_unselect_visible_regions_from", new String[]
281                 { (av.hasHiddenColumns()
282                         ? MessageManager.getString("label.visible")
283                         : ""),
284                     af.getTitle() });
285       }
286       else
287       {
288         // just take selected region intersection
289         _input = new AlignmentView(av.getAlignment(),
290                 av.getAlignment().getHiddenColumns(),
291                 av.getSelectionGroup(), av.hasHiddenColumns(), true, true);
292         viewTitle = MessageManager.formatMessage(
293                 "label.select_visible_region_of", new String[]
294                 { (av.hasHiddenColumns()
295                         ? MessageManager.getString("label.visible")
296                         : ""),
297                     af.getTitle() });
298       }
299     }
300     else
301     {
302       // standard alignment view without selection present
303       _input = new AlignmentView(av.getAlignment(),
304               av.getAlignment().getHiddenColumns(), null,
305               av.hasHiddenColumns(), false, true);
306       viewTitle = ""
307               + (av.hasHiddenColumns()
308                       ? (new StringBuffer(" ")
309                               .append(MessageManager
310                                       .getString("label.visible_region_of"))
311                               .toString())
312                       : "")
313               + af.getTitle();
314     }
315
316     RestJobThread jobsthread = new RestJobThread(this);
317
318     if (jobsthread.isValid())
319     {
320       setWebserviceInfo(headless);
321       if (!headless)
322       {
323         wsInfo.setthisService(this);
324         jobsthread.setWebServiceInfo(wsInfo);
325       }
326       jobsthread.start();
327     }
328     else
329     {
330       // TODO: try to tell the user why the job couldn't be started.
331       JvOptionPane.showMessageDialog(Desktop.desktop,
332               (jobsthread.hasWarnings() ? jobsthread.getWarnings()
333                       : MessageManager.getString(
334                               "label.job_couldnt_be_started_check_input")),
335               MessageManager
336                       .getString("label.unable_start_web_service_analysis"),
337               JvOptionPane.WARNING_MESSAGE);
338     }
339   }
340
341   public AlignmentPanel recoverAlignPanelForView()
342   {
343     AlignmentPanel[] aps = Desktop
344             .getAlignmentPanels(av.getSequenceSetId());
345     for (AlignmentPanel alp : aps)
346     {
347       if (alp.av == av)
348       {
349         return alp;
350       }
351     }
352     return null;
353   }
354
355   public boolean isShowResultsInNewView()
356   {
357     // TODO make this a property of the service
358     return true;
359   }
360
361   protected static Vector<String> services = null;
362
363   public static final String RSBS_SERVICES = "RSBS_SERVICES";
364
365   public static RestClient[] getRestClients()
366   {
367     if (services == null)
368     {
369       services = new Vector<>();
370       try
371       {
372         for (RestServiceDescription descr : RestServiceDescription
373                 .parseDescriptions(jalview.bin.Cache.getDefault(
374                         RSBS_SERVICES,
375                         ShmrRestClient.makeShmmrRestClient().service.toString())))
376         {
377           services.add(descr.toString());
378         }
379       } catch (Exception ex)
380       {
381         System.err.println(
382                 "Serious - RSBS descriptions in user preferences are corrupt!");
383         ex.printStackTrace();
384       }
385
386     }
387     RestClient[] lst = new RestClient[services.size()];
388     int i = 0;
389     for (String svc : services)
390     {
391       lst[i++] = new RestClient(new RestServiceDescription(svc));
392     }
393     return lst;
394   }
395
396   public String getAction()
397   {
398     return service.details.getAction();
399   }
400
401   public RestServiceDescription getRestDescription()
402   {
403     return service;
404   }
405
406   public static Vector<String> getRsbsDescriptions()
407   {
408     Vector<String> rsbsDescrs = new Vector<>();
409     for (RestClient rsbs : getRestClients())
410     {
411       rsbsDescrs.add(rsbs.getRestDescription().toString());
412     }
413     return rsbsDescrs;
414   }
415
416   public static void setRsbsServices(Vector<String> rsbsUrls)
417   {
418     if (rsbsUrls != null)
419     {
420       // TODO: consider validating services ?
421       services = new Vector<>(rsbsUrls);
422       StringBuffer sprop = new StringBuffer();
423       for (String s : services)
424       {
425         sprop.append(s);
426       }
427       Cache.setProperty(RSBS_SERVICES, sprop.toString());
428     }
429     else
430     {
431       Cache.removeProperty(RSBS_SERVICES);
432     }
433   }
434
435 }