2 * jSite - Configuration.java - Copyright © 2006–2012 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 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.freenet.fcp2.ClientPutDir.ManifestPutter;
43 import de.todesbaum.util.freenet.fcp2.PriorityClass;
44 import de.todesbaum.util.io.Closer;
45 import de.todesbaum.util.io.StreamCopier;
46 import de.todesbaum.util.xml.SimpleXML;
47 import de.todesbaum.util.xml.XML;
52 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
54 public class Configuration {
56 /** The root node of the configuration. */
57 private SimpleXML rootNode;
59 /** The configuration locator. */
60 private final ConfigurationLocator configurationLocator;
62 /** Where the configuration resides. */
63 private ConfigurationLocation configurationLocation;
66 * Creates a new configuration that is read from the given file.
68 * @param configurationLocator
69 * The configuration locator
70 * @param configurationLocation
71 * The configuration directory
73 public Configuration(ConfigurationLocator configurationLocator, ConfigurationLocation configurationLocation) {
74 this.configurationLocator = configurationLocator;
75 this.configurationLocation = configurationLocation;
76 readConfiguration(configurationLocator.getFile(configurationLocation));
84 * Returns the configuration locator.
86 * @return The configuration locator
88 public ConfigurationLocator getConfigurationLocator() {
89 return configurationLocator;
93 * Returns the location the configuration will be written to when calling
96 * @return The location the configuration will be written to
98 public ConfigurationLocation getConfigurationDirectory() {
99 return configurationLocation;
103 * Sets the location the configuration will be written to when calling
106 * @param configurationLocation
107 * The location to write the configuration to
109 public void setConfigurationLocation(ConfigurationLocation configurationLocation) {
110 this.configurationLocation = configurationLocation;
114 * Reads the configuration from the file.
117 * The name of the file to read the configuration from
119 private void readConfiguration(String filename) {
120 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Reading configuration from: " + filename);
121 if (filename != null) {
122 File configurationFile = new File(filename);
123 if (configurationFile.exists()) {
124 ByteArrayOutputStream fileByteOutputStream = null;
125 FileInputStream fileInputStream = null;
127 fileByteOutputStream = new ByteArrayOutputStream();
128 fileInputStream = new FileInputStream(configurationFile);
129 StreamCopier.copy(fileInputStream, fileByteOutputStream, configurationFile.length());
130 fileByteOutputStream.close();
131 byte[] fileBytes = fileByteOutputStream.toByteArray();
132 rootNode = SimpleXML.fromDocument(XML.transformToDocument(fileBytes));
134 } catch (FileNotFoundException e) {
136 } catch (IOException e) {
139 Closer.close(fileInputStream);
140 Closer.close(fileByteOutputStream);
144 rootNode = new SimpleXML("configuration");
148 * Saves the configuration.
150 * @return <code>true</code> if the configuration could be saved,
151 * <code>false</code> otherwise
153 public boolean save() {
154 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Trying to save configuration to: " + configurationLocation);
155 File configurationFile = new File(configurationLocator.getFile(configurationLocation));
156 if (!configurationFile.exists()) {
157 File configurationFilePath = configurationFile.getAbsoluteFile().getParentFile();
158 if (!configurationFilePath.exists() && !configurationFilePath.mkdirs()) {
162 FileOutputStream fileOutputStream = null;
163 ByteArrayInputStream configurationInputStream = null;
165 byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
166 configurationInputStream = new ByteArrayInputStream(configurationBytes);
167 fileOutputStream = new FileOutputStream(configurationFile);
168 StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
170 } catch (IOException ioe1) {
173 Closer.close(configurationInputStream);
174 Closer.close(fileOutputStream);
180 * Returns the value of a node.
183 * The name of all nodes in the chain
184 * @param defaultValue
185 * The default value to return if the node could not be found
186 * @return The value of the node, or the default value if the node could not
189 private String getNodeValue(String[] nodeNames, String defaultValue) {
190 SimpleXML node = rootNode;
192 while ((node != null) && (nodeIndex < nodeNames.length)) {
193 node = node.getNode(nodeNames[nodeIndex++]);
198 return node.getValue();
202 * Returns the integer value of a node.
205 * The names of all nodes in the chain
206 * @param defaultValue
207 * The default value to return if the node can not be found
208 * @return The parsed integer value, or the default value if the node can
209 * not be found or the value can not be parsed into an integer
211 private int getNodeIntValue(String[] nodeNames, int defaultValue) {
213 return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
214 } catch (NumberFormatException nfe1) {
221 * Returns the boolean value of a node.
224 * The names of all nodes in the chain
225 * @param defaultValue
226 * The default value to return if the node can not be found
227 * @return The parsed boolean value, or the default value if the node can
230 private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
231 String nodeValue = getNodeValue(nodeNames, null);
232 if (nodeValue == null) {
235 return Boolean.parseBoolean(nodeValue);
239 * Returns the hostname of the node.
241 * @return The hostname of the node
242 * @deprecated Use {@link #getSelectedNode()} instead
245 public String getNodeAddress() {
246 return getNodeValue(new String[] { "node-address" }, "localhost");
250 * Sets the hostname of the node.
253 * The hostname of the node
254 * @deprecated Use {@link #setSelectedNode(Node)} instead
257 public void setNodeAddress(String nodeAddress) {
258 rootNode.replace("node-address", nodeAddress);
262 * The port number of the node
264 * @return The port number of the node
265 * @deprecated Use {@link #getSelectedNode()} instead.
268 public int getNodePort() {
269 return getNodeIntValue(new String[] { "node-port" }, 9481);
273 * Sets the port number of the node.
276 * The port number of the node
277 * @deprecated Use {@link #setSelectedNode(Node)} instead
280 public void setNodePort(int nodePort) {
281 rootNode.replace("node-port", String.valueOf(nodePort));
285 * Returns whether the node configuration page should be skipped on startup.
287 * @return <code>true</code> to skip the node configuration page on startup,
288 * <code>false</code> to show it
290 public boolean isSkipNodePage() {
291 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
295 * Sets whether the node configuration page should be skipped on startup.
297 * @param skipNodePage
298 * <code>true</code> to skip the node configuration page on
299 * startup, <code>false</code> to show it
301 public void setSkipNodePage(boolean skipNodePage) {
302 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
306 * Returns all configured projects.
308 * @return A list of all projects
310 public Project[] getProjects() {
311 List<Project> projects = new ArrayList<Project>();
312 SimpleXML projectsNode = rootNode.getNode("project-list");
313 if (projectsNode != null) {
314 SimpleXML[] projectNodes = projectsNode.getNodes("project");
315 for (SimpleXML projectNode : projectNodes) {
317 Project project = new Project();
318 projects.add(project);
319 project.setDescription(projectNode.getNode("description").getValue(""));
320 String indexFile = projectNode.getNode("index-file").getValue("");
321 if (indexFile.indexOf('/') > -1) {
324 project.setIndexFile(indexFile);
325 project.setLastInsertionTime(Long.parseLong(projectNode.getNode("last-insertion-time").getValue("0")));
326 project.setLocalPath(projectNode.getNode("local-path").getValue(""));
327 project.setName(projectNode.getNode("name").getValue(""));
328 project.setPath(projectNode.getNode("path").getValue(""));
329 if ((project.getPath() != null) && (project.getPath().indexOf("/") != -1)) {
330 project.setPath(project.getPath().replaceAll("/", ""));
332 project.setEdition(Integer.parseInt(projectNode.getNode("edition").getValue("0")));
333 project.setInsertURI(projectNode.getNode("insert-uri").getValue(""));
334 project.setRequestURI(projectNode.getNode("request-uri").getValue(""));
335 if (projectNode.getNode("ignore-hidden-files") != null) {
336 project.setIgnoreHiddenFiles(Boolean.parseBoolean(projectNode.getNode("ignore-hidden-files").getValue("true")));
338 project.setIgnoreHiddenFiles(true);
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.getNode("custom-key").getValue(""));
370 if (fileOptionNode.getNode("changed-name") != null) {
371 fileOption.setChangedName(fileOptionNode.getNode("changed-name").getValue());
373 fileOption.setMimeType(fileOptionNode.getNode("mime-type").getValue(""));
374 fileOptions.put(filename, fileOption);
377 project.setFileOptions(fileOptions);
378 } catch (NumberFormatException nfe1) {
379 nfe1.printStackTrace();
383 return projects.toArray(new Project[projects.size()]);
387 * Sets the list of all projects.
390 * The list of all projects
392 public void setProjects(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()));
407 /* store last insert hashes. */
408 SimpleXML lastInsertHashesNode = projectNode.append("last-insert-hashes");
409 for (Entry<String, FileOption> fileOption : project.getFileOptions().entrySet()) {
410 if ((fileOption.getValue().getLastInsertHash() == null) || (fileOption.getValue().getLastInsertHash().length() == 0)) {
413 SimpleXML fileNode = lastInsertHashesNode.append("file");
414 fileNode.append("filename", fileOption.getKey());
415 fileNode.append("last-insert-hash", fileOption.getValue().getLastInsertHash());
416 fileNode.append("last-insert-edition", String.valueOf(fileOption.getValue().getLastInsertEdition()));
417 fileNode.append("last-insert-filename", fileOption.getValue().getLastInsertFilename());
420 SimpleXML fileOptionsNode = projectNode.append("file-options");
421 Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
422 while (entries.hasNext()) {
423 Entry<String, FileOption> entry = entries.next();
424 FileOption fileOption = entry.getValue();
425 if (fileOption.isCustom()) {
426 SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
427 fileOptionNode.append("filename", entry.getKey());
428 fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
429 fileOptionNode.append("insert-redirect", String.valueOf(fileOption.isInsertRedirect()));
430 fileOptionNode.append("custom-key", fileOption.getCustomKey());
431 fileOptionNode.append("changed-name", fileOption.getChangedName());
432 fileOptionNode.append("mime-type", fileOption.getMimeType());
436 rootNode.replace(projectsNode);
440 * Returns the stored locale.
442 * @return The stored locale
444 public Locale getLocale() {
445 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
446 String country = getNodeValue(new String[] { "i18n", "country" }, null);
447 if (country != null) {
448 return new Locale(language, country);
450 return new Locale(language);
454 * Sets the locale to store.
457 * The locale to store
459 public void setLocale(Locale locale) {
460 SimpleXML i18nNode = new SimpleXML("i18n");
461 if (locale.getCountry().length() != 0) {
462 i18nNode.append("country", locale.getCountry());
464 i18nNode.append("language", locale.getLanguage());
465 rootNode.replace(i18nNode);
470 * Returns a list of configured nodes.
472 * @return The list of the configured nodes
474 public Node[] getNodes() {
475 SimpleXML nodesNode = rootNode.getNode("nodes");
476 if (nodesNode == null) {
477 String hostname = getNodeAddress();
478 int port = getNodePort();
479 if (hostname == null) {
480 hostname = "127.0.0.1";
483 return new Node[] { new Node(hostname, port, "Node") };
485 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
486 Node[] returnNodes = new Node[nodeNodes.length];
488 for (SimpleXML nodeNode : nodeNodes) {
489 String name = nodeNode.getNode("name").getValue();
490 String hostname = nodeNode.getNode("hostname").getValue();
491 int port = Integer.parseInt(nodeNode.getNode("port").getValue());
492 Node node = new Node(hostname, port, name);
493 returnNodes[nodeIndex++] = node;
499 * Sets the list of configured nodes.
502 * The list of configured nodes
504 public void setNodes(Node[] nodes) {
505 SimpleXML nodesNode = new SimpleXML("nodes");
506 for (Node node : nodes) {
507 SimpleXML nodeNode = nodesNode.append("node");
508 nodeNode.append("name", node.getName());
509 nodeNode.append("hostname", node.getHostname());
510 nodeNode.append("port", String.valueOf(node.getPort()));
512 rootNode.replace(nodesNode);
513 rootNode.remove("node-address");
514 rootNode.remove("node-port");
518 * Sets the selected node.
520 * @param selectedNode
523 public void setSelectedNode(Node selectedNode) {
524 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
525 selectedNodeNode.append("name", selectedNode.getName());
526 selectedNodeNode.append("hostname", selectedNode.getHostname());
527 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
528 rootNode.replace(selectedNodeNode);
532 * Returns the selected node.
534 * @return The selected node
536 public Node getSelectedNode() {
537 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
538 if (selectedNodeNode == null) {
539 String hostname = getNodeAddress();
540 int port = getNodePort();
541 if (hostname == null) {
542 hostname = "127.0.0.1";
545 return new Node(hostname, port, "Node");
547 String name = selectedNodeNode.getNode("name").getValue();
548 String hostname = selectedNodeNode.getNode("hostname").getValue();
549 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
550 return new Node(hostname, port, name);
554 * Returns the temp directory to use.
556 * @return The temp directoy, or {@code null} to use the default temp
559 public String getTempDirectory() {
560 return getNodeValue(new String[] { "temp-directory" }, null);
564 * Sets the temp directory to use.
566 * @param tempDirectory
567 * The temp directory to use, or {@code null} to use the default
570 public void setTempDirectory(String tempDirectory) {
571 if (tempDirectory != null) {
572 SimpleXML tempDirectoryNode = new SimpleXML("temp-directory");
573 tempDirectoryNode.setValue(tempDirectory);
574 rootNode.replace(tempDirectoryNode);
576 rootNode.remove("temp-directory");
581 * Returns whether to use the “early encode“ flag for the insert.
583 * @return {@code true} to set the “early encode” flag for the insert,
584 * {@code false} otherwise
586 public boolean useEarlyEncode() {
587 return getNodeBooleanValue(new String[] { "use-early-encode" }, false);
591 * Sets whether to use the “early encode“ flag for the insert.
593 * @param useEarlyEncode
594 * {@code true} to set the “early encode” flag for the insert,
595 * {@code false} otherwise
596 * @return This configuration
598 public Configuration setUseEarlyEncode(boolean useEarlyEncode) {
599 rootNode.replace("use-early-encode", String.valueOf(useEarlyEncode));
604 * Returns the insert priority.
606 * @return The insert priority
608 public PriorityClass getPriority() {
609 return PriorityClass.valueOf(getNodeValue(new String[] { "insert-priority" }, "interactive"));
613 * Sets the insert priority.
616 * The insert priority
617 * @return This configuration
619 public Configuration setPriority(PriorityClass priority) {
620 rootNode.replace("insert-priority", priority.toString());
625 * Returns the manifest putter.
627 * @return The manifest putter
629 public ManifestPutter getManifestPutter() {
630 return ManifestPutter.valueOf(getNodeValue(new String[] { "manifest-putter" }, "simple").toUpperCase());
634 * Sets the manifest putter.
636 * @param manifestPutter
637 * The manifest putter
638 * @return This configuration
640 public Configuration setManifestPutter(ManifestPutter manifestPutter) {
641 rootNode.replace("manifest-putter", manifestPutter.name().toLowerCase());