View Javadoc

1   /*
2      Copyright 2007 Ivo Limmen
3   
4      Licensed under the Apache License, Version 2.0 (the "License");
5      you may not use this file except in compliance with the License.
6      You may obtain a copy of the License at
7   
8          http://www.apache.org/licenses/LICENSE-2.0
9   
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15  */
16  package org.limmen.crs.storage.xml;
17  
18  import java.io.File;
19  import java.io.FileOutputStream;
20  import java.io.IOException;
21  import java.io.OutputStream;
22  import java.util.List;
23  
24  import javax.xml.parsers.DocumentBuilder;
25  import javax.xml.parsers.DocumentBuilderFactory;
26  import javax.xml.parsers.ParserConfigurationException;
27  import javax.xml.transform.OutputKeys;
28  import javax.xml.transform.Transformer;
29  import javax.xml.transform.TransformerConfigurationException;
30  import javax.xml.transform.TransformerException;
31  import javax.xml.transform.TransformerFactory;
32  import javax.xml.transform.TransformerFactoryConfigurationError;
33  import javax.xml.transform.dom.DOMSource;
34  import javax.xml.transform.stream.StreamResult;
35  
36  import org.limmen.crs.exception.SectionNotFoundException;
37  import org.limmen.crs.model.Configuration;
38  import org.limmen.crs.model.Documentation;
39  import org.limmen.crs.model.Section;
40  import org.limmen.crs.model.Setting;
41  import org.w3c.dom.Document;
42  import org.w3c.dom.Element;
43  
44  public class ConfigurationXMLWriter {
45  
46  	public static void write(File aFile, Configuration aConfiguration) throws IOException {
47  
48  		FileOutputStream fileOutputStream = null;
49  
50  		try {
51  
52  			fileOutputStream = new FileOutputStream(aFile);
53  
54  			write(fileOutputStream, aConfiguration);
55        }
56  		finally {
57  
58           try {
59  	         fileOutputStream.flush();
60  	         fileOutputStream.close();
61           }
62           catch (Exception e) {
63  
64           	// ignore
65           }
66  		}
67  	}
68  
69  	public static void write(OutputStream outputStream, Configuration aConfiguration) throws IOException {
70  
71  		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
72  		DocumentBuilder builder = null;
73  
74        try {
75  
76  	      builder = factory.newDocumentBuilder();
77        }
78        catch (ParserConfigurationException e) {
79  
80  	      throw new IOException(e);
81        }
82  
83  		Document document = builder.newDocument();
84  
85  		Element configElement = document.createElement("configuration");
86  
87  		configElement.setAttribute("id", aConfiguration.getId());
88  
89  		if (aConfiguration.getBaseConfiguration() != null) {
90  
91  			if (!aConfiguration.getId().equals(aConfiguration.getBaseConfiguration().getId())) {
92  
93  				Element baseConfig = document.createElement("base");
94  
95  				baseConfig.appendChild(
96  						document.createTextNode(
97  								aConfiguration.getBaseConfiguration().getId()));
98  
99  				configElement.appendChild(baseConfig);
100 			}
101 			else {
102 
103 				// TODO: Add a warning for a circular configuration.
104 			}
105 		}
106 
107 		writeDocumentation(document, configElement, aConfiguration.getDocumentation());
108 
109       writeSections(document, configElement, aConfiguration);
110 
111 		document.appendChild(configElement);
112 
113 		document.normalize();
114 
115 		Transformer transformer = null;
116 
117       try {
118 
119       	transformer = TransformerFactory.newInstance().newTransformer();
120       }
121       catch (TransformerConfigurationException e) {
122 
123       	throw new IOException(e);
124       }
125       catch (TransformerFactoryConfigurationError e) {
126 
127       	throw new IOException(e);
128       }
129 
130       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
131       transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
132       transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
133 
134 		//	initialise StreamResult with File object to save to file
135 		StreamResult result = new StreamResult(outputStream);
136 		DOMSource source = new DOMSource(document);
137 
138 		try {
139 
140 			transformer.transform(source, result);
141       }
142 		catch (TransformerException e) {
143 
144       	throw new IOException(e);
145       }
146 	}
147 
148 	public static void write(String aFile, Configuration aConfiguration) throws IOException {
149 
150 		write(new File(aFile), aConfiguration);
151 	}
152 
153 	private static void writeDocumentation(Document document, Element root, List<Documentation> documentation) {
154 
155 		for (Documentation doc : documentation) {
156 
157 			Element docNode = document.createElement("documentation");
158 
159 			docNode.setAttribute("lang", doc.getLanguage());
160 
161 			docNode.appendChild(
162 					document.createTextNode(doc.getText()));
163 
164 			root.appendChild(docNode);
165 		}
166 	}
167 
168 	private static void writeSections(Document document, Element root, Configuration aConfiguration) {
169 
170 		for (Section section : aConfiguration.getSections()) {
171 
172 			Element sectionNode = document.createElement("section");
173 
174 			sectionNode.setAttribute("id", section.getId());
175 
176 			try {
177 
178 				writeDocumentation(document, sectionNode, aConfiguration.getDocumentation(section.getId()));
179          }
180          catch (SectionNotFoundException e) {
181 
182 	         e.printStackTrace();
183          }
184 
185 			writeSettings(document, sectionNode, aConfiguration, section.getId());
186 
187 			root.appendChild(sectionNode);
188 		}
189 	}
190 
191 	private static void writeSettings(Document document, Element root, Configuration aConfiguration, String aSectionId) {
192 
193 		try {
194 
195 	      for (Setting setting : aConfiguration.getSection(aSectionId).getSettings()) {
196 
197 	      	Element settingNode = document.createElement("setting");
198 
199 	      	settingNode.setAttribute("id", setting.getId());
200 
201 	      	try {
202 
203 	      		writeDocumentation(document, settingNode, aConfiguration.getDocumentation(aSectionId, setting.getId()));
204 	         }
205 	         catch (Exception e) {
206 
207 	            e.printStackTrace();
208 	         }
209 
210 	      	Element valueNode = document.createElement("value");
211 	      	valueNode.appendChild(document.createTextNode(setting.getValue()));
212 
213 	      	settingNode.appendChild(valueNode);
214 
215 	      	Element typeNode = document.createElement("type");
216 	      	typeNode.appendChild(document.createTextNode(setting.getType().name()));
217 
218 	      	settingNode.appendChild(typeNode);
219 
220 	      	root.appendChild(settingNode);
221 	      }
222       }
223       catch (Exception e) {
224 
225       	e.printStackTrace();
226       }
227 	}
228 }