comparison dwtx/jface/text/templates/persistence/TemplateReaderWriter.d @ 129:eb30df5ca28b

Added JFace Text sources
author Frank Benoit <benoit@tionex.de>
date Sat, 23 Aug 2008 19:10:48 +0200
parents
children c4fb132a086c
comparison
equal deleted inserted replaced
128:8df1d4193877 129:eb30df5ca28b
1 /*******************************************************************************
2 * Copyright (c) 2000, 2008 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * IBM Corporation - initial API and implementation
10 * Port to the D programming language:
11 * Frank Benoit <benoit@tionex.de>
12 *******************************************************************************/
13 module dwtx.jface.text.templates.persistence.TemplateReaderWriter;
14
15 import dwt.dwthelper.utils;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStream;
20 import java.io.Reader;
21 import java.io.Writer;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.MissingResourceException;
26 import java.util.ResourceBundle;
27 import java.util.Set;
28
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
32 import javax.xml.transform.OutputKeys;
33 import javax.xml.transform.Transformer;
34 import javax.xml.transform.TransformerException;
35 import javax.xml.transform.TransformerFactory;
36 import javax.xml.transform.dom.DOMSource;
37 import javax.xml.transform.stream.StreamResult;
38
39 import org.w3c.dom.Attr;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.NamedNodeMap;
42 import org.w3c.dom.Node;
43 import org.w3c.dom.NodeList;
44 import org.w3c.dom.Text;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.SAXException;
47
48 import dwtx.core.runtime.Assert;
49 import dwtx.jface.text.templates.Template;
50
51 /**
52 * Serializes templates as character or byte stream and reads the same format
53 * back.
54 * <p>
55 * Clients may instantiate this class, it is not intended to be
56 * subclassed.</p>
57 *
58 * @since 3.0
59 * @noextend This class is not intended to be subclassed by clients.
60 */
61 public class TemplateReaderWriter {
62
63 private static final String TEMPLATE_ROOT = "templates"; //$NON-NLS-1$
64 private static final String TEMPLATE_ELEMENT = "template"; //$NON-NLS-1$
65 private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
66 private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
67 private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
68 private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
69 private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
70 private static final String DELETED_ATTRIBUTE= "deleted"; //$NON-NLS-1$
71 /**
72 * @since 3.1
73 */
74 private static final String AUTO_INSERTABLE_ATTRIBUTE= "autoinsert"; //$NON-NLS-1$
75
76 /**
77 * Create a new instance.
78 */
79 public TemplateReaderWriter() {
80 }
81
82 /**
83 * Reads templates from a reader and returns them. The reader must present
84 * a serialized form as produced by the <code>save</code> method.
85 *
86 * @param reader the reader to read templates from
87 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
88 * @throws IOException if reading from the stream fails
89 */
90 public TemplatePersistenceData[] read(Reader reader) throws IOException {
91 return read(reader, null);
92 }
93
94 /**
95 * Reads the template with identifier <code>id</code> from a reader and
96 * returns it. The reader must present a serialized form as produced by the
97 * <code>save</code> method.
98 *
99 * @param reader the reader to read templates from
100 * @param id the id of the template to return
101 * @return the read template, encapsulated in an instances of
102 * <code>TemplatePersistenceData</code>
103 * @throws IOException if reading from the stream fails
104 * @since 3.1
105 */
106 public TemplatePersistenceData readSingle(Reader reader, String id) throws IOException {
107 TemplatePersistenceData[] datas= read(new InputSource(reader), null, id);
108 if (datas.length > 0)
109 return datas[0];
110 return null;
111 }
112
113 /**
114 * Reads templates from a stream and adds them to the templates.
115 *
116 * @param reader the reader to read templates from
117 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
118 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
119 * @throws IOException if reading from the stream fails
120 */
121 public TemplatePersistenceData[] read(Reader reader, ResourceBundle bundle) throws IOException {
122 return read(new InputSource(reader), bundle, null);
123 }
124
125 /**
126 * Reads templates from a stream and adds them to the templates.
127 *
128 * @param stream the byte stream to read templates from
129 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
130 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
131 * @throws IOException if reading from the stream fails
132 */
133 public TemplatePersistenceData[] read(InputStream stream, ResourceBundle bundle) throws IOException {
134 return read(new InputSource(stream), bundle, null);
135 }
136
137 /**
138 * Reads templates from an <code>InputSource</code> and adds them to the templates.
139 *
140 * @param source the input source
141 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
142 * @param singleId the template id to extract, or <code>null</code> to read in all templates
143 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
144 * @throws IOException if reading from the stream fails
145 */
146 private TemplatePersistenceData[] read(InputSource source, ResourceBundle bundle, String singleId) throws IOException {
147 try {
148 Collection templates= new ArrayList();
149 Set ids= new HashSet();
150
151 DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
152 DocumentBuilder parser= factory.newDocumentBuilder();
153 Document document= parser.parse(source);
154
155 NodeList elements= document.getElementsByTagName(TEMPLATE_ELEMENT);
156
157 int count= elements.getLength();
158 for (int i= 0; i !is count; i++) {
159 Node node= elements.item(i);
160 NamedNodeMap attributes= node.getAttributes();
161
162 if (attributes is null)
163 continue;
164
165 String id= getStringValue(attributes, ID_ATTRIBUTE, null);
166 if (id !is null && ids.contains(id))
167 throw new IOException(TemplatePersistenceMessages.getString("TemplateReaderWriter.duplicate.id")); //$NON-NLS-1$
168
169 if (singleId !is null && !singleId.equals(id))
170 continue;
171
172 bool deleted = getBooleanValue(attributes, DELETED_ATTRIBUTE, false);
173
174 String name= getStringValue(attributes, NAME_ATTRIBUTE);
175 name= translateString(name, bundle);
176
177 String description= getStringValue(attributes, DESCRIPTION_ATTRIBUTE, ""); //$NON-NLS-1$
178 description= translateString(description, bundle);
179
180 String context= getStringValue(attributes, CONTEXT_ATTRIBUTE);
181
182 if (name is null || context is null)
183 throw new IOException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.missing_attribute")); //$NON-NLS-1$
184
185 bool enabled = getBooleanValue(attributes, ENABLED_ATTRIBUTE, true);
186 bool autoInsertable= getBooleanValue(attributes, AUTO_INSERTABLE_ATTRIBUTE, true);
187
188 StringBuffer buffer= new StringBuffer();
189 NodeList children= node.getChildNodes();
190 for (int j= 0; j !is children.getLength(); j++) {
191 String value= children.item(j).getNodeValue();
192 if (value !is null)
193 buffer.append(value);
194 }
195 String pattern= buffer.toString();
196 pattern= translateString(pattern, bundle);
197
198 Template template= new Template(name, description, context, pattern, autoInsertable);
199 TemplatePersistenceData data= new TemplatePersistenceData(template, enabled, id);
200 data.setDeleted(deleted);
201
202 templates.add(data);
203
204 if (singleId !is null && singleId.equals(id))
205 break;
206 }
207
208 return (TemplatePersistenceData[]) templates.toArray(new TemplatePersistenceData[templates.size()]);
209
210 } catch (ParserConfigurationException e) {
211 Assert.isTrue(false);
212 } catch (SAXException e) {
213 Throwable t= e.getCause();
214 if (t instanceof IOException)
215 throw (IOException) t;
216 else if (t !is null)
217 throw new IOException(t.getMessage());
218 else
219 throw new IOException(e.getMessage());
220 }
221
222 return null; // dummy
223 }
224
225 /**
226 * Saves the templates as XML, encoded as UTF-8 onto the given byte stream.
227 *
228 * @param templates the templates to save
229 * @param stream the byte output to write the templates to in XML
230 * @throws IOException if writing the templates fails
231 */
232 public void save(TemplatePersistenceData[] templates, OutputStream stream) throws IOException {
233 save(templates, new StreamResult(stream));
234 }
235
236 /**
237 * Saves the templates as XML.
238 *
239 * @param templates the templates to save
240 * @param writer the writer to write the templates to in XML
241 * @throws IOException if writing the templates fails
242 */
243 public void save(TemplatePersistenceData[] templates, Writer writer) throws IOException {
244 save(templates, new StreamResult(writer));
245 }
246
247 /**
248 * Saves the templates as XML.
249 *
250 * @param templates the templates to save
251 * @param result the stream result to write to
252 * @throws IOException if writing the templates fails
253 */
254 private void save(TemplatePersistenceData[] templates, StreamResult result) throws IOException {
255 try {
256 DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
257 DocumentBuilder builder= factory.newDocumentBuilder();
258 Document document= builder.newDocument();
259
260 Node root= document.createElement(TEMPLATE_ROOT);
261 document.appendChild(root);
262
263 for (int i= 0; i < templates.length; i++) {
264 TemplatePersistenceData data= templates[i];
265 Template template= data.getTemplate();
266
267 Node node= document.createElement(TEMPLATE_ELEMENT);
268 root.appendChild(node);
269
270 NamedNodeMap attributes= node.getAttributes();
271
272 String id= data.getId();
273 if (id !is null) {
274 Attr idAttr= document.createAttribute(ID_ATTRIBUTE);
275 idAttr.setValue(id);
276 attributes.setNamedItem(idAttr);
277 }
278
279 if (template !is null) {
280 Attr name= document.createAttribute(NAME_ATTRIBUTE);
281 name.setValue(template.getName());
282 attributes.setNamedItem(name);
283 }
284
285 if (template !is null) {
286 Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
287 description.setValue(template.getDescription());
288 attributes.setNamedItem(description);
289 }
290
291 if (template !is null) {
292 Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
293 context.setValue(template.getContextTypeId());
294 attributes.setNamedItem(context);
295 }
296
297 Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE);
298 enabled.setValue(data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false));
299 attributes.setNamedItem(enabled);
300
301 Attr deleted= document.createAttribute(DELETED_ATTRIBUTE);
302 deleted.setValue(data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false));
303 attributes.setNamedItem(deleted);
304
305 if (template !is null) {
306 Attr autoInsertable= document.createAttribute(AUTO_INSERTABLE_ATTRIBUTE);
307 autoInsertable.setValue(template.isAutoInsertable() ? Boolean.toString(true) : Boolean.toString(false));
308 attributes.setNamedItem(autoInsertable);
309 }
310
311 if (template !is null) {
312 Text pattern= document.createTextNode(template.getPattern());
313 node.appendChild(pattern);
314 }
315 }
316
317
318 Transformer transformer=TransformerFactory.newInstance().newTransformer();
319 transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
320 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
321 DOMSource source = new DOMSource(document);
322
323 transformer.transform(source, result);
324
325 } catch (ParserConfigurationException e) {
326 Assert.isTrue(false);
327 } catch (TransformerException e) {
328 if (e.getException() instanceof IOException)
329 throw (IOException) e.getException();
330 Assert.isTrue(false);
331 }
332 }
333
334 private bool getBooleanValue(NamedNodeMap attributes, String attribute, bool defaultValue) throws SAXException {
335 Node enabledNode= attributes.getNamedItem(attribute);
336 if (enabledNode is null)
337 return defaultValue;
338 else if (enabledNode.getNodeValue().equals(Boolean.toString(true)))
339 return true;
340 else if (enabledNode.getNodeValue().equals(Boolean.toString(false)))
341 return false;
342 else
343 throw new SAXException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.illegal_boolean_attribute")); //$NON-NLS-1$
344 }
345
346 private String getStringValue(NamedNodeMap attributes, String name) throws SAXException {
347 String val= getStringValue(attributes, name, null);
348 if (val is null)
349 throw new SAXException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.missing_attribute")); //$NON-NLS-1$
350 return val;
351 }
352
353 private String getStringValue(NamedNodeMap attributes, String name, String defaultValue) {
354 Node node= attributes.getNamedItem(name);
355 return node is null ? defaultValue : node.getNodeValue();
356 }
357
358 private String translateString(String str, ResourceBundle bundle) {
359 if (bundle is null)
360 return str;
361
362 int idx= str.indexOf('%');
363 if (idx is -1) {
364 return str;
365 }
366 StringBuffer buf= new StringBuffer();
367 int k= 0;
368 while (idx !is -1) {
369 buf.append(str.substring(k, idx));
370 for (k= idx + 1; k < str.length() && !Character.isWhitespace(str.charAt(k)); k++) {
371 // loop
372 }
373 String key= str.substring(idx + 1, k);
374 buf.append(getBundleString(key, bundle));
375 idx= str.indexOf('%', k);
376 }
377 buf.append(str.substring(k));
378 return buf.toString();
379 }
380
381 private String getBundleString(String key, ResourceBundle bundle) {
382 if (bundle !is null) {
383 try {
384 return bundle.getString(key);
385 } catch (MissingResourceException e) {
386 return '!' + key + '!';
387 }
388 }
389 return TemplatePersistenceMessages.getString(key); // default messages
390 }
391 }
392