2 * jSite - Configuration.java - Copyright © 2006–2011 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.io.Closer;
43 import de.todesbaum.util.io.StreamCopier;
44 import de.todesbaum.util.xml.SimpleXML;
45 import de.todesbaum.util.xml.XML;
50 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
52 public class Configuration {
54 /** The root node of the configuration. */
55 private SimpleXML rootNode;
57 /** The configuration locator. */
58 private final ConfigurationLocator configurationLocator;
60 /** Where the configuration resides. */
61 private ConfigurationLocation configurationLocation;
64 * Creates a new configuration that is read from the given file.
66 * @param configurationLocator
67 * The configuration locator
68 * @param configurationLocation
69 * The configuration directory
71 public Configuration(ConfigurationLocator configurationLocator, ConfigurationLocation configurationLocation) {
72 this.configurationLocator = configurationLocator;
73 this.configurationLocation = configurationLocation;
74 readConfiguration(configurationLocator.getFile(configurationLocation));
82 * Returns the configuration locator.
84 * @return The configuration locator
86 public ConfigurationLocator getConfigurationLocator() {
87 return configurationLocator;
91 * Returns the location the configuration will be written to when calling
94 * @return The location the configuration will be written to
96 public ConfigurationLocation getConfigurationDirectory() {
97 return configurationLocation;
101 * Sets the location the configuration will be written to when calling
104 * @param configurationLocation
105 * The location to write the configuration to
107 public void setConfigurationLocation(ConfigurationLocation configurationLocation) {
108 this.configurationLocation = configurationLocation;
112 * Reads the configuration from the file.
115 * The name of the file to read the configuration from
117 private void readConfiguration(String filename) {
118 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Reading configuration from: " + filename);
119 if (filename != null) {
120 File configurationFile = new File(filename);
121 if (configurationFile.exists()) {
122 ByteArrayOutputStream fileByteOutputStream = null;
123 FileInputStream fileInputStream = null;
125 fileByteOutputStream = new ByteArrayOutputStream();
126 fileInputStream = new FileInputStream(configurationFile);
127 StreamCopier.copy(fileInputStream, fileByteOutputStream, configurationFile.length());
128 fileByteOutputStream.close();
129 byte[] fileBytes = fileByteOutputStream.toByteArray();
130 rootNode = SimpleXML.fromDocument(XML.transformToDocument(fileBytes));
132 } catch (FileNotFoundException e) {
134 } catch (IOException e) {
137 Closer.close(fileInputStream);
138 Closer.close(fileByteOutputStream);
142 rootNode = new SimpleXML("configuration");
146 * Saves the configuration.
148 * @return <code>true</code> if the configuration could be saved,
149 * <code>false</code> otherwise
151 public boolean save() {
152 Logger.getLogger(Configuration.class.getName()).log(Level.CONFIG, "Trying to save configuration to: " + configurationLocation);
153 File configurationFile = new File(configurationLocator.getFile(configurationLocation));
154 if (!configurationFile.exists()) {
155 File configurationFilePath = configurationFile.getAbsoluteFile().getParentFile();
156 if (!configurationFilePath.exists() && !configurationFilePath.mkdirs()) {
160 FileOutputStream fileOutputStream = null;
161 ByteArrayInputStream configurationInputStream = null;
163 byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
164 configurationInputStream = new ByteArrayInputStream(configurationBytes);
165 fileOutputStream = new FileOutputStream(configurationFile);
166 StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
168 } catch (IOException ioe1) {
171 Closer.close(configurationInputStream);
172 Closer.close(fileOutputStream);
178 * Returns the value of a node.
181 * The name of all nodes in the chain
182 * @param defaultValue
183 * The default value to return if the node could not be found
184 * @return The value of the node, or the default value if the node could not
187 private String getNodeValue(String[] nodeNames, String defaultValue) {
188 SimpleXML node = rootNode;
190 while ((node != null) && (nodeIndex < nodeNames.length)) {
191 node = node.getNode(nodeNames[nodeIndex++]);
196 return node.getValue();
200 * Returns the integer value of a node.
203 * The names of all nodes in the chain
204 * @param defaultValue
205 * The default value to return if the node can not be found
206 * @return The parsed integer value, or the default value if the node can
207 * not be found or the value can not be parsed into an integer
209 private int getNodeIntValue(String[] nodeNames, int defaultValue) {
211 return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
212 } catch (NumberFormatException nfe1) {
219 * Returns the boolean value of a node.
222 * The names of all nodes in the chain
223 * @param defaultValue
224 * The default value to return if the node can not be found
225 * @return The parsed boolean value, or the default value if the node can
228 private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
229 String nodeValue = getNodeValue(nodeNames, null);
230 if (nodeValue == null) {
233 return Boolean.parseBoolean(nodeValue);
237 * Returns the hostname of the node.
239 * @return The hostname of the node
240 * @deprecated Use {@link #getSelectedNode()} instead
243 public String getNodeAddress() {
244 return getNodeValue(new String[] { "node-address" }, "localhost");
248 * Sets the hostname of the node.
251 * The hostname of the node
252 * @deprecated Use {@link #setSelectedNode(Node)} instead
255 public void setNodeAddress(String nodeAddress) {
256 rootNode.replace("node-address", nodeAddress);
260 * The port number of the node
262 * @return The port number of the node
263 * @deprecated Use {@link #getSelectedNode()} instead.
266 public int getNodePort() {
267 return getNodeIntValue(new String[] { "node-port" }, 9481);
271 * Sets the port number of the node.
274 * The port number of the node
275 * @deprecated Use {@link #setSelectedNode(Node)} instead
278 public void setNodePort(int nodePort) {
279 rootNode.replace("node-port", String.valueOf(nodePort));
283 * Returns whether the node configuration page should be skipped on startup.
285 * @return <code>true</code> to skip the node configuration page on startup,
286 * <code>false</code> to show it
288 public boolean isSkipNodePage() {
289 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
293 * Sets whether the node configuration page should be skipped on startup.
295 * @param skipNodePage
296 * <code>true</code> to skip the node configuration page on
297 * startup, <code>false</code> to show it
299 public void setSkipNodePage(boolean skipNodePage) {
300 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
304 * Returns all configured projects.
306 * @return A list of all projects
308 public Project[] getProjects() {
309 List<Project> projects = new ArrayList<Project>();
310 SimpleXML projectsNode = rootNode.getNode("project-list");
311 if (projectsNode != null) {
312 SimpleXML[] projectNodes = projectsNode.getNodes("project");
313 for (SimpleXML projectNode : projectNodes) {
315 Project project = new Project();
316 projects.add(project);
317 project.setDescription(projectNode.getNode("description").getValue(""));
318 String indexFile = projectNode.getNode("index-file").getValue("");
319 if (indexFile.indexOf('/') > -1) {
322 project.setIndexFile(indexFile);
323 project.setLastInsertionTime(Long.parseLong(projectNode.getNode("last-insertion-time").getValue("0")));
324 project.setLocalPath(projectNode.getNode("local-path").getValue(""));
325 project.setName(projectNode.getNode("name").getValue(""));
326 project.setPath(projectNode.getNode("path").getValue(""));
327 if ((project.getPath() != null) && (project.getPath().indexOf("/") != -1)) {
328 project.setPath(project.getPath().replaceAll("/", ""));
330 project.setEdition(Integer.parseInt(projectNode.getNode("edition").getValue("0")));
331 project.setInsertURI(projectNode.getNode("insert-uri").getValue(""));
332 project.setRequestURI(projectNode.getNode("request-uri").getValue(""));
333 if (projectNode.getNode("ignore-hidden-files") != null) {
334 project.setIgnoreHiddenFiles(Boolean.parseBoolean(projectNode.getNode("ignore-hidden-files").getValue("true")));
336 project.setIgnoreHiddenFiles(true);
339 /* load last insert hashes. */
340 Map<String, FileOption> fileOptions = new HashMap<String, FileOption>();
341 SimpleXML lastInsertHashesNode = projectNode.getNode("last-insert-hashes");
342 if (lastInsertHashesNode != null) {
343 for (SimpleXML fileNode : lastInsertHashesNode.getNodes("file")) {
344 String filename = fileNode.getNode("filename").getValue();
345 String lastInsertHash = fileNode.getNode("last-insert-hash").getValue();
346 int lastInsertEdition = Integer.valueOf(fileNode.getNode("last-insert-edition").getValue());
347 FileOption fileOption = project.getFileOption(filename);
348 fileOption.setLastInsertHash(lastInsertHash).setLastInsertEdition(lastInsertEdition);
349 fileOptions.put(filename, fileOption);
353 SimpleXML fileOptionsNode = projectNode.getNode("file-options");
354 if (fileOptionsNode != null) {
355 SimpleXML[] fileOptionNodes = fileOptionsNode.getNodes("file-option");
356 for (SimpleXML fileOptionNode : fileOptionNodes) {
357 String filename = fileOptionNode.getNode("filename").getValue();
358 FileOption fileOption = project.getFileOption(filename);
359 fileOption.setInsert(Boolean.parseBoolean(fileOptionNode.getNode("insert").getValue()));
360 if (fileOptionNode.getNode("insert-redirect") != null) {
361 fileOption.setInsertRedirect(Boolean.parseBoolean(fileOptionNode.getNode("insert-redirect").getValue()));
363 fileOption.setCustomKey(fileOptionNode.getNode("custom-key").getValue(""));
364 if (fileOptionNode.getNode("changed-name") != null) {
365 fileOption.setChangedName(fileOptionNode.getNode("changed-name").getValue());
367 fileOption.setMimeType(fileOptionNode.getNode("mime-type").getValue(""));
368 fileOptions.put(filename, fileOption);
371 project.setFileOptions(fileOptions);
372 } catch (NumberFormatException nfe1) {
373 nfe1.printStackTrace();
377 return projects.toArray(new Project[projects.size()]);
381 * Sets the list of all projects.
384 * The list of all projects
386 public void setProjects(Project[] projects) {
387 SimpleXML projectsNode = new SimpleXML("project-list");
388 for (Project project : projects) {
389 SimpleXML projectNode = projectsNode.append("project");
390 projectNode.append("edition", String.valueOf(project.getEdition()));
391 projectNode.append("description", project.getDescription());
392 projectNode.append("index-file", project.getIndexFile());
393 projectNode.append("last-insertion-time", String.valueOf(project.getLastInsertionTime()));
394 projectNode.append("local-path", project.getLocalPath());
395 projectNode.append("name", project.getName());
396 projectNode.append("path", project.getPath());
397 projectNode.append("insert-uri", project.getInsertURI());
398 projectNode.append("request-uri", project.getRequestURI());
399 projectNode.append("ignore-hidden-files", String.valueOf(project.isIgnoreHiddenFiles()));
401 /* store last insert hashes. */
402 SimpleXML lastInsertHashesNode = projectNode.append("last-insert-hashes");
403 for (Entry<String, FileOption> fileOption : project.getFileOptions().entrySet()) {
404 if ((fileOption.getValue().getLastInsertHash() == null) || (fileOption.getValue().getLastInsertHash().length() == 0)) {
407 SimpleXML fileNode = lastInsertHashesNode.append("file");
408 fileNode.append("filename", fileOption.getKey());
409 fileNode.append("last-insert-hash", fileOption.getValue().getLastInsertHash());
410 fileNode.append("last-insert-edition", String.valueOf(fileOption.getValue().getLastInsertEdition()));
413 SimpleXML fileOptionsNode = projectNode.append("file-options");
414 Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
415 while (entries.hasNext()) {
416 Entry<String, FileOption> entry = entries.next();
417 FileOption fileOption = entry.getValue();
418 if (fileOption.isCustom()) {
419 SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
420 fileOptionNode.append("filename", entry.getKey());
421 fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
422 fileOptionNode.append("insert-redirect", String.valueOf(fileOption.isInsertRedirect()));
423 fileOptionNode.append("custom-key", fileOption.getCustomKey());
424 fileOptionNode.append("changed-name", fileOption.getChangedName());
425 fileOptionNode.append("mime-type", fileOption.getMimeType());
429 rootNode.replace(projectsNode);
433 * Returns the stored locale.
435 * @return The stored locale
437 public Locale getLocale() {
438 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
439 String country = getNodeValue(new String[] { "i18n", "country" }, null);
440 if (country != null) {
441 return new Locale(language, country);
443 return new Locale(language);
447 * Sets the locale to store.
450 * The locale to store
452 public void setLocale(Locale locale) {
453 SimpleXML i18nNode = new SimpleXML("i18n");
454 if (locale.getCountry().length() != 0) {
455 i18nNode.append("country", locale.getCountry());
457 i18nNode.append("language", locale.getLanguage());
458 rootNode.replace(i18nNode);
463 * Returns a list of configured nodes.
465 * @return The list of the configured nodes
467 public Node[] getNodes() {
468 SimpleXML nodesNode = rootNode.getNode("nodes");
469 if (nodesNode == null) {
470 String hostname = getNodeAddress();
471 int port = getNodePort();
472 if (hostname == null) {
473 hostname = "127.0.0.1";
476 return new Node[] { new Node(hostname, port, "Node") };
478 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
479 Node[] returnNodes = new Node[nodeNodes.length];
481 for (SimpleXML nodeNode : nodeNodes) {
482 String name = nodeNode.getNode("name").getValue();
483 String hostname = nodeNode.getNode("hostname").getValue();
484 int port = Integer.parseInt(nodeNode.getNode("port").getValue());
485 Node node = new Node(hostname, port, name);
486 returnNodes[nodeIndex++] = node;
492 * Sets the list of configured nodes.
495 * The list of configured nodes
497 public void setNodes(Node[] nodes) {
498 SimpleXML nodesNode = new SimpleXML("nodes");
499 for (Node node : nodes) {
500 SimpleXML nodeNode = nodesNode.append("node");
501 nodeNode.append("name", node.getName());
502 nodeNode.append("hostname", node.getHostname());
503 nodeNode.append("port", String.valueOf(node.getPort()));
505 rootNode.replace(nodesNode);
506 rootNode.remove("node-address");
507 rootNode.remove("node-port");
511 * Sets the selected node.
513 * @param selectedNode
516 public void setSelectedNode(Node selectedNode) {
517 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
518 selectedNodeNode.append("name", selectedNode.getName());
519 selectedNodeNode.append("hostname", selectedNode.getHostname());
520 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
521 rootNode.replace(selectedNodeNode);
525 * Returns the selected node.
527 * @return The selected node
529 public Node getSelectedNode() {
530 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
531 if (selectedNodeNode == null) {
532 String hostname = getNodeAddress();
533 int port = getNodePort();
534 if (hostname == null) {
535 hostname = "127.0.0.1";
538 return new Node(hostname, port, "Node");
540 String name = selectedNodeNode.getNode("name").getValue();
541 String hostname = selectedNodeNode.getNode("hostname").getValue();
542 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
543 return new Node(hostname, port, name);
547 * Returns the temp directory to use.
549 * @return The temp directoy, or {@code null} to use the default temp
552 public String getTempDirectory() {
553 return getNodeValue(new String[] { "temp-directory" }, null);
557 * Sets the temp directory to use.
559 * @param tempDirectory
560 * The temp directory to use, or {@code null} to use the default
563 public void setTempDirectory(String tempDirectory) {
564 if (tempDirectory != null) {
565 SimpleXML tempDirectoryNode = new SimpleXML("temp-directory");
566 tempDirectoryNode.setValue(tempDirectory);
567 rootNode.replace(tempDirectoryNode);
569 rootNode.remove("temp-directory");