Remove manifest putter selection
[jSite.git] / src / main / java / de / todesbaum / jsite / main / Configuration.java
1 /*
2  * jSite - Configuration.java - Copyright © 2006–2014 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 net.pterodactylus.util.io.Closer;
39 import net.pterodactylus.util.io.StreamCopier;
40 import net.pterodactylus.util.xml.SimpleXML;
41 import net.pterodactylus.util.xml.XML;
42 import de.todesbaum.jsite.application.FileOption;
43 import de.todesbaum.jsite.application.Node;
44 import de.todesbaum.jsite.application.Project;
45 import de.todesbaum.jsite.main.ConfigurationLocator.ConfigurationLocation;
46 import de.todesbaum.util.freenet.fcp2.PriorityClass;
47
48 /**
49  * The configuration.
50  *
51  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
52  */
53 public class Configuration {
54
55         /** The root node of the configuration. */
56         private SimpleXML rootNode;
57
58         /** The configuration locator. */
59         private final ConfigurationLocator configurationLocator;
60
61         /** Where the configuration resides. */
62         private ConfigurationLocation configurationLocation;
63
64         /**
65          * Creates a new configuration that is read from the given file.
66          *
67          * @param configurationLocator
68          *            The configuration locator
69          * @param configurationLocation
70          *            The configuration directory
71          */
72         public Configuration(ConfigurationLocator configurationLocator, ConfigurationLocation configurationLocation) {
73                 this.configurationLocator = configurationLocator;
74                 this.configurationLocation = configurationLocation;
75                 readConfiguration(configurationLocator.getFile(configurationLocation));
76         }
77
78         //
79         // ACCESSORS
80         //
81
82         /**
83          * Returns the configuration locator.
84          *
85          * @return The configuration locator
86          */
87         public ConfigurationLocator getConfigurationLocator() {
88                 return configurationLocator;
89         }
90
91         /**
92          * Returns the location the configuration will be written to when calling
93          * {@link #save()}.
94          *
95          * @return The location the configuration will be written to
96          */
97         public ConfigurationLocation getConfigurationDirectory() {
98                 return configurationLocation;
99         }
100
101         /**
102          * Sets the location the configuration will be written to when calling
103          * {@link #save()}.
104          *
105          * @param configurationLocation
106          *            The location to write the configuration to
107          */
108         public void setConfigurationLocation(ConfigurationLocation configurationLocation) {
109                 this.configurationLocation = configurationLocation;
110         }
111
112         /**
113          * Reads the configuration from the file.
114          *
115          * @param filename
116          *            The name of the file to read the configuration from
117          */
118         private void readConfiguration(String filename) {
119                 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Reading configuration from: " + filename);
120                 if (filename != null) {
121                         File configurationFile = new File(filename);
122                         if (configurationFile.exists()) {
123                                 ByteArrayOutputStream fileByteOutputStream = null;
124                                 FileInputStream fileInputStream = null;
125                                 try {
126                                         fileByteOutputStream = new ByteArrayOutputStream();
127                                         fileInputStream = new FileInputStream(configurationFile);
128                                         StreamCopier.copy(fileInputStream, fileByteOutputStream, configurationFile.length());
129                                         fileByteOutputStream.close();
130                                         byte[] fileBytes = fileByteOutputStream.toByteArray();
131                                         rootNode = SimpleXML.fromDocument(XML.transformToDocument(fileBytes));
132                                         return;
133                                 } catch (FileNotFoundException e) {
134                                         /* ignore. */
135                                 } catch (IOException e) {
136                                         /* ignore. */
137                                 } finally {
138                                         Closer.close(fileInputStream);
139                                         Closer.close(fileByteOutputStream);
140                                 }
141                         }
142                 }
143                 rootNode = new SimpleXML("configuration");
144         }
145
146         /**
147          * Saves the configuration.
148          *
149          * @return <code>true</code> if the configuration could be saved,
150          *         <code>false</code> otherwise
151          */
152         public boolean save() {
153                 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Trying to save configuration to: " + configurationLocation);
154                 File configurationFile = new File(configurationLocator.getFile(configurationLocation));
155                 if (!configurationFile.exists()) {
156                         File configurationFilePath = configurationFile.getAbsoluteFile().getParentFile();
157                         if (!configurationFilePath.exists() && !configurationFilePath.mkdirs()) {
158                                 return false;
159                         }
160                 }
161                 FileOutputStream fileOutputStream = null;
162                 ByteArrayInputStream configurationInputStream = null;
163                 try {
164                         byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
165                         configurationInputStream = new ByteArrayInputStream(configurationBytes);
166                         fileOutputStream = new FileOutputStream(configurationFile);
167                         StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
168                         return true;
169                 } catch (IOException ioe1) {
170                         /* ignore. */
171                 } finally {
172                         Closer.close(configurationInputStream);
173                         Closer.close(fileOutputStream);
174                 }
175                 return false;
176         }
177
178         /**
179          * Returns the value of a node.
180          *
181          * @param nodeNames
182          *            The name of all nodes in the chain
183          * @param defaultValue
184          *            The default value to return if the node could not be found
185          * @return The value of the node, or the default value if the node could not
186          *         be found
187          */
188         private String getNodeValue(String[] nodeNames, String defaultValue) {
189                 SimpleXML node = rootNode;
190                 int nodeIndex = 0;
191                 while ((node != null) && (nodeIndex < nodeNames.length)) {
192                         node = node.getNode(nodeNames[nodeIndex++]);
193                 }
194                 if (node == null) {
195                         return defaultValue;
196                 }
197                 return node.getValue();
198         }
199
200         /**
201          * Returns the integer value of a node.
202          *
203          * @param nodeNames
204          *            The names of all nodes in the chain
205          * @param defaultValue
206          *            The default value to return if the node can not be found
207          * @return The parsed integer value, or the default value if the node can
208          *         not be found or the value can not be parsed into an integer
209          */
210         private int getNodeIntValue(String[] nodeNames, int defaultValue) {
211                 try {
212                         return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
213                 } catch (NumberFormatException nfe1) {
214                         /* ignore. */
215                 }
216                 return defaultValue;
217         }
218
219         /**
220          * Returns the boolean value of a node.
221          *
222          * @param nodeNames
223          *            The names of all nodes in the chain
224          * @param defaultValue
225          *            The default value to return if the node can not be found
226          * @return The parsed boolean value, or the default value if the node can
227          *         not be found
228          */
229         private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
230                 String nodeValue = getNodeValue(nodeNames, null);
231                 if (nodeValue == null) {
232                         return defaultValue;
233                 }
234                 return Boolean.parseBoolean(nodeValue);
235         }
236
237         /**
238          * Returns the hostname of the node.
239          *
240          * @return The hostname of the node
241          * @deprecated Use {@link #getSelectedNode()} instead
242          */
243         @Deprecated
244         public String getNodeAddress() {
245                 return getNodeValue(new String[] { "node-address" }, "localhost");
246         }
247
248         /**
249          * Sets the hostname of the node.
250          *
251          * @param nodeAddress
252          *            The hostname of the node
253          * @deprecated Use {@link #setSelectedNode(Node)} instead
254          */
255         @Deprecated
256         public void setNodeAddress(String nodeAddress) {
257                 rootNode.replace("node-address", nodeAddress);
258         }
259
260         /**
261          * The port number of the node
262          *
263          * @return The port number of the node
264          * @deprecated Use {@link #getSelectedNode()} instead.
265          */
266         @Deprecated
267         public int getNodePort() {
268                 return getNodeIntValue(new String[] { "node-port" }, 9481);
269         }
270
271         /**
272          * Sets the port number of the node.
273          *
274          * @param nodePort
275          *            The port number of the node
276          * @deprecated Use {@link #setSelectedNode(Node)} instead
277          */
278         @Deprecated
279         public void setNodePort(int nodePort) {
280                 rootNode.replace("node-port", String.valueOf(nodePort));
281         }
282
283         /**
284          * Returns whether the node configuration page should be skipped on startup.
285          *
286          * @return <code>true</code> to skip the node configuration page on startup,
287          *         <code>false</code> to show it
288          */
289         public boolean isSkipNodePage() {
290                 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
291         }
292
293         /**
294          * Sets whether the node configuration page should be skipped on startup.
295          *
296          * @param skipNodePage
297          *            <code>true</code> to skip the node configuration page on
298          *            startup, <code>false</code> to show it
299          */
300         public void setSkipNodePage(boolean skipNodePage) {
301                 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
302         }
303
304         /**
305          * Returns all configured projects.
306          *
307          * @return A list of all projects
308          */
309         public List<Project> getProjects() {
310                 List<Project> projects = new ArrayList<Project>();
311                 SimpleXML projectsNode = rootNode.getNode("project-list");
312                 if (projectsNode != null) {
313                         SimpleXML[] projectNodes = projectsNode.getNodes("project");
314                         for (SimpleXML projectNode : projectNodes) {
315                                 try {
316                                         Project project = new Project();
317                                         projects.add(project);
318                                         project.setDescription(projectNode.getValue("description", ""));
319                                         String indexFile = projectNode.getValue("index-file", "");
320                                         if (indexFile.indexOf('/') > -1) {
321                                                 indexFile = "";
322                                         }
323                                         project.setIndexFile(indexFile);
324                                         project.setLastInsertionTime(Long.parseLong(projectNode.getValue("last-insertion-time", "0")));
325                                         project.setLocalPath(projectNode.getValue("local-path", ""));
326                                         project.setName(projectNode.getValue("name", ""));
327                                         project.setPath(projectNode.getValue("path", ""));
328                                         if ((project.getPath() != null) && (project.getPath().indexOf("/") != -1)) {
329                                                 project.setPath(project.getPath().replaceAll("/", ""));
330                                         }
331                                         project.setEdition(Integer.parseInt(projectNode.getValue("edition", "0")));
332                                         project.setInsertURI(projectNode.getValue("insert-uri", ""));
333                                         project.setRequestURI(projectNode.getValue("request-uri", ""));
334                                         if (projectNode.getNode("ignore-hidden-files") != null) {
335                                                 project.setIgnoreHiddenFiles(Boolean.parseBoolean(projectNode.getValue("ignore-hidden-files", "true")));
336                                         } else {
337                                                 project.setIgnoreHiddenFiles(true);
338                                         }
339                                         project.setAlwaysForceInsert(Boolean.parseBoolean(projectNode.getValue("always-force-insert", "false")));
340
341                                         /* load last insert hashes. */
342                                         Map<String, FileOption> fileOptions = new HashMap<String, FileOption>();
343                                         SimpleXML lastInsertHashesNode = projectNode.getNode("last-insert-hashes");
344                                         if (lastInsertHashesNode != null) {
345                                                 for (SimpleXML fileNode : lastInsertHashesNode.getNodes("file")) {
346                                                         String filename = fileNode.getNode("filename").getValue();
347                                                         String lastInsertHash = fileNode.getNode("last-insert-hash").getValue();
348                                                         int lastInsertEdition = Integer.valueOf(fileNode.getNode("last-insert-edition").getValue());
349                                                         String lastInsertFilename = filename;
350                                                         if (fileNode.getNode("last-insert-filename") != null) {
351                                                                 lastInsertFilename = fileNode.getNode("last-insert-filename").getValue();
352                                                         }
353                                                         FileOption fileOption = project.getFileOption(filename);
354                                                         fileOption.setLastInsertHash(lastInsertHash).setLastInsertEdition(lastInsertEdition).setLastInsertFilename(lastInsertFilename);
355                                                         fileOptions.put(filename, fileOption);
356                                                 }
357                                         }
358
359                                         SimpleXML fileOptionsNode = projectNode.getNode("file-options");
360                                         if (fileOptionsNode != null) {
361                                                 SimpleXML[] fileOptionNodes = fileOptionsNode.getNodes("file-option");
362                                                 for (SimpleXML fileOptionNode : fileOptionNodes) {
363                                                         String filename = fileOptionNode.getNode("filename").getValue();
364                                                         FileOption fileOption = project.getFileOption(filename);
365                                                         fileOption.setInsert(Boolean.parseBoolean(fileOptionNode.getNode("insert").getValue()));
366                                                         if (fileOptionNode.getNode("insert-redirect") != null) {
367                                                                 fileOption.setInsertRedirect(Boolean.parseBoolean(fileOptionNode.getNode("insert-redirect").getValue()));
368                                                         }
369                                                         fileOption.setCustomKey(fileOptionNode.getValue("custom-key", ""));
370                                                         if (fileOptionNode.getNode("changed-name") != null) {
371                                                                 fileOption.setChangedName(fileOptionNode.getNode("changed-name").getValue());
372                                                         }
373                                                         fileOption.setMimeType(fileOptionNode.getValue("mime-type", ""));
374                                                         fileOptions.put(filename, fileOption);
375                                                 }
376                                         }
377                                         project.setFileOptions(fileOptions);
378                                 } catch (NumberFormatException nfe1) {
379                                         nfe1.printStackTrace();
380                                 }
381                         }
382                 }
383                 return projects;
384         }
385
386         /**
387          * Sets the list of all projects.
388          *
389          * @param projects
390          *            The list of all projects
391          */
392         public void setProjects(List<Project> projects) {
393                 SimpleXML projectsNode = new SimpleXML("project-list");
394                 for (Project project : projects) {
395                         SimpleXML projectNode = projectsNode.append("project");
396                         projectNode.append("edition", String.valueOf(project.getEdition()));
397                         projectNode.append("description", project.getDescription());
398                         projectNode.append("index-file", project.getIndexFile());
399                         projectNode.append("last-insertion-time", String.valueOf(project.getLastInsertionTime()));
400                         projectNode.append("local-path", project.getLocalPath());
401                         projectNode.append("name", project.getName());
402                         projectNode.append("path", project.getPath());
403                         projectNode.append("insert-uri", project.getInsertURI());
404                         projectNode.append("request-uri", project.getRequestURI());
405                         projectNode.append("ignore-hidden-files", String.valueOf(project.isIgnoreHiddenFiles()));
406                         projectNode.append("always-force-insert", String.valueOf(project.isAlwaysForceInsert()));
407
408                         /* store last insert hashes. */
409                         SimpleXML lastInsertHashesNode = projectNode.append("last-insert-hashes");
410                         for (Entry<String, FileOption> fileOption : project.getFileOptions().entrySet()) {
411                                 if ((fileOption.getValue().getLastInsertHash() == null) || (fileOption.getValue().getLastInsertHash().length() == 0)) {
412                                         continue;
413                                 }
414                                 SimpleXML fileNode = lastInsertHashesNode.append("file");
415                                 fileNode.append("filename", fileOption.getKey());
416                                 fileNode.append("last-insert-hash", fileOption.getValue().getLastInsertHash());
417                                 fileNode.append("last-insert-edition", String.valueOf(fileOption.getValue().getLastInsertEdition()));
418                                 fileNode.append("last-insert-filename", fileOption.getValue().getLastInsertFilename());
419                         }
420
421                         SimpleXML fileOptionsNode = projectNode.append("file-options");
422                         Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
423                         while (entries.hasNext()) {
424                                 Entry<String, FileOption> entry = entries.next();
425                                 FileOption fileOption = entry.getValue();
426                                 if (fileOption.isCustom()) {
427                                         SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
428                                         fileOptionNode.append("filename", entry.getKey());
429                                         fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
430                                         fileOptionNode.append("insert-redirect", String.valueOf(fileOption.isInsertRedirect()));
431                                         fileOptionNode.append("custom-key", fileOption.getCustomKey());
432                                         fileOptionNode.append("changed-name", fileOption.getChangedName().orNull());
433                                         fileOptionNode.append("mime-type", fileOption.getMimeType());
434                                 }
435                         }
436                 }
437                 rootNode.replace(projectsNode);
438         }
439
440         /**
441          * Returns the stored locale.
442          *
443          * @return The stored locale
444          */
445         public Locale getLocale() {
446                 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
447                 String country = getNodeValue(new String[] { "i18n", "country" }, null);
448                 if (country != null) {
449                         return new Locale(language, country);
450                 }
451                 return new Locale(language);
452         }
453
454         /**
455          * Sets the locale to store.
456          *
457          * @param locale
458          *            The locale to store
459          */
460         public void setLocale(Locale locale) {
461                 SimpleXML i18nNode = new SimpleXML("i18n");
462                 if (locale.getCountry().length() != 0) {
463                         i18nNode.append("country", locale.getCountry());
464                 }
465                 i18nNode.append("language", locale.getLanguage());
466                 rootNode.replace(i18nNode);
467                 return;
468         }
469
470         /**
471          * Returns a list of configured nodes.
472          *
473          * @return The list of the configured nodes
474          */
475         public Node[] getNodes() {
476                 SimpleXML nodesNode = rootNode.getNode("nodes");
477                 if (nodesNode == null) {
478                         String hostname = getNodeAddress();
479                         int port = getNodePort();
480                         if (hostname == null) {
481                                 hostname = "127.0.0.1";
482                                 port = 9481;
483                         }
484                         return new Node[] { new Node(hostname, port, "Node") };
485                 }
486                 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
487                 Node[] returnNodes = new Node[nodeNodes.length];
488                 int nodeIndex = 0;
489                 for (SimpleXML nodeNode : nodeNodes) {
490                         String name = nodeNode.getNode("name").getValue();
491                         String hostname = nodeNode.getNode("hostname").getValue();
492                         int port = Integer.parseInt(nodeNode.getNode("port").getValue());
493                         Node node = new Node(hostname, port, name);
494                         returnNodes[nodeIndex++] = node;
495                 }
496                 return returnNodes;
497         }
498
499         /**
500          * Sets the list of configured nodes.
501          *
502          * @param nodes
503          *            The list of configured nodes
504          */
505         public void setNodes(Node[] nodes) {
506                 SimpleXML nodesNode = new SimpleXML("nodes");
507                 for (Node node : nodes) {
508                         SimpleXML nodeNode = nodesNode.append("node");
509                         nodeNode.append("name", node.getName());
510                         nodeNode.append("hostname", node.getHostname());
511                         nodeNode.append("port", String.valueOf(node.getPort()));
512                 }
513                 rootNode.replace(nodesNode);
514                 rootNode.remove("node-address");
515                 rootNode.remove("node-port");
516         }
517
518         /**
519          * Sets the selected node.
520          *
521          * @param selectedNode
522          *            The selected node
523          */
524         public void setSelectedNode(Node selectedNode) {
525                 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
526                 selectedNodeNode.append("name", selectedNode.getName());
527                 selectedNodeNode.append("hostname", selectedNode.getHostname());
528                 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
529                 rootNode.replace(selectedNodeNode);
530         }
531
532         /**
533          * Returns the selected node.
534          *
535          * @return The selected node
536          */
537         public Node getSelectedNode() {
538                 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
539                 if (selectedNodeNode == null) {
540                         String hostname = getNodeAddress();
541                         int port = getNodePort();
542                         if (hostname == null) {
543                                 hostname = "127.0.0.1";
544                                 port = 9481;
545                         }
546                         return new Node(hostname, port, "Node");
547                 }
548                 String name = selectedNodeNode.getNode("name").getValue();
549                 String hostname = selectedNodeNode.getNode("hostname").getValue();
550                 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
551                 return new Node(hostname, port, name);
552         }
553
554         /**
555          * Returns the temp directory to use.
556          *
557          * @return The temp directoy, or {@code null} to use the default temp
558          *         directory
559          */
560         public String getTempDirectory() {
561                 return getNodeValue(new String[] { "temp-directory" }, null);
562         }
563
564         /**
565          * Sets the temp directory to use.
566          *
567          * @param tempDirectory
568          *            The temp directory to use, or {@code null} to use the default
569          *            temp directory
570          */
571         public void setTempDirectory(String tempDirectory) {
572                 if (tempDirectory != null) {
573                         SimpleXML tempDirectoryNode = new SimpleXML("temp-directory");
574                         tempDirectoryNode.setValue(tempDirectory);
575                         rootNode.replace(tempDirectoryNode);
576                 } else {
577                         rootNode.remove("temp-directory");
578                 }
579         }
580
581         /**
582          * Returns whether to use the “early encode“ flag for the insert.
583          *
584          * @return {@code true} to set the “early encode” flag for the insert,
585          *         {@code false} otherwise
586          */
587         public boolean useEarlyEncode() {
588                 return getNodeBooleanValue(new String[] { "use-early-encode" }, false);
589         }
590
591         /**
592          * Sets whether to use the “early encode“ flag for the insert.
593          *
594          * @param useEarlyEncode
595          *            {@code true} to set the “early encode” flag for the insert,
596          *            {@code false} otherwise
597          * @return This configuration
598          */
599         public Configuration setUseEarlyEncode(boolean useEarlyEncode) {
600                 rootNode.replace("use-early-encode", String.valueOf(useEarlyEncode));
601                 return this;
602         }
603
604         /**
605          * Returns the insert priority.
606          *
607          * @return The insert priority
608          */
609         public PriorityClass getPriority() {
610                 return PriorityClass.valueOf(getNodeValue(new String[] { "insert-priority" }, "interactive"));
611         }
612
613         /**
614          * Sets the insert priority.
615          *
616          * @param priority
617          *            The insert priority
618          * @return This configuration
619          */
620         public Configuration setPriority(PriorityClass priority) {
621                 rootNode.replace("insert-priority", priority.toString());
622                 return this;
623         }
624
625 }