JAL-3949 - refactor logging from jalview.bin.Cache to jalview.bin.Console
[jalview.git] / src / jalview / gui / WsParamSetManager.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.gui;
22
23 import jalview.bin.Cache;
24 import jalview.bin.Console;
25 import jalview.io.JalviewFileChooser;
26 import jalview.io.JalviewFileView;
27 import jalview.util.MessageManager;
28 import jalview.ws.params.ParamDatastoreI;
29 import jalview.ws.params.ParamManager;
30 import jalview.ws.params.WsParamSetI;
31 import jalview.xml.binding.jalview.ObjectFactory;
32 import jalview.xml.binding.jalview.WebServiceParameterSet;
33
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.FileOutputStream;
37 import java.io.IOException;
38 import java.io.InputStreamReader;
39 import java.io.OutputStreamWriter;
40 import java.io.PrintWriter;
41 import java.util.ArrayList;
42 import java.util.Hashtable;
43 import java.util.List;
44 import java.util.StringTokenizer;
45
46 import javax.xml.bind.JAXBContext;
47 import javax.xml.bind.JAXBElement;
48 import javax.xml.bind.Marshaller;
49 import javax.xml.stream.XMLInputFactory;
50 import javax.xml.stream.XMLStreamReader;
51
52 /**
53  * store and retrieve web service parameter sets.
54  * 
55  * @author JimP
56  * 
57  */
58 public class WsParamSetManager implements ParamManager
59 {
60   Hashtable<String, ParamDatastoreI> paramparsers = new Hashtable<>();
61
62   @Override
63   public WsParamSetI[] getParameterSet(String name, String serviceUrl,
64           boolean modifiable, boolean unmodifiable)
65   {
66     String files = Cache.getProperty("WS_PARAM_FILES");
67     if (files == null)
68     {
69       return null;
70     }
71     StringTokenizer st = new StringTokenizer(files, "|");
72     String pfile = null;
73     List<WsParamSetI> params = new ArrayList<>();
74     while (st.hasMoreTokens())
75     {
76       pfile = st.nextToken();
77       try
78       {
79         WsParamSetI[] pset = parseParamFile(pfile);
80         for (WsParamSetI p : pset)
81         {
82           boolean add = false;
83           if (serviceUrl != null)
84           {
85             for (String url : p.getApplicableUrls())
86             {
87               if (url.equals(serviceUrl))
88               {
89                 add = true;
90               }
91             }
92           }
93           else
94           {
95             add = true;
96           }
97           add &= (modifiable == p.isModifiable()
98                   || unmodifiable == !p.isModifiable());
99           add &= name == null || p.getName().equals(name);
100
101           if (add)
102           {
103
104             params.add(p);
105           }
106
107         }
108       } catch (IOException e)
109       {
110         Console.info("Failed to parse parameter file " + pfile
111                 + " (Check that all JALVIEW_WSPARAMFILES entries are valid!)",
112                 e);
113       }
114     }
115     return params.toArray(new WsParamSetI[0]);
116   }
117
118   private WsParamSetI[] parseParamFile(String filename) throws IOException
119   {
120     List<WsParamSetI> psets = new ArrayList<>();
121     InputStreamReader is = new InputStreamReader(
122             new FileInputStream(new File(filename)), "UTF-8");
123
124     WebServiceParameterSet wspset = null;
125     try
126     {
127       JAXBContext jc = JAXBContext
128               .newInstance("jalview.xml.binding.jalview");
129       javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
130       XMLStreamReader streamReader = XMLInputFactory.newInstance()
131               .createXMLStreamReader(is);
132       JAXBElement<WebServiceParameterSet> jbe = um.unmarshal(streamReader,
133               WebServiceParameterSet.class);
134       wspset = jbe.getValue();
135     } catch (Exception ex)
136     {
137       throw new IOException(ex);
138     }
139
140     if (wspset != null && wspset.getParameters().length() > 0)
141     {
142       List<String> urls = wspset.getServiceURL();
143       final String[] urlArray = urls.toArray(new String[urls.size()]);
144
145       for (String url : urls)
146       {
147         ParamDatastoreI parser = paramparsers.get(url);
148         if (parser != null)
149         {
150           WsParamSetI pset = parser.parseServiceParameterFile(
151                   wspset.getName(), wspset.getDescription(),
152                   urlArray, wspset.getParameters());
153           if (pset != null)
154           {
155             pset.setSourceFile(filename);
156             psets.add(pset);
157             break;
158           }
159         }
160       }
161     }
162
163     return psets.toArray(new WsParamSetI[0]);
164   }
165
166   @Override
167   public void storeParameterSet(WsParamSetI parameterSet)
168   {
169     String filename = parameterSet.getSourceFile();
170     File outfile = null;
171     try
172     {
173       if (filename != null && !((outfile = new File(filename)).canWrite()))
174       {
175         Console.warn("Can't write to " + filename
176                 + " - Prompting for new file to write to.");
177         filename = null;
178       }
179     } catch (Exception e)
180     {
181       filename = null;
182     }
183
184     ParamDatastoreI parser = null;
185     for (String urls : parameterSet.getApplicableUrls())
186     {
187       if (parser == null)
188       {
189         parser = paramparsers.get(urls);
190       }
191     }
192     if (parser == null)
193     {
194       throw new Error(MessageManager.getString(
195               "error.implementation_error_cannot_find_marshaller_for_param_set"));
196     }
197     if (filename == null)
198     {
199       // TODO: JAL-3048 webservice - not required for Jalview-JS
200
201       JalviewFileChooser chooser = new JalviewFileChooser("wsparams",
202               "Web Service Parameter File");
203       chooser.setFileView(new JalviewFileView());
204       chooser.setDialogTitle(MessageManager
205               .getString("label.choose_filename_for_param_file"));
206       chooser.setToolTipText(MessageManager.getString("action.save"));
207       int value = chooser.showSaveDialog(Desktop.instance);
208       if (value == JalviewFileChooser.APPROVE_OPTION)
209       {
210         outfile = chooser.getSelectedFile();
211         Cache.setProperty("LAST_DIRECTORY", outfile.getParent());
212         filename = outfile.getAbsolutePath();
213         if (!filename.endsWith(".wsparams"))
214         {
215           filename = filename.concat(".wsparams");
216           outfile = new File(filename);
217         }
218       }
219     }
220     if (outfile != null)
221     {
222       String paramFiles = Cache.getDefault("WS_PARAM_FILES",
223               filename);
224       if (paramFiles.indexOf(filename) == -1)
225       {
226         if (paramFiles.length() > 0)
227         {
228           paramFiles = paramFiles.concat("|");
229         }
230         paramFiles = paramFiles.concat(filename);
231       }
232       Cache.setProperty("WS_PARAM_FILES", paramFiles);
233
234       WebServiceParameterSet paramxml = new WebServiceParameterSet();
235
236       paramxml.setName(parameterSet.getName());
237       paramxml.setDescription(parameterSet.getDescription());
238       for (String url : parameterSet.getApplicableUrls())
239       {
240         paramxml.getServiceURL().add(url);
241       }
242       paramxml.setVersion("1.0");
243       try
244       {
245         paramxml.setParameters(
246                 parser.generateServiceParameterFile(parameterSet));
247         PrintWriter out = new PrintWriter(new OutputStreamWriter(
248                 new FileOutputStream(outfile), "UTF-8"));
249         JAXBContext jaxbContext = JAXBContext
250                 .newInstance(WebServiceParameterSet.class);
251         Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
252         jaxbMarshaller.marshal(
253                 new ObjectFactory().createWebServiceParameterSet(paramxml),
254                 out);
255         out.close();
256         parameterSet.setSourceFile(filename);
257       } catch (Exception e)
258       {
259         Console.error("Couldn't write parameter file to " + outfile, e);
260       }
261     }
262   }
263
264   /*
265    * 
266    * JalviewFileChooser chooser = new JalviewFileChooser(Cache
267    * .getProperty("LAST_DIRECTORY"), new String[] { "jc" }, new String[] {
268    * "Jalview User Colours" }, "Jalview User Colours"); chooser.setFileView(new
269    * jalview.io.JalviewFileView());
270    * chooser.setDialogTitle("Load colour scheme");
271    * chooser.setToolTipText("Load");
272    * 
273    * int value = chooser.showOpenDialog(this);
274    * 
275    * if (value == JalviewFileChooser.APPROVE_OPTION) { File choice =
276    * chooser.getSelectedFile(); Cache.setProperty("LAST_DIRECTORY",
277    * choice.getParent()); String defaultColours = Cache.getDefault(
278    * "USER_DEFINED_COLOURS", choice.getPath()); if
279    * (defaultColours.indexOf(choice.getPath()) == -1) { defaultColours =
280    * defaultColours.concat("|") .concat(choice.getPath()); } (non-Javadoc)
281    * 
282    * @see
283    * jalview.ws.params.ParamManager#deleteParameterSet(jalview.ws.params.WsParamSetI
284    * )
285    */
286   @Override
287   public void deleteParameterSet(WsParamSetI parameterSet)
288   {
289     String filename = parameterSet.getSourceFile();
290     if (filename == null || filename.trim().length() < 1)
291     {
292       return;
293     }
294     String paramFiles = Cache.getDefault("WS_PARAM_FILES", "");
295     if (paramFiles.indexOf(filename) > -1)
296     {
297       String nparamFiles = new String();
298       StringTokenizer st = new StringTokenizer(paramFiles, "|");
299       while (st.hasMoreElements())
300       {
301         String fl = st.nextToken();
302         if (!fl.equals(filename))
303         {
304           nparamFiles = nparamFiles.concat("|").concat(fl);
305         }
306       }
307       Cache.setProperty("WS_PARAM_FILES", nparamFiles);
308     }
309
310     try
311     {
312       File pfile = new File(filename);
313       if (pfile.exists() && pfile.canWrite())
314       {
315         if (JvOptionPane.showConfirmDialog(Desktop.instance,
316                 "Delete the preset's file, too ?", "Delete User Preset ?",
317                 JvOptionPane.OK_CANCEL_OPTION) == JvOptionPane.OK_OPTION)
318         {
319           pfile.delete();
320         }
321       }
322     } catch (Exception e)
323     {
324       Console.error(
325               "Exception when trying to delete webservice user preset: ",
326               e);
327     }
328   }
329
330   @Override
331   public void registerParser(String hosturl, ParamDatastoreI paramdataStore)
332   {
333     paramparsers.put(hosturl, paramdataStore);
334   }
335
336 }