bd8e43ef44bd99c2017f688f538a5976fa0ffcbd
[jalview.git] / src / jalview / gui / WsParamSetManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.io.File;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.util.ArrayList;
27 import java.util.Hashtable;
28 import java.util.List;
29 import java.util.StringTokenizer;
30
31 import javax.swing.JOptionPane;
32
33 import jalview.bin.Cache;
34 import jalview.io.JalviewFileChooser;
35 import jalview.ws.params.ParamDatastoreI;
36 import jalview.ws.params.ParamManager;
37 import jalview.ws.params.WsParamSetI;
38
39 /**
40  * store and retrieve web service parameter sets.
41  * 
42  * @author JimP
43  * 
44  */
45 public class WsParamSetManager implements ParamManager
46 {
47   Hashtable<String, ParamDatastoreI> paramparsers = new Hashtable<String, ParamDatastoreI>();
48
49   @Override
50   public WsParamSetI[] getParameterSet(String name, String serviceUrl,
51           boolean modifiable, boolean unmodifiable)
52   {
53     String files = Cache.getProperty("WS_PARAM_FILES");
54     if (files == null)
55     {
56       return null;
57     }
58     StringTokenizer st = new StringTokenizer(files, "|");
59     String pfile = null;
60     ArrayList<WsParamSetI> params = new ArrayList<WsParamSetI>();
61     while (st.hasMoreTokens())
62     {
63       pfile = st.nextToken();
64       try
65       {
66         WsParamSetI[] pset = parseParamFile(pfile);
67         for (WsParamSetI p : pset)
68         {
69           boolean add = false;
70           if (serviceUrl != null)
71           {
72             for (String url : p.getApplicableUrls())
73             {
74               if (url.equals(serviceUrl))
75               {
76                 add = true;
77               }
78             }
79           }
80           else
81           {
82             add = true;
83           }
84           add &= (modifiable == p.isModifiable() || unmodifiable == !p
85                   .isModifiable());
86           add &= name == null || p.getName().equals(name);
87
88           if (add)
89           {
90
91             params.add(p);
92           }
93
94         }
95       } catch (IOException e)
96       {
97         Cache.log
98                 .info("Failed to parse parameter file "
99                         + pfile
100                         + " (Check that all JALVIEW_WSPARAMFILES entries are valid!)",
101                         e);
102       }
103     }
104     return params.toArray(new WsParamSetI[0]);
105   }
106
107   private WsParamSetI[] parseParamFile(String filename) throws IOException
108   {
109     List<WsParamSetI> psets = new ArrayList<WsParamSetI>();
110     InputStreamReader is = new InputStreamReader(
111             new java.io.FileInputStream(new File(filename)), "UTF-8");
112
113     jalview.schemabinding.version2.WebServiceParameterSet wspset = new jalview.schemabinding.version2.WebServiceParameterSet();
114
115     org.exolab.castor.xml.Unmarshaller unmar = new org.exolab.castor.xml.Unmarshaller(
116             wspset);
117     unmar.setWhitespacePreserve(true);
118     try
119     {
120       wspset = (jalview.schemabinding.version2.WebServiceParameterSet) unmar
121               .unmarshal(is);
122     } catch (Exception ex)
123     {
124       throw new IOException(ex);
125     }
126     if (wspset != null && wspset.getParameters().length() > 0)
127     {
128       for (String url : wspset.getServiceURL())
129       {
130         ParamDatastoreI parser = paramparsers.get(url);
131         if (parser != null)
132         {
133           WsParamSetI pset = parser.parseServiceParameterFile(
134                   wspset.getName(), wspset.getDescription(),
135                   wspset.getServiceURL(), wspset.getParameters());
136           if (pset != null)
137           {
138             pset.setSourceFile(filename);
139             psets.add(pset);
140             break;
141           }
142         }
143       }
144     }
145
146     return psets.toArray(new WsParamSetI[0]);
147   }
148
149   @Override
150   public void storeParameterSet(WsParamSetI parameterSet)
151   {
152     String filename = parameterSet.getSourceFile();
153     File outfile = null;
154     try
155     {
156       if (filename != null && !((outfile = new File(filename)).canWrite()))
157       {
158         Cache.log.info("Can't write to " + filename
159                 + " - Prompting for new file to write to.");
160         filename = null;
161       }
162     } catch (Exception e)
163     {
164       filename = null;
165     }
166
167     ParamDatastoreI parser = null;
168     for (String urls : parameterSet.getApplicableUrls())
169     {
170       if (parser == null)
171       {
172         parser = paramparsers.get(urls);
173       }
174     }
175     if (parser == null)
176     {
177       throw new Error(
178               "Implementation error: Can't find a marshaller for the parameter set");
179     }
180     if (filename == null)
181     {
182       JalviewFileChooser chooser = new JalviewFileChooser(
183               jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
184               { "wsparams" }, new String[]
185               { "Web Service Parameter File" },
186               "Web Service Parameter File");
187       chooser.setFileView(new jalview.io.JalviewFileView());
188       chooser.setDialogTitle("Choose a filename for this parameter file");
189       chooser.setToolTipText("Save");
190       int value = chooser.showSaveDialog(Desktop.instance);
191       if (value == JalviewFileChooser.APPROVE_OPTION)
192       {
193         outfile = chooser.getSelectedFile();
194         jalview.bin.Cache
195                 .setProperty("LAST_DIRECTORY", outfile.getParent());
196         filename = outfile.getAbsolutePath();
197         if (!filename.endsWith(".wsparams"))
198         {
199           filename = filename.concat(".wsparams");
200           outfile = new File(filename);
201         }
202       }
203     }
204     if (outfile != null)
205     {
206       String paramFiles = jalview.bin.Cache.getDefault("WS_PARAM_FILES",
207               filename);
208       if (paramFiles.indexOf(filename) == -1)
209       {
210         if (paramFiles.length() > 0)
211         {
212           paramFiles = paramFiles.concat("|");
213         }
214         paramFiles = paramFiles.concat(filename);
215       }
216       jalview.bin.Cache.setProperty("WS_PARAM_FILES", paramFiles);
217
218       jalview.schemabinding.version2.WebServiceParameterSet paramxml = new jalview.schemabinding.version2.WebServiceParameterSet();
219
220       paramxml.setName(parameterSet.getName());
221       paramxml.setDescription(parameterSet.getDescription());
222       paramxml.setServiceURL(parameterSet.getApplicableUrls().clone());
223       paramxml.setVersion("1.0");
224       try
225       {
226         paramxml.setParameters(parser
227                 .generateServiceParameterFile(parameterSet));
228         PrintWriter out = new PrintWriter(new OutputStreamWriter(
229                 new FileOutputStream(outfile), "UTF-8"));
230         paramxml.marshal(out);
231         out.close();
232         parameterSet.setSourceFile(filename);
233       } catch (Exception e)
234       {
235         Cache.log.error("Couldn't write parameter file to " + outfile, e);
236       }
237     }
238   }
239
240   /*
241    * 
242    * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
243    * .getProperty("LAST_DIRECTORY"), new String[] { "jc" }, new String[] {
244    * "Jalview User Colours" }, "Jalview User Colours"); chooser.setFileView(new
245    * jalview.io.JalviewFileView());
246    * chooser.setDialogTitle("Load colour scheme");
247    * chooser.setToolTipText("Load");
248    * 
249    * int value = chooser.showOpenDialog(this);
250    * 
251    * if (value == JalviewFileChooser.APPROVE_OPTION) { File choice =
252    * chooser.getSelectedFile(); jalview.bin.Cache.setProperty("LAST_DIRECTORY",
253    * choice.getParent()); String defaultColours = jalview.bin.Cache.getDefault(
254    * "USER_DEFINED_COLOURS", choice.getPath()); if
255    * (defaultColours.indexOf(choice.getPath()) == -1) { defaultColours =
256    * defaultColours.concat("|") .concat(choice.getPath()); } (non-Javadoc)
257    * 
258    * @see
259    * jalview.ws.params.ParamManager#deleteParameterSet(jalview.ws.params.WsParamSetI
260    * )
261    */
262   @Override
263   public void deleteParameterSet(WsParamSetI parameterSet)
264   {
265     String filename = parameterSet.getSourceFile();
266     if (filename == null || filename.trim().length() < 1)
267     {
268       return;
269     }
270     String paramFiles = jalview.bin.Cache.getDefault("WS_PARAM_FILES", "");
271     if (paramFiles.indexOf(filename) > -1)
272     {
273       String nparamFiles = new String();
274       StringTokenizer st = new StringTokenizer(paramFiles, "|");
275       while (st.hasMoreElements())
276       {
277         String fl = st.nextToken();
278         if (!fl.equals(filename))
279         {
280           nparamFiles = nparamFiles.concat("|").concat(fl);
281         }
282       }
283       jalview.bin.Cache.setProperty("WS_PARAM_FILES", nparamFiles);
284     }
285
286     try
287     {
288       File pfile = new File(filename);
289       if (pfile.exists() && pfile.canWrite())
290       {
291         if (JOptionPane.showConfirmDialog(Desktop.instance,
292                 "Delete the preset's file, too ?", "Delete User Preset ?",
293                 JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)
294         {
295           pfile.delete();
296         }
297       }
298     } catch (Exception e)
299     {
300       Cache.log
301               .error("Exception when trying to delete webservice user preset: ",
302                       e);
303     }
304   }
305
306   @Override
307   public void registerParser(String hosturl, ParamDatastoreI paramdataStore)
308   {
309     paramparsers.put(hosturl, paramdataStore);
310   }
311
312 }