Unify copyright file headers, update years to include 2011.
[jSite.git] / src / de / todesbaum / jsite / main / 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                                                         fileOption.setContainer(fileOptionNode.getNode("container").getValue());
355                                                         if (fileOptionNode.getNode("replace-edition") != null) {
356                                                                 fileOption.setReplaceEdition(Boolean.parseBoolean(fileOptionNode.getNode("replace-edition").getValue()));
357                                                                 fileOption.setEditionRange(Integer.parseInt(fileOptionNode.getNode("edition-range").getValue()));
358                                                         }
359                                                         fileOptions.put(filename, fileOption);
360                                                 }
361                                         }
362                                         project.setFileOptions(fileOptions);
363                                 } catch (NumberFormatException nfe1) {
364                                         nfe1.printStackTrace();
365                                 }
366                         }
367                 }
368                 return projects.toArray(new Project[projects.size()]);
369         }
370
371         /**
372          * Sets the list of all projects.
373          *
374          * @param projects
375          *            The list of all projects
376          */
377         public void setProjects(Project[] projects) {
378                 SimpleXML projectsNode = new SimpleXML("project-list");
379                 for (Project project : projects) {
380                         SimpleXML projectNode = projectsNode.append("project");
381                         projectNode.append("edition", String.valueOf(project.getEdition()));
382                         projectNode.append("description", project.getDescription());
383                         projectNode.append("index-file", project.getIndexFile());
384                         projectNode.append("last-insertion-time", String.valueOf(project.getLastInsertionTime()));
385                         projectNode.append("local-path", project.getLocalPath());
386                         projectNode.append("name", project.getName());
387                         projectNode.append("path", project.getPath());
388                         projectNode.append("insert-uri", project.getInsertURI());
389                         projectNode.append("request-uri", project.getRequestURI());
390                         projectNode.append("ignore-hidden-files", String.valueOf(project.isIgnoreHiddenFiles()));
391                         SimpleXML fileOptionsNode = projectNode.append("file-options");
392                         Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
393                         while (entries.hasNext()) {
394                                 Entry<String, FileOption> entry = entries.next();
395                                 FileOption fileOption = entry.getValue();
396                                 if (fileOption.isCustom()) {
397                                         SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
398                                         fileOptionNode.append("filename", entry.getKey());
399                                         fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
400                                         fileOptionNode.append("insert-redirect", String.valueOf(fileOption.isInsertRedirect()));
401                                         fileOptionNode.append("custom-key", fileOption.getCustomKey());
402                                         fileOptionNode.append("changed-name", fileOption.getChangedName());
403                                         fileOptionNode.append("mime-type", fileOption.getMimeType());
404                                         fileOptionNode.append("container", fileOption.getContainer());
405                                         fileOptionNode.append("replace-edition", String.valueOf(fileOption.getReplaceEdition()));
406                                         fileOptionNode.append("edition-range", String.valueOf(fileOption.getEditionRange()));
407                                 }
408                         }
409                 }
410                 rootNode.replace(projectsNode);
411         }
412
413         /**
414          * Returns the stored locale.
415          *
416          * @return The stored locale
417          */
418         public Locale getLocale() {
419                 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
420                 String country = getNodeValue(new String[] { "i18n", "country" }, null);
421                 if (country != null) {
422                         return new Locale(language, country);
423                 }
424                 return new Locale(language);
425         }
426
427         /**
428          * Sets the locale to store.
429          *
430          * @param locale
431          *            The locale to store
432          */
433         public void setLocale(Locale locale) {
434                 SimpleXML i18nNode = new SimpleXML("i18n");
435                 if (locale.getCountry().length() != 0) {
436                         i18nNode.append("country", locale.getCountry());
437                 }
438                 i18nNode.append("language", locale.getLanguage());
439                 rootNode.replace(i18nNode);
440                 return;
441         }
442
443         /**
444          * Returns a list of configured nodes.
445          *
446          * @return The list of the configured nodes
447          */
448         public Node[] getNodes() {
449                 SimpleXML nodesNode = rootNode.getNode("nodes");
450                 if (nodesNode == null) {
451                         String hostname = getNodeAddress();
452                         int port = getNodePort();
453                         if (hostname == null) {
454                                 hostname = "127.0.0.1";
455                                 port = 9481;
456                         }
457                         return new Node[] { new Node(hostname, port, "Node") };
458                 }
459                 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
460                 Node[] returnNodes = new Node[nodeNodes.length];
461                 int nodeIndex = 0;
462                 for (SimpleXML nodeNode : nodeNodes) {
463                         String name = nodeNode.getNode("name").getValue();
464                         String hostname = nodeNode.getNode("hostname").getValue();
465                         int port = Integer.parseInt(nodeNode.getNode("port").getValue());
466                         Node node = new Node(hostname, port, name);
467                         returnNodes[nodeIndex++] = node;
468                 }
469                 return returnNodes;
470         }
471
472         /**
473          * Sets the list of configured nodes.
474          *
475          * @param nodes
476          *            The list of configured nodes
477          */
478         public void setNodes(Node[] nodes) {
479                 SimpleXML nodesNode = new SimpleXML("nodes");
480                 for (Node node : nodes) {
481                         SimpleXML nodeNode = nodesNode.append("node");
482                         nodeNode.append("name", node.getName());
483                         nodeNode.append("hostname", node.getHostname());
484                         nodeNode.append("port", String.valueOf(node.getPort()));
485                 }
486                 rootNode.replace(nodesNode);
487                 rootNode.remove("node-address");
488                 rootNode.remove("node-port");
489         }
490
491         /**
492          * Sets the selected node.
493          *
494          * @param selectedNode
495          *            The selected node
496          */
497         public void setSelectedNode(Node selectedNode) {
498                 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
499                 selectedNodeNode.append("name", selectedNode.getName());
500                 selectedNodeNode.append("hostname", selectedNode.getHostname());
501                 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
502                 rootNode.replace(selectedNodeNode);
503         }
504
505         /**
506          * Returns the selected node.
507          *
508          * @return The selected node
509          */
510         public Node getSelectedNode() {
511                 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
512                 if (selectedNodeNode == null) {
513                         String hostname = getNodeAddress();
514                         int port = getNodePort();
515                         if (hostname == null) {
516                                 hostname = "127.0.0.1";
517                                 port = 9481;
518                         }
519                         return new Node(hostname, port, "Node");
520                 }
521                 String name = selectedNodeNode.getNode("name").getValue();
522                 String hostname = selectedNodeNode.getNode("hostname").getValue();
523                 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
524                 return new Node(hostname, port, name);
525         }
526
527         /**
528          * Returns the temp directory to use.
529          *
530          * @return The temp directoy, or {@code null} to use the default temp
531          *         directory
532          */
533         public String getTempDirectory() {
534                 return getNodeValue(new String[] { "temp-directory" }, null);
535         }
536
537         /**
538          * Sets the temp directory to use.
539          *
540          * @param tempDirectory
541          *            The temp directory to use, or {@code null} to use the default
542          *            temp directory
543          */
544         public void setTempDirectory(String tempDirectory) {
545                 if (tempDirectory != null) {
546                         SimpleXML tempDirectoryNode = new SimpleXML("temp-directory");
547                         tempDirectoryNode.setValue(tempDirectory);
548                         rootNode.replace(tempDirectoryNode);
549                 } else {
550                         rootNode.remove("temp-directory");
551                 }
552         }
553
554 }