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