JAL-1950 structuring methods and note on parsing flat-files
[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.WebserviceInfo;
30 import jalview.util.MessageManager;
31 import jalview.ws.WSClient;
32 import jalview.ws.WSClientI;
33 import jalview.ws.WSMenuEntryProviderI;
34 import jalview.ws.rest.clientdefs.ShmrRestClient;
35
36 import java.awt.event.ActionEvent;
37 import java.awt.event.ActionListener;
38 import java.util.Vector;
39
40 import javax.swing.JMenu;
41 import javax.swing.JMenuItem;
42 import javax.swing.JOptionPane;
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 implements WSClientI,
51         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.formatMessage(
100             "label.webservice_job_title", new String[] {
101                 service.details.Action, service.details.Name });
102     WebServiceName = service.details.Name;
103     WebServiceReference = "No reference - go to url for more info";
104     if (service.details.description != null)
105     {
106       WebServiceReference = service.details.description;
107     }
108     if (!headless)
109     {
110       wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceName + "\n"
111               + 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.Name);
144     submit.setToolTipText(MessageManager.formatMessage(
145             "label.rest_client_submit", new String[] {
146                 service.details.Action, service.details.Name }));
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.getColumnSelection(), av.getSelectionGroup(),
262                   av.hasHiddenColumns(), true, true);
263           viewTitle = MessageManager.formatMessage(
264                   "label.select_visible_region_of",
265                   new String[] {
266                       (av.hasHiddenColumns() ? MessageManager
267                               .getString("label.visible") : ""),
268                       af.getTitle() });
269         }
270         else
271         {
272           // use selected region to partition alignment
273           _input = new AlignmentView(av.getAlignment(),
274                   av.getColumnSelection(), av.getSelectionGroup(),
275                   av.hasHiddenColumns(), false, true);
276         }
277         viewTitle = MessageManager.formatMessage(
278                 "label.select_unselect_visible_regions_from",
279                 new String[] {
280                     (av.hasHiddenColumns() ? MessageManager
281                             .getString("label.visible") : ""),
282                     af.getTitle() });
283       }
284       else
285       {
286         // just take selected region intersection
287         _input = new AlignmentView(av.getAlignment(),
288                 av.getColumnSelection(), av.getSelectionGroup(),
289                 av.hasHiddenColumns(), true, true);
290         viewTitle = MessageManager.formatMessage(
291                 "label.select_visible_region_of",
292                 new String[] {
293                     (av.hasHiddenColumns() ? MessageManager
294                             .getString("label.visible") : ""),
295                     af.getTitle() });
296       }
297     }
298     else
299     {
300       // standard alignment view without selection present
301       _input = new AlignmentView(av.getAlignment(),
302               av.getColumnSelection(), null, av.hasHiddenColumns(), false,
303               true);
304       viewTitle = ""
305               + (av.hasHiddenColumns() ? (new StringBuffer(" ")
306                       .append(MessageManager
307                               .getString("label.visible_region_of"))
308                       .toString()) : "") + af.getTitle();
309     }
310
311     RestJobThread jobsthread = new RestJobThread(this);
312
313     if (jobsthread.isValid())
314     {
315       setWebserviceInfo(headless);
316       if (!headless)
317       {
318         wsInfo.setthisService(this);
319         jobsthread.setWebServiceInfo(wsInfo);
320       }
321       jobsthread.start();
322     }
323     else
324     {
325       // TODO: try to tell the user why the job couldn't be started.
326       JOptionPane
327               .showMessageDialog(
328                       Desktop.desktop,
329                       (jobsthread.hasWarnings() ? jobsthread.getWarnings()
330                               : MessageManager
331                                       .getString("label.job_couldnt_be_started_check_input")),
332                       MessageManager
333                               .getString("label.unable_start_web_service_analysis"),
334                       JOptionPane.WARNING_MESSAGE);
335     }
336   }
337
338   public AlignmentPanel recoverAlignPanelForView()
339   {
340     AlignmentPanel[] aps = Desktop
341             .getAlignmentPanels(av.getSequenceSetId());
342     for (AlignmentPanel alp : aps)
343     {
344       if (alp.av == av)
345       {
346         return alp;
347       }
348     }
349     return null;
350   }
351
352   public boolean isShowResultsInNewView()
353   {
354     // TODO make this a property of the service
355     return true;
356   }
357
358   protected static Vector<String> services = null;
359
360   public static final String RSBS_SERVICES = "RSBS_SERVICES";
361
362   public static RestClient[] getRestClients()
363   {
364     if (services == null)
365     {
366       services = new Vector<String>();
367       try
368       {
369         for (RestServiceDescription descr : RestServiceDescription
370                 .parseDescriptions(jalview.bin.Cache.getDefault(
371                         RSBS_SERVICES,
372                         ShmrRestClient.makeShmmrRestClient().service.toString())))
373         {
374           services.add(descr.toString());
375         }
376       } catch (Exception ex)
377       {
378         System.err
379                 .println("Serious - RSBS descriptions in user preferences are corrupt!");
380         ex.printStackTrace();
381       }
382
383     }
384     RestClient[] lst = new RestClient[services.size()];
385     int i = 0;
386     for (String svc : services)
387     {
388       lst[i++] = new RestClient(new RestServiceDescription(svc));
389     }
390     return lst;
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     if (rsbsUrls != null)
416     {
417       // TODO: consider validating services ?
418       services = new Vector<String>(rsbsUrls);
419       StringBuffer sprop = new StringBuffer();
420       for (String s : services)
421       {
422         sprop.append(s);
423       }
424       Cache.setProperty(RSBS_SERVICES, sprop.toString());
425     }
426     else
427     {
428       Cache.removeProperty(RSBS_SERVICES);
429     }
430   }
431
432 }