2 * jSite - Configuration.java - Copyright © 2006–2014 David Roden
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.
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.
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.
19 package de.todesbaum.jsite.main;
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
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;
34 import java.util.Map.Entry;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
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;
51 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
53 public class Configuration {
55 /** The root node of the configuration. */
56 private SimpleXML rootNode;
58 /** The configuration locator. */
59 private final ConfigurationLocator configurationLocator;
61 /** Where the configuration resides. */
62 private ConfigurationLocation configurationLocation;
65 * Creates a new configuration that is read from the given file.
67 * @param configurationLocator
68 * The configuration locator
69 * @param configurationLocation
70 * The configuration directory
72 public Configuration(ConfigurationLocator configurationLocator, ConfigurationLocation configurationLocation) {
73 this.configurationLocator = configurationLocator;
74 this.configurationLocation = configurationLocation;
75 readConfiguration(configurationLocator.getFile(configurationLocation));
83 * Returns the configuration locator.
85 * @return The configuration locator
87 public ConfigurationLocator getConfigurationLocator() {
88 return configurationLocator;
92 * Returns the location the configuration will be written to when calling
95 * @return The location the configuration will be written to
97 public ConfigurationLocation getConfigurationDirectory() {
98 return configurationLocation;
102 * Sets the location the configuration will be written to when calling
105 * @param configurationLocation
106 * The location to write the configuration to
108 public void setConfigurationLocation(ConfigurationLocation configurationLocation) {
109 this.configurationLocation = configurationLocation;
113 * Reads the configuration from the file.
116 * The name of the file to read the configuration from
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;
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));
133 } catch (FileNotFoundException e) {
135 } catch (IOException e) {
138 Closer.close(fileInputStream);
139 Closer.close(fileByteOutputStream);
143 rootNode = new SimpleXML("configuration");
147 * Saves the configuration.
149 * @return <code>true</code> if the configuration could be saved,
150 * <code>false</code> otherwise
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()) {
161 FileOutputStream fileOutputStream = null;
162 ByteArrayInputStream configurationInputStream = null;
164 byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
165 configurationInputStream = new ByteArrayInputStream(configurationBytes);
166 fileOutputStream = new FileOutputStream(configurationFile);
167 StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
169 } catch (IOException ioe1) {
172 Closer.close(configurationInputStream);
173 Closer.close(fileOutputStream);
179 * Returns the value of a node.
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
188 private String getNodeValue(String[] nodeNames, String defaultValue) {
189 SimpleXML node = rootNode;
191 while ((node != null) && (nodeIndex < nodeNames.length)) {
192 node = node.getNode(nodeNames[nodeIndex++]);
197 return node.getValue();
201 * Returns the integer value of a node.
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
210 private int getNodeIntValue(String[] nodeNames, int defaultValue) {
212 return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
213 } catch (NumberFormatException nfe1) {
220 * Returns the boolean value of a node.
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
229 private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
230 String nodeValue = getNodeValue(nodeNames, null);
231 if (nodeValue == null) {
234 return Boolean.parseBoolean(nodeValue);
238 * Returns the hostname of the node.
240 * @return The hostname of the node
241 * @deprecated Use {@link #getSelectedNode()} instead
244 public String getNodeAddress() {
245 return getNodeValue(new String[] { "node-address" }, "localhost");
249 * Sets the hostname of the node.
252 * The hostname of the node
253 * @deprecated Use {@link #setSelectedNode(Node)} instead
256 public void setNodeAddress(String nodeAddress) {
257 rootNode.replace("node-address", nodeAddress);
261 * The port number of the node
263 * @return The port number of the node
264 * @deprecated Use {@link #getSelectedNode()} instead.
267 public int getNodePort() {
268 return getNodeIntValue(new String[] { "node-port" }, 9481);
272 * Sets the port number of the node.
275 * The port number of the node
276 * @deprecated Use {@link #setSelectedNode(Node)} instead
279 public void setNodePort(int nodePort) {
280 rootNode.replace("node-port", String.valueOf(nodePort));
284 * Returns whether the node configuration page should be skipped on startup.
286 * @return <code>true</code> to skip the node configuration page on startup,
287 * <code>false</code> to show it
289 public boolean isSkipNodePage() {
290 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
294 * Sets whether the node configuration page should be skipped on startup.
296 * @param skipNodePage
297 * <code>true</code> to skip the node configuration page on
298 * startup, <code>false</code> to show it
300 public void setSkipNodePage(boolean skipNodePage) {
301 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
305 * Returns all configured projects.
307 * @return A list of all projects
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) {
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) {
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("/", ""));
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")));
337 project.setIgnoreHiddenFiles(true);
339 project.setAlwaysForceInsert(Boolean.parseBoolean(projectNode.getValue("always-force-insert", "false")));
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();
353 FileOption fileOption = project.getFileOption(filename);
354 fileOption.setLastInsertHash(lastInsertHash).setLastInsertEdition(lastInsertEdition).setLastInsertFilename(lastInsertFilename);
355 fileOptions.put(filename, fileOption);
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()));
369 fileOption.setCustomKey(fileOptionNode.getValue("custom-key", ""));
370 if (fileOptionNode.getNode("changed-name") != null) {
371 fileOption.setChangedName(fileOptionNode.getNode("changed-name").getValue());
373 fileOption.setMimeType(fileOptionNode.getValue("mime-type", ""));
374 fileOptions.put(filename, fileOption);
377 project.setFileOptions(fileOptions);
378 } catch (NumberFormatException nfe1) {
379 nfe1.printStackTrace();
387 * Sets the list of all projects.
390 * The list of all projects
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()));
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)) {
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());
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());
437 rootNode.replace(projectsNode);
441 * Returns the stored locale.
443 * @return The stored locale
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);
451 return new Locale(language);
455 * Sets the locale to store.
458 * The locale to store
460 public void setLocale(Locale locale) {
461 SimpleXML i18nNode = new SimpleXML("i18n");
462 if (locale.getCountry().length() != 0) {
463 i18nNode.append("country", locale.getCountry());
465 i18nNode.append("language", locale.getLanguage());
466 rootNode.replace(i18nNode);
471 * Returns a list of configured nodes.
473 * @return The list of the configured nodes
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";
484 return new Node[] { new Node(hostname, port, "Node") };
486 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
487 Node[] returnNodes = new Node[nodeNodes.length];
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;
500 * Sets the list of configured nodes.
503 * The list of configured nodes
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()));
513 rootNode.replace(nodesNode);
514 rootNode.remove("node-address");
515 rootNode.remove("node-port");
519 * Sets the selected node.
521 * @param selectedNode
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);
533 * Returns the selected node.
535 * @return The selected node
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";
546 return new Node(hostname, port, "Node");
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);
555 * Returns the temp directory to use.
557 * @return The temp directoy, or {@code null} to use the default temp
560 public String getTempDirectory() {
561 return getNodeValue(new String[] { "temp-directory" }, null);
565 * Sets the temp directory to use.
567 * @param tempDirectory
568 * The temp directory to use, or {@code null} to use the default
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);
577 rootNode.remove("temp-directory");
582 * Returns whether to use the “early encode“ flag for the insert.
584 * @return {@code true} to set the “early encode” flag for the insert,
585 * {@code false} otherwise
587 public boolean useEarlyEncode() {
588 return getNodeBooleanValue(new String[] { "use-early-encode" }, false);
592 * Sets whether to use the “early encode“ flag for the insert.
594 * @param useEarlyEncode
595 * {@code true} to set the “early encode” flag for the insert,
596 * {@code false} otherwise
597 * @return This configuration
599 public Configuration setUseEarlyEncode(boolean useEarlyEncode) {
600 rootNode.replace("use-early-encode", String.valueOf(useEarlyEncode));
605 * Returns the insert priority.
607 * @return The insert priority
609 public PriorityClass getPriority() {
610 return PriorityClass.valueOf(getNodeValue(new String[] { "insert-priority" }, "interactive"));
614 * Sets the insert priority.
617 * The insert priority
618 * @return This configuration
620 public Configuration setPriority(PriorityClass priority) {
621 rootNode.replace("insert-priority", priority.toString());