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