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