6a12a65865ee20c6327a91f7b4f1dcbf5bb6b2ec
[jSite.git] / Configuration.java
1 /*
2  * jSite - Configuration.java - Copyright © 2006–2011 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package de.todesbaum.jsite.main;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import de.todesbaum.jsite.application.FileOption;
39 import de.todesbaum.jsite.application.Node;
40 import de.todesbaum.jsite.application.Project;
41 import de.todesbaum.jsite.main.ConfigurationLocator.ConfigurationLocation;
42 import de.todesbaum.util.io.Closer;
43 import de.todesbaum.util.io.StreamCopier;
44 import de.todesbaum.util.xml.SimpleXML;
45 import de.todesbaum.util.xml.XML;
46
47 /**
48  * The configuration.
49  *
50  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
51  */
52 public class Configuration {
53
54         /** The root node of the configuration. */
55         private SimpleXML rootNode;
56
57         /** The configuration locator. */
58         private final ConfigurationLocator configurationLocator;
59
60         /** Where the configuration resides. */
61         private ConfigurationLocation configurationLocation;
62
63         /**
64          * Creates a new configuration that is read from the given file.
65          *
66          * @param configurationLocator
67          *            The configuration locator
68          * @param configurationLocation
69          *            The configuration directory
70          */
71         public Configuration(ConfigurationLocator configurationLocator, ConfigurationLocation configurationLocation) {
72                 this.configurationLocator = configurationLocator;
73                 this.configurationLocation = configurationLocation;
74                 readConfiguration(configurationLocator.getFile(configurationLocation));
75         }
76
77         //
78         // ACCESSORS
79         //
80
81         /**
82          * Returns the configuration locator.
83          *
84          * @return The configuration locator
85          */
86         public ConfigurationLocator getConfigurationLocator() {
87                 return configurationLocator;
88         }
89
90         /**
91          * Returns the location the configuration will be written to when calling
92          * {@link #save()}.
93          *
94          * @return The location the configuration will be written to
95          */
96         public ConfigurationLocation getConfigurationDirectory() {
97                 return configurationLocation;
98         }
99
100         /**
101          * Sets the location the configuration will be written to when calling
102          * {@link #save()}.
103          *
104          * @param configurationLocation
105          *            The location to write the configuration to
106          */
107         public void setConfigurationLocation(ConfigurationLocation configurationLocation) {
108                 this.configurationLocation = configurationLocation;
109         }
110
111         /**
112          * Reads the configuration from the file.
113          *
114          * @param filename
115          *            The name of the file to read the configuration from
116          */
117         private void readConfiguration(String filename) {
118                 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Reading configuration from: " + filename);
119                 if (filename != null) {
120                         File configurationFile = new File(filename);
121                         if (configurationFile.exists()) {
122                                 ByteArrayOutputStream fileByteOutputStream = null;
123                                 FileInputStream fileInputStream = null;
124                                 try {
125                                         fileByteOutputStream = new ByteArrayOutputStream();
126                                         fileInputStream = new FileInputStream(configurationFile);
127                                         StreamCopier.copy(fileInputStream, fileByteOutputStream, configurationFile.length());
128                                         fileByteOutputStream.close();
129                                         byte[] fileBytes = fileByteOutputStream.toByteArray();
130                                         rootNode = SimpleXML.fromDocument(XML.transformToDocument(fileBytes));
131                                         return;
132                                 } catch (FileNotFoundException e) {
133                                         /* ignore. */
134                                 } catch (IOException e) {
135                                         /* ignore. */
136                                 } finally {
137                                         Closer.close(fileInputStream);
138                                         Closer.close(fileByteOutputStream);
139                                 }
140                         }
141                 }
142                 rootNode = new SimpleXML("configuration");
143         }
144
145         /**
146          * Saves the configuration.
147          *
148          * @return <code>true</code> if the configuration could be saved,
149          *         <code>false</code> otherwise
150          */
151         public boolean save() {
152                 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Trying to save configuration to: " + configurationLocation);
153                 File configurationFile = new File(configurationLocator.getFile(configurationLocation));
154                 if (!configurationFile.exists()) {
155                         File configurationFilePath = configurationFile.getAbsoluteFile().getParentFile();
156                         if (!configurationFilePath.exists() && !configurationFilePath.mkdirs()) {
157                                 return false;
158                         }
159                 }
160                 FileOutputStream fileOutputStream = null;
161                 ByteArrayInputStream configurationInputStream = null;
162                 try {
163                         byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
164                         configurationInputStream = new ByteArrayInputStream(configurationBytes);
165                         fileOutputStream = new FileOutputStream(configurationFile);
166                         StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
167                         return true;
168                 } catch (IOException ioe1) {
169                         /* ignore. */
170                 } finally {
171                         Closer.close(configurationInputStream);
172                         Closer.close(fileOutputStream);
173                 }
174                 return false;
175         }
176
177         /**
178          * Returns the value of a node.
179          *
180          * @param nodeNames
181          *            The name of all nodes in the chain
182          * @param defaultValue
183          *            The default value to return if the node could not be found
184          * @return The value of the node, or the default value if the node could not
185          *         be found
186          */
187         private String getNodeValue(String[] nodeNames, String defaultValue) {
188                 SimpleXML node = rootNode;
189                 int nodeIndex = 0;
190                 while ((node != null) && (nodeIndex < nodeNames.length)) {
191                         node = node.getNode(nodeNames[nodeIndex++]);
192                 }
193                 if (node == null) {
194                         return defaultValue;
195                 }
196                 return node.getValue();
197         }
198
199         /**
200          * Returns the integer value of a node.
201          *
202          * @param nodeNames
203          *            The names of all nodes in the chain
204          * @param defaultValue
205          *            The default value to return if the node can not be found
206          * @return The parsed integer value, or the default value if the node can
207          *         not be found or the value can not be parsed into an integer
208          */
209         private int getNodeIntValue(String[] nodeNames, int defaultValue) {
210                 try {
211                         return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
212                 } catch (NumberFormatException nfe1) {
213                         /* ignore. */
214                 }
215                 return defaultValue;
216         }
217
218         /**
219          * Returns the boolean value of a node.
220          *
221          * @param nodeNames
222          *            The names of all nodes in the chain
223          * @param defaultValue
224          *            The default value to return if the node can not be found
225          * @return The parsed boolean value, or the default value if the node can
226          *         not be found
227          */
228         private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
229                 String nodeValue = getNodeValue(nodeNames, null);
230                 if (nodeValue == null) {
231                         return defaultValue;
232                 }
233                 return Boolean.parseBoolean(nodeValue);
234         }
235
236         /**
237          * Returns the hostname of the node.
238          *
239          * @return The hostname of the node
240          * @deprecated Use {@link #getSelectedNode()} instead
241          */
242         @Deprecated
243         public String getNodeAddress() {
244                 return getNodeValue(new String[] { "node-address" }, "localhost");
245         }
246
247         /**
248          * Sets the hostname of the node.
249          *
250          * @param nodeAddress
251          *            The hostname of the node
252          * @deprecated Use {@link #setSelectedNode(Node)} instead
253          */
254         @Deprecated
255         public void setNodeAddress(String nodeAddress) {
256                 rootNode.replace("node-address", nodeAddress);
257         }
258
259         /**
260          * The port number of the node
261          *
262          * @return The port number of the node
263          * @deprecated Use {@link #getSelectedNode()} instead.
264          */
265         @Deprecated
266         public int getNodePort() {
267                 return getNodeIntValue(new String[] { "node-port" }, 9481);
268         }
269
270         /**
271          * Sets the port number of the node.
272          *
273          * @param nodePort
274          *            The port number of the node
275          * @deprecated Use {@link #setSelectedNode(Node)} instead
276          */
277         @Deprecated
278         public void setNodePort(int nodePort) {
279                 rootNode.replace("node-port", String.valueOf(nodePort));
280         }
281
282         /**
283          * Returns whether the node configuration page should be skipped on startup.
284          *
285          * @return <code>true</code> to skip the node configuration page on startup,
286          *         <code>false</code> to show it
287          */
288         public boolean isSkipNodePage() {
289                 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
290         }
291
292         /**
293          * Sets whether the node configuration page should be skipped on startup.
294          *
295          * @param skipNodePage
296          *            <code>true</code> to skip the node configuration page on
297          *            startup, <code>false</code> to show it
298          */
299         public void setSkipNodePage(boolean skipNodePage) {
300                 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
301         }
302
303         /**
304          * Returns all configured projects.
305          *
306          * @return A list of all projects
307          */
308         public Project[] getProjects() {
309                 List<Project> projects = new ArrayList<Project>();
310                 SimpleXML projectsNode = rootNode.getNode("project-list");
311                 if (projectsNode != null) {
312                         SimpleXML[] projectNodes = projectsNode.getNodes("project");
313                         for (SimpleXML projectNode : projectNodes) {
314                                 try {
315                                         Project project = new Project();
316                                         projects.add(project);
317                                         project.setDescription(projectNode.getNode("description").getValue(""));
318                                         String indexFile = projectNode.getNode("index-file").getValue("");
319                                         if (indexFile.indexOf('/') > -1) {
320                                                 indexFile = "";
321                                         }
322                                         project.setIndexFile(indexFile);
323                                         project.setLastInsertionTime(Long.parseLong(projectNode.getNode("last-insertion-time").getValue("0")));
324                                         project.setLocalPath(projectNode.getNode("local-path").getValue(""));
325                                         project.setName(projectNode.getNode("name").getValue(""));
326                                         project.setPath(projectNode.getNode("path").getValue(""));
327                                         if ((project.getPath() != null) && (project.getPath().indexOf("/") != -1)) {
328                                                 project.setPath(project.getPath().replaceAll("/", ""));
329                                         }
330                                         project.setEdition(Integer.parseInt(projectNode.getNode("edition").getValue("0")));
331                                         project.setInsertURI(projectNode.getNode("insert-uri").getValue(""));
332                                         project.setRequestURI(projectNode.getNode("request-uri").getValue(""));
333                                         if (projectNode.getNode("ignore-hidden-files") != null) {
334                                                 project.setIgnoreHiddenFiles(Boolean.parseBoolean(projectNode.getNode("ignore-hidden-files").getValue("true")));
335                                         } else {
336                                                 project.setIgnoreHiddenFiles(true);
337                                         }
338                                         SimpleXML fileOptionsNode = projectNode.getNode("file-options");
339                                         Map<String, FileOption> fileOptions = new HashMap<String, FileOption>();
340                                         if (fileOptionsNode != null) {
341                                                 SimpleXML[] fileOptionNodes = fileOptionsNode.getNodes("file-option");
342                                                 for (SimpleXML fileOptionNode : fileOptionNodes) {
343                                                         String filename = fileOptionNode.getNode("filename").getValue();
344                                                         FileOption fileOption = project.getFileOption(filename);
345                                                         fileOption.setInsert(Boolean.parseBoolean(fileOptionNode.getNode("insert").getValue()));
346                                                         if (fileOptionNode.getNode("insert-redirect") != null) {
347                                                                 fileOption.setInsertRedirect(Boolean.parseBoolean(fileOptionNode.getNode("insert-redirect").getValue()));
348                                                         }
349                                                         fileOption.setCustomKey(fileOptionNode.getNode("custom-key").getValue(""));
350                                                         if (fileOptionNode.getNode("changed-name") != null) {
351                                                                 fileOption.setChangedName(fileOptionNode.getNode("changed-name").getValue());
352                                                         }
353                                                         fileOption.setMimeType(fileOptionNode.getNode("mime-type").getValue(""));
354                                                         fileOptions.put(filename, fileOption);
355                                                 }
356                                         }
357                                         project.setFileOptions(fileOptions);
358                                 } catch (NumberFormatException nfe1) {
359                                         nfe1.printStackTrace();
360                                 }
361                         }
362                 }
363                 return projects.toArray(new Project[projects.size()]);
364         }
365
366         /**
367          * Sets the list of all projects.
368          *
369          * @param projects
370          *            The list of all projects
371          */
372         public void setProjects(Project[] projects) {
373                 SimpleXML projectsNode = new SimpleXML("project-list");
374                 for (Project project : projects) {
375                         SimpleXML projectNode = projectsNode.append("project");
376                         projectNode.append("edition", String.valueOf(project.getEdition()));
377                         projectNode.append("description", project.getDescription());
378                         projectNode.append("index-file", project.getIndexFile());
379                         projectNode.append("last-insertion-time", String.valueOf(project.getLastInsertionTime()));
380                         projectNode.append("local-path", project.getLocalPath());
381                         projectNode.append("name", project.getName());
382                         projectNode.append("path", project.getPath());
383                         projectNode.append("insert-uri", project.getInsertURI());
384                         projectNode.append("request-uri", project.getRequestURI());
385                         projectNode.append("ignore-hidden-files", String.valueOf(project.isIgnoreHiddenFiles()));
386                         SimpleXML fileOptionsNode = projectNode.append("file-options");
387                         Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
388                         while (entries.hasNext()) {
389                                 Entry<String, FileOption> entry = entries.next();
390                                 FileOption fileOption = entry.getValue();
391                                 if (fileOption.isCustom()) {
392                                         SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
393                                         fileOptionNode.append("filename", entry.getKey());
394                                         fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
395                                         fileOptionNode.append("insert-redirect", String.valueOf(fileOption.isInsertRedirect()));
396                                         fileOptionNode.append("custom-key", fileOption.getCustomKey());
397                                         fileOptionNode.append("changed-name", fileOption.getChangedName());
398                                         fileOptionNode.append("mime-type", fileOption.getMimeType());
399                                 }
400                         }
401                 }
402                 rootNode.replace(projectsNode);
403         }
404
405         /**
406          * Returns the stored locale.
407          *
408          * @return The stored locale
409          */
410         public Locale getLocale() {
411                 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
412                 String country = getNodeValue(new String[] { "i18n", "country" }, null);
413                 if (country != null) {
414                         return new Locale(language, country);
415                 }
416                 return new Locale(language);
417         }
418
419         /**
420          * Sets the locale to store.
421          *
422          * @param locale
423          *            The locale to store
424          */
425         public void setLocale(Locale locale) {
426                 SimpleXML i18nNode = new SimpleXML("i18n");
427                 if (locale.getCountry().length() != 0) {
428                         i18nNode.append("country", locale.getCountry());
429                 }
430                 i18nNode.append("language", locale.getLanguage());
431                 rootNode.replace(i18nNode);
432                 return;
433         }
434
435         /**
436          * Returns a list of configured nodes.
437          *
438          * @return The list of the configured nodes
439          */
440         public Node[] getNodes() {
441                 SimpleXML nodesNode = rootNode.getNode("nodes");
442                 if (nodesNode == null) {
443                         String hostname = getNodeAddress();
444                         int port = getNodePort();
445                         if (hostname == null) {
446                                 hostname = "127.0.0.1";
447                                 port = 9481;
448                         }
449                         return new Node[] { new Node(hostname, port, "Node") };
450                 }
451                 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
452                 Node[] returnNodes = new Node[nodeNodes.length];
453                 int nodeIndex = 0;
454                 for (SimpleXML nodeNode : nodeNodes) {
455                         String name = nodeNode.getNode("name").getValue();
456                         String hostname = nodeNode.getNode("hostname").getValue();
457                         int port = Integer.parseInt(nodeNode.getNode("port").getValue());
458                         Node node = new Node(hostname, port, name);
459                         returnNodes[nodeIndex++] = node;
460                 }
461                 return returnNodes;
462         }
463
464         /**
465          * Sets the list of configured nodes.
466          *
467          * @param nodes
468          *            The list of configured nodes
469          */
470         public void setNodes(Node[] nodes) {
471                 SimpleXML nodesNode = new SimpleXML("nodes");
472                 for (Node node : nodes) {
473                         SimpleXML nodeNode = nodesNode.append("node");
474                         nodeNode.append("name", node.getName());
475                         nodeNode.append("hostname", node.getHostname());
476                         nodeNode.append("port", String.valueOf(node.getPort()));
477                 }
478                 rootNode.replace(nodesNode);
479                 rootNode.remove("node-address");
480                 rootNode.remove("node-port");
481         }
482
483         /**
484          * Sets the selected node.
485          *
486          * @param selectedNode
487          *            The selected node
488          */
489         public void setSelectedNode(Node selectedNode) {
490                 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
491                 selectedNodeNode.append("name", selectedNode.getName());
492                 selectedNodeNode.append("hostname", selectedNode.getHostname());
493                 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
494                 rootNode.replace(selectedNodeNode);
495         }
496
497         /**
498          * Returns the selected node.
499          *
500          * @return The selected node
501          */
502         public Node getSelectedNode() {
503                 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
504                 if (selectedNodeNode == null) {
505                         String hostname = getNodeAddress();
506                         int port = getNodePort();
507                         if (hostname == null) {
508                                 hostname = "127.0.0.1";
509                                 port = 9481;
510                         }
511                         return new Node(hostname, port, "Node");
512                 }
513                 String name = selectedNodeNode.getNode("name").getValue();
514                 String hostname = selectedNodeNode.getNode("hostname").getValue();
515                 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
516                 return new Node(hostname, port, name);
517         }
518
519         /**
520          * Returns the temp directory to use.
521          *
522          * @return The temp directoy, or {@code null} to use the default temp
523          *         directory
524          */
525         public String getTempDirectory() {
526                 return getNodeValue(new String[] { "temp-directory" }, null);
527         }
528
529         /**
530          * Sets the temp directory to use.
531          *
532          * @param tempDirectory
533          *            The temp directory to use, or {@code null} to use the default
534          *            temp directory
535          */
536         public void setTempDirectory(String tempDirectory) {
537                 if (tempDirectory != null) {
538                         SimpleXML tempDirectoryNode = new SimpleXML("temp-directory");
539                         tempDirectoryNode.setValue(tempDirectory);
540                         rootNode.replace(tempDirectoryNode);
541                 } else {
542                         rootNode.remove("temp-directory");
543                 }
544         }
545
546 }