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