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