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