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