Skip to main content
summaryrefslogtreecommitdiffstats
blob: b5f5dadeae779b61c38967a247024751b09e7268 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*******************************************************************************
 * Copyright (c) 2000, 2003 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jface.text.templates.persistence;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.templates.Template;

/**
 * Serializes templates as character stream and reads the same format back.
 * Clients may instantiate this class, it is not intended to be subclassed.
 * 
 * @since 3.0
 */
public class TemplateReaderWriter {

	private static final String TEMPLATE_ROOT = "templates"; //$NON-NLS-1$
	private static final String TEMPLATE_ELEMENT = "template"; //$NON-NLS-1$
	private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
	private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
	private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
	private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
	private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
	private static final String DELETED_ATTRIBUTE= "deleted"; //$NON-NLS-1$
	
	/**
	 * Create a new instance.
	 */
	public TemplateReaderWriter() {
	}
	
	/**
	 * Reads templates from a reader and returns them. The reader must present
	 * a serialized form as produced by the <code>save</code> method.
	 * 
	 * @param reader the reader to read templates from
	 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
	 * @throws IOException if reading from the stream fails 
	 */	
	public TemplatePersistenceData[] read(Reader reader) throws IOException {
		return read(reader, null);
	}
	
	/**
	 * Reads templates from a stream and adds them to the templates.
	 * 
	 * @param reader the reader to read templates from
	 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
	 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
	 * @throws IOException if reading from the stream fails 
	 */	
	public TemplatePersistenceData[] read(Reader reader, ResourceBundle bundle) throws IOException {
		return read(new InputSource(reader), bundle);
	}
	
	/**
	 * Reads templates from a stream and adds them to the templates.
	 * 
	 * @param stream the byte stream to read templates from
	 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
	 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
	 * @throws IOException if reading from the stream fails 
	 */	
	public TemplatePersistenceData[] read(InputStream stream, ResourceBundle bundle) throws IOException {
		return read(new InputSource(stream), bundle);
	}
	
	/**
	 * Reads templates from an InputSource and adds them to the templates.
	 * 
	 * @param source the input source
	 * @param bundle a resource bundle to use for translating the read templates, or <code>null</code> if no translation should occur
	 * @return the read templates, encapsulated in instances of <code>TemplatePersistenceData</code>
	 * @throws IOException if reading from the stream fails 
	 */	
	private TemplatePersistenceData[] read(InputSource source, ResourceBundle bundle) throws IOException {
		try {
			Collection templates= new ArrayList();
			Set ids= new HashSet();
			
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder parser= factory.newDocumentBuilder();		
			Document document= parser.parse(source);
			
			NodeList elements= document.getElementsByTagName(TEMPLATE_ELEMENT);
			
			int count= elements.getLength();
			for (int i= 0; i != count; i++) {
				Node node= elements.item(i);					
				NamedNodeMap attributes= node.getAttributes();

				if (attributes == null)
					continue;

				String id= getStringValue(attributes, ID_ATTRIBUTE, null);
				if (id != null && ids.contains(id))
					throw new IOException(TemplatePersistenceMessages.getString("TemplateReaderWriter.duplicate.id")); //$NON-NLS-1$
				
				boolean deleted = getBooleanValue(attributes, DELETED_ATTRIBUTE, false);
				
				String name= getStringValue(attributes, NAME_ATTRIBUTE);
				name= translateString(name, bundle);

				String description= getStringValue(attributes, DESCRIPTION_ATTRIBUTE, ""); //$NON-NLS-1$
				description= translateString(description, bundle);
				
				String context= getStringValue(attributes, CONTEXT_ATTRIBUTE);

				if (name == null || context == null)
					throw new IOException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.missing_attribute")); //$NON-NLS-1$

				boolean enabled = getBooleanValue(attributes, ENABLED_ATTRIBUTE, true);
				
				StringBuffer buffer= new StringBuffer();
				NodeList children= node.getChildNodes();
				for (int j= 0; j != children.getLength(); j++) {
					String value= children.item(j).getNodeValue();
					if (value != null)
						buffer.append(value);
				}
				String pattern= buffer.toString();
				pattern= translateString(pattern, bundle);

				Template template= new Template(name, description, context, pattern);
				TemplatePersistenceData data= new TemplatePersistenceData(template, enabled, id);
				data.setDeleted(deleted);
				
				templates.add(data);
			}
			
			return (TemplatePersistenceData[]) templates.toArray(new TemplatePersistenceData[templates.size()]);
			
		} catch (ParserConfigurationException e) {
			Assert.isTrue(false);
		} catch (SAXException e) {
			Throwable t= e.getCause();
			if (t instanceof IOException)
				throw (IOException) t;
			else
				throw new IOException(t.getMessage());
		}
		
		return null; // dummy
	}
	
	/**
	 * Saves the templates as XML, encoded as UTF-8 onto the given byte stream.
	 * 
	 * @param templates the templates to save
	 * @param stream the byte output to write the templates to in XML
	 * @throws IOException if writing the templates fails 
	 */
	public void save(TemplatePersistenceData[] templates, OutputStream stream) throws IOException {
		save(templates, new StreamResult(stream));
	}
	
	/**
	 * Saves the templates as XML.
	 * 
	 * @param templates the templates to save
	 * @param writer the writer to write the templates to in XML
	 * @throws IOException if writing the templates fails 
	 */
	public void save(TemplatePersistenceData[] templates, Writer writer) throws IOException {
		save(templates, new StreamResult(writer));
	}
	
	/**
	 * Saves the templates as XML.
	 * 
	 * @param templates the templates to save
	 * @param result the stream result to write to
	 * @throws IOException if writing the templates fails 
	 */
	private void save(TemplatePersistenceData[] templates, StreamResult result) throws IOException {
		try {
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder builder= factory.newDocumentBuilder();		
			Document document= builder.newDocument();

			Node root= document.createElement(TEMPLATE_ROOT); //$NON-NLS-1$
			document.appendChild(root);
			
			for (int i= 0; i < templates.length; i++) {
				TemplatePersistenceData data= templates[i];
				Template template= data.getTemplate();
				
				Node node= document.createElement(TEMPLATE_ELEMENT);
				root.appendChild(node);
				
				NamedNodeMap attributes= node.getAttributes();
				
				String id= data.getId();
				if (id != null) {
					Attr idAttr= document.createAttribute(ID_ATTRIBUTE);
					idAttr.setValue(id);
					attributes.setNamedItem(idAttr);
				}
				
				if (template != null) {
					Attr name= document.createAttribute(NAME_ATTRIBUTE);
					name.setValue(template.getName());
					attributes.setNamedItem(name);
				}
	
				if (template != null) {
					Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
					description.setValue(template.getDescription());
					attributes.setNamedItem(description);
				}
	
				if (template != null) {
					Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
					context.setValue(template.getContextTypeId());
					attributes.setNamedItem(context);
				}
				
				Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE);
				enabled.setValue(data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false)); //$NON-NLS-1$ //$NON-NLS-2$
				attributes.setNamedItem(enabled);
				
				Attr deleted= document.createAttribute(DELETED_ATTRIBUTE);
				deleted.setValue(data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false)); //$NON-NLS-1$ //$NON-NLS-2$
				attributes.setNamedItem(deleted);
				
				if (template != null) {
					Text pattern= document.createTextNode(template.getPattern());
					node.appendChild(pattern);			
				}
			}		
			
			
			Transformer transformer=TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			DOMSource source = new DOMSource(document);

			transformer.transform(source, result);

		} catch (ParserConfigurationException e) {
			Assert.isTrue(false);
		} catch (TransformerException e) {
			if (e.getException() instanceof IOException)
				throw (IOException) e.getException();
			Assert.isTrue(false);
		}		
	}

	private boolean getBooleanValue(NamedNodeMap attributes, String attribute, boolean defaultValue) throws SAXException {
		Node enabledNode= attributes.getNamedItem(attribute);
		if (enabledNode == null)
			return defaultValue;
		else if (enabledNode.getNodeValue().equals(Boolean.toString(true)))
			return true;
		else if (enabledNode.getNodeValue().equals(Boolean.toString(false)))
			return false;
		else
			throw new SAXException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.illegal_boolean_attribute")); //$NON-NLS-1$
	}
	
	private String getStringValue(NamedNodeMap attributes, String name) throws SAXException {
		String val= getStringValue(attributes, name, null);
		if (val == null)
			throw new SAXException(TemplatePersistenceMessages.getString("TemplateReaderWriter.error.missing_attribute")); //$NON-NLS-1$
		return val;
	}

	private String getStringValue(NamedNodeMap attributes, String name, String defaultValue) {
		Node node= attributes.getNamedItem(name);
		return node == null	? defaultValue : node.getNodeValue();
	}

	private String translateString(String str, ResourceBundle bundle) {
		if (bundle == null)
			return str;
		
		int idx= str.indexOf('%');
		if (idx == -1) {
			return str;
		}
		StringBuffer buf= new StringBuffer();
		int k= 0;
		while (idx != -1) {
			buf.append(str.substring(k, idx));
			for (k= idx + 1; k < str.length() && !Character.isWhitespace(str.charAt(k)); k++) {
				// loop
			}
			String key= str.substring(idx + 1, k);
			buf.append(getBundleString(key, bundle));
			idx= str.indexOf('%', k);
		}
		buf.append(str.substring(k));
		return buf.toString();
	}
	
	private String getBundleString(String key, ResourceBundle bundle) {
		if (bundle != null) {
			try {
				return bundle.getString(key);
			} catch (MissingResourceException e) {
				return '!' + key + '!';
			}
		} else
			return TemplatePersistenceMessages.getString(key); // default messages
	}
}

Back to the top