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