let users specify configuration file on the command line
[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.EditionProject;
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.util.io.StreamCopier;
42 import de.todesbaum.util.xml.SimpleXML;
43 import de.todesbaum.util.xml.XML;
44
45 /**
46  * @author David Roden <droden@gmail.com>
47  * @version $Id$
48  */
49 public class Configuration {
50
51         private String filename;
52         private String lockFilename;
53         private SimpleXML rootNode;
54
55         public Configuration() {
56                 this(System.getProperty("user.home") + "/.jSite/config7");
57         }
58         
59         public Configuration(String filename) {
60                 this(filename, filename + ".lock");
61         }
62         
63         public Configuration(String filename, String lockFilename) {
64                 this.filename = filename;
65                 this.lockFilename = lockFilename;
66                 readConfiguration();
67         }
68         
69         private boolean createConfigDirectory() {
70                 File configDirectory = new File(filename).getAbsoluteFile().getParentFile();
71                 return (configDirectory.exists() && configDirectory.isDirectory()) || configDirectory.mkdirs();
72         }
73
74         public boolean createLockFile() {
75                 if (!createConfigDirectory()) {
76                         return false;
77                 }
78                 File lockFile = new File(lockFilename);
79                 lockFile.deleteOnExit();
80                 try {
81                         return lockFile.createNewFile();
82                 } catch (IOException e) {
83                 }
84                 return false;
85         }
86
87         private void readConfiguration() {
88                 File configurationFile = new File(filename);
89                 if (configurationFile.exists()) {
90                         ByteArrayOutputStream fileByteOutputStream = null;
91                         FileInputStream fileInputStream = null;
92                         try {
93                                 fileByteOutputStream = new ByteArrayOutputStream();
94                                 fileInputStream = new FileInputStream(configurationFile);
95                                 StreamCopier.copy(fileInputStream, fileByteOutputStream, configurationFile.length());
96                                 fileByteOutputStream.close();
97                                 byte[] fileBytes = fileByteOutputStream.toByteArray();
98                                 rootNode = SimpleXML.fromDocument(XML.transformToDocument(fileBytes));
99                                 return;
100                         } catch (FileNotFoundException e) {
101                         } catch (IOException e) {
102                         } finally {
103                                 if (fileInputStream != null) {
104                                         try {
105                                                 fileInputStream.close();
106                                         } catch (IOException ioe1) {
107                                         }
108                                 }
109                                 if (fileByteOutputStream != null) {
110                                         try {
111                                                 fileByteOutputStream.close();
112                                         } catch (IOException ioe1) {
113                                         }
114                                 }
115                         }
116                 }
117                 rootNode = new SimpleXML("configuration");
118         }
119
120         public boolean save() {
121                 File configurationFile = new File(filename);
122                 if (!configurationFile.exists()) {
123                         File configurationFilePath = configurationFile.getAbsoluteFile().getParentFile();
124                         if (!configurationFilePath.exists() && !configurationFilePath.mkdirs()) {
125                                 return false;
126                         }
127                 }
128                 FileOutputStream fileOutputStream = null;
129                 ByteArrayInputStream configurationInputStream = null;
130                 try {
131                         byte[] configurationBytes = XML.transformToByteArray(rootNode.getDocument());
132                         configurationInputStream = new ByteArrayInputStream(configurationBytes);
133                         fileOutputStream = new FileOutputStream(configurationFile);
134                         StreamCopier.copy(configurationInputStream, fileOutputStream, configurationBytes.length);
135                         return true;
136                 } catch (IOException ioe1) {
137                 } finally {
138                         if (configurationInputStream != null) {
139                                 try {
140                                         configurationInputStream.close();
141                                 } catch (IOException ioe1) {
142                                 }
143                         }
144                         if (fileOutputStream != null) {
145                                 try {
146                                         fileOutputStream.close();
147                                 } catch (IOException ioe1) {
148                                 }
149                         }
150                 }
151                 return false;
152         }
153
154         private String getNodeValue(String[] nodeNames, String defaultValue) {
155                 SimpleXML node = rootNode;
156                 int nodeIndex = 0;
157                 while ((node != null) && (nodeIndex < nodeNames.length)) {
158                         node = node.getNode(nodeNames[nodeIndex++]);
159                 }
160                 if (node == null) {
161                         return defaultValue;
162                 }
163                 return node.getValue();
164         }
165
166         private int getNodeIntValue(String[] nodeNames, int defaultValue) {
167                 try {
168                         return Integer.parseInt(getNodeValue(nodeNames, String.valueOf(defaultValue)));
169                 } catch (NumberFormatException nfe1) {
170                 }
171                 return defaultValue;
172         }
173
174         private boolean getNodeBooleanValue(String[] nodeNames, boolean defaultValue) {
175                 String nodeValue = getNodeValue(nodeNames, null);
176                 if (nodeValue == null) {
177                         return defaultValue;
178                 }
179                 return Boolean.parseBoolean(nodeValue);
180         }
181
182         /**
183          * Returns the hostname of the node.
184          * @return The hostname of the node
185          * @deprecated Use {@link #getSelectedNode()} instead
186          */
187         @Deprecated
188         public String getNodeAddress() {
189                 return getNodeValue(new String[] { "node-address" }, "localhost");
190         }
191
192         /**
193          * Sets the hostname of the node.
194          * @param nodeAddress The hostname of the node
195          * @deprecated Use {@link #setSelectedNode(Node)} instead
196          */
197         @Deprecated
198         public void setNodeAddress(String nodeAddress) {
199                 rootNode.replace("node-address", nodeAddress);
200         }
201
202         /**
203          * The port number of the node
204          * @return The port number of the node
205          * @deprecated Use {@link #getSelectedNode()} instead. 
206          */
207         @Deprecated
208         public int getNodePort() {
209                 return getNodeIntValue(new String[] { "node-port" }, 9481);
210         }
211
212         /**
213          * Sets the port number of the node.
214          * @param nodePort The port number of the node
215          * @deprecated Use {@link #setSelectedNode(Node)} instead
216          */
217         @Deprecated
218         public void setNodePort(int nodePort) {
219                 rootNode.replace("node-port", String.valueOf(nodePort));
220         }
221
222         public boolean isSkipNodePage() {
223                 return getNodeBooleanValue(new String[] { "skip-node-page" }, false);
224         }
225
226         public void setSkipNodePage(boolean skipNodePage) {
227                 rootNode.replace("skip-node-page", String.valueOf(skipNodePage));
228         }
229
230         public Project[] getProjects() {
231                 List<Project> projects = new ArrayList<Project>();
232                 SimpleXML projectsNode = rootNode.getNode("project-list");
233                 if (projectsNode != null) {
234                         SimpleXML[] projectNodes = projectsNode.getNodes("project");
235                         for (SimpleXML projectNode: projectNodes) {
236                                 try {
237                                         Project project = null;
238                                         SimpleXML typeNode = projectNode.getNode("type");
239                                         if ("edition".equals(typeNode.getValue())) {
240                                                 EditionProject editionProject = new EditionProject();
241                                                 project = editionProject;
242                                                 editionProject.setEdition(Integer.parseInt(projectNode.getNode("edition").getValue()));
243                                         }
244                                         projects.add(project);
245                                         project.setDescription(projectNode.getNode("description").getValue());
246                                         project.setIndexFile(projectNode.getNode("index-file").getValue());
247                                         project.setLastInsertionTime(Long.parseLong(projectNode.getNode("last-insertion-time").getValue()));
248                                         project.setLocalPath(projectNode.getNode("local-path").getValue());
249                                         project.setName(projectNode.getNode("name").getValue());
250                                         project.setPath(projectNode.getNode("path").getValue());
251                                         project.setInsertURI(projectNode.getNode("insert-uri").getValue());
252                                         project.setRequestURI(projectNode.getNode("request-uri").getValue());
253                                         SimpleXML fileOptionsNode = projectNode.getNode("file-options");
254                                         Map<String, FileOption> fileOptions = new HashMap<String, FileOption>();
255                                         if (fileOptionsNode != null) {
256                                                 SimpleXML[] fileOptionNodes = fileOptionsNode.getNodes("file-option");
257                                                 for (SimpleXML fileOptionNode: fileOptionNodes) {
258                                                         String filename = fileOptionNode.getNode("filename").getValue();
259                                                         FileOption fileOption = project.getFileOption(filename);
260                                                         fileOption.setInsert(Boolean.parseBoolean(fileOptionNode.getNode("insert").getValue()));
261                                                         fileOption.setCustomKey(fileOptionNode.getNode("custom-key").getValue());
262                                                         fileOption.setMimeType(fileOptionNode.getNode("mime-type").getValue());
263                                                         fileOption.setContainer(fileOptionNode.getNode("container").getValue());
264                                                         if (fileOptionNode.getNode("replace-edition") != null) {
265                                                                 fileOption.setReplaceEdition(Boolean.parseBoolean(fileOptionNode.getNode("replace-edition").getValue()));
266                                                                 fileOption.setEditionRange(Integer.parseInt(fileOptionNode.getNode("edition-range").getValue()));
267                                                         }
268                                                         fileOptions.put(filename, fileOption);
269                                                 }
270                                         }
271                                         project.setFileOptions(fileOptions);
272                                 } catch (NumberFormatException nfe1) {
273                                         nfe1.printStackTrace();
274                                 }
275                         }
276                 }
277                 return projects.toArray(new Project[projects.size()]);
278         }
279
280         public void setProjects(Project[] projects) {
281                 SimpleXML projectsNode = new SimpleXML("project-list");
282                 for (Project project: projects) {
283                         SimpleXML projectNode = projectsNode.append("project");
284                         if (project instanceof EditionProject) {
285                                 projectNode.append("type", "edition");
286                                 projectNode.append("edition", String.valueOf(((EditionProject) project).getEdition()));
287                         }
288                         projectNode.append("description", project.getDescription());
289                         projectNode.append("index-file", project.getIndexFile());
290                         projectNode.append("last-insertion-time", String.valueOf(project.getLastInsertionTime()));
291                         projectNode.append("local-path", project.getLocalPath());
292                         projectNode.append("name", project.getName());
293                         projectNode.append("path", project.getPath());
294                         projectNode.append("insert-uri", project.getInsertURI());
295                         projectNode.append("request-uri", project.getRequestURI());
296                         SimpleXML fileOptionsNode = projectNode.append("file-options");
297                         Iterator<Entry<String, FileOption>> entries = project.getFileOptions().entrySet().iterator();
298                         while (entries.hasNext()) {
299                                 Entry<String, FileOption> entry = entries.next();
300                                 FileOption fileOption = entry.getValue();
301                                 if (fileOption.isCustom()) {
302                                         SimpleXML fileOptionNode = fileOptionsNode.append("file-option");
303                                         fileOptionNode.append("filename", entry.getKey());
304                                         fileOptionNode.append("insert", String.valueOf(fileOption.isInsert()));
305                                         fileOptionNode.append("custom-key", fileOption.getCustomKey());
306                                         fileOptionNode.append("mime-type", fileOption.getMimeType());
307                                         fileOptionNode.append("container", fileOption.getContainer());
308                                         fileOptionNode.append("replace-edition", String.valueOf(fileOption.getReplaceEdition()));
309                                         fileOptionNode.append("edition-range", String.valueOf(fileOption.getEditionRange()));
310                                 }
311                         }
312                 }
313                 rootNode.replace(projectsNode);
314         }
315
316         public Locale getLocale() {
317                 String language = getNodeValue(new String[] { "i18n", "language" }, "en");
318                 String country = getNodeValue(new String[] { "i18n", "country" }, null);
319                 if (country != null) {
320                         return new Locale(language, country);
321                 }
322                 return new Locale(language);
323         }
324
325         public void setLocale(Locale locale) {
326                 SimpleXML i18nNode = new SimpleXML("i18n");
327                 if (locale.getCountry().length() != 0) {
328                         i18nNode.append("country", locale.getCountry());
329                 }
330                 i18nNode.append("language", locale.getLanguage());
331                 rootNode.replace(i18nNode);
332                 return;
333         }
334         
335         public Node[] getNodes() {
336                 SimpleXML nodesNode = rootNode.getNode("nodes");
337                 if (nodesNode == null) {
338                         String hostname = getNodeAddress();
339                         int port = getNodePort();
340                         if (hostname == null) {
341                                 hostname = "127.0.0.1";
342                                 port = 9481;
343                         }
344                         return new Node[] { new Node(hostname, port, "Node") };
345                 }
346                 SimpleXML[] nodeNodes = nodesNode.getNodes("node");
347                 Node[] returnNodes = new Node[nodeNodes.length];
348                 int nodeIndex = 0;
349                 for (SimpleXML nodeNode: nodeNodes) {
350                         String name = nodeNode.getNode("name").getValue();
351                         String hostname = nodeNode.getNode("hostname").getValue();
352                         int port = Integer.parseInt(nodeNode.getNode("port").getValue());
353                         Node node = new Node(hostname, port, name);
354                         returnNodes[nodeIndex++] = node;
355                 }
356                 return returnNodes;
357         }
358         
359         public void setNodes(Node[] nodes) {
360                 SimpleXML nodesNode = new SimpleXML("nodes");
361                 for (Node node: nodes) {
362                         SimpleXML nodeNode = nodesNode.append("node");
363                         nodeNode.append("name", node.getName());
364                         nodeNode.append("hostname", node.getHostname());
365                         nodeNode.append("port", String.valueOf(node.getPort()));
366                 }
367                 rootNode.replace(nodesNode);
368                 rootNode.remove("node-address");
369                 rootNode.remove("node-port");
370         }
371
372         public void setSelectedNode(Node selectedNode) {
373                 SimpleXML selectedNodeNode = new SimpleXML("selected-node");
374                 selectedNodeNode.append("name", selectedNode.getName());
375                 selectedNodeNode.append("hostname", selectedNode.getHostname());
376                 selectedNodeNode.append("port", String.valueOf(selectedNode.getPort()));
377                 rootNode.replace(selectedNodeNode);
378         }
379         
380         public Node getSelectedNode() {
381                 SimpleXML selectedNodeNode = rootNode.getNode("selected-node");
382                 if (selectedNodeNode == null) {
383                         String hostname = getNodeAddress();
384                         int port = getNodePort();
385                         if (hostname == null) {
386                                 hostname = "127.0.0.1";
387                                 port = 9481;
388                         }
389                         return new Node(hostname, port, "Node");
390                 }
391                 String name = selectedNodeNode.getNode("name").getValue();
392                 String hostname = selectedNodeNode.getNode("hostname").getValue();
393                 int port = Integer.valueOf(selectedNodeNode.getNode("port").getValue());
394                 return new Node(hostname, port, name);
395         }
396         
397 }