Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 17a0bd3839e0d31d88c16e29de0c95a77c94ad82 (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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*******************************************************************************
 * 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.team.internal.core;

import java.io.*;
import java.util.ArrayList;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.team.core.TeamException;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This class represents the default implementation of the
 * <code>IMemento</code> interface.
 * <p>
 * This class is not intended to be extended by clients.
 * </p>
 * [Note: This class has been copied from org.eclipse.ui to get a quick and
 * dirty xml input/output code. This should be purged once the settings
 * work is complete]
 * @see IMemento
 */
public final class XMLMemento implements IMemento {
	private Document factory;
	private Element element;

	/**
	 * Creates a <code>Document</code> from the <code>Reader</code>
	 * and returns a memento on the first <code>Element</code> for reading
	 * the document.
	 * <p>
	 * Same as calling createReadRoot(reader, null)
	 * </p>
	 * 
	 * @param reader the <code>Reader</code> used to create the memento's document
	 * @return a memento on the first <code>Element</code> for reading the document
	 * @throws <code>WorkbenchException</code> if IO problems, invalid format, or no element.
	 */
	public static XMLMemento createReadRoot(Reader reader) throws TeamException {
		return createReadRoot(reader, null);
	}

	/**
	 * Creates a <code>Document</code> from the <code>Reader</code>
	 * and returns a memento on the first <code>Element</code> for reading
	 * the document.
	 * 
	 * @param reader the <code>Reader</code> used to create the memento's document
	 * @param baseDir the directory used to resolve relative file names
	 * 		in the XML document. This directory must exist and include the
	 * 		trailing separator. The directory format, including the separators,
	 * 		must be valid for the platform. Can be <code>null</code> if not
	 * 		needed.
	 * @return a memento on the first <code>Element</code> for reading the document
	 * @throws <code>WorkbenchException</code> if IO problems, invalid format, or no element.
	 */
	public static XMLMemento createReadRoot(Reader reader, String baseDir) throws TeamException {
		String messageKey = "XMLMemento.noElement"; //$NON-NLS-1$
		Exception exception = null;
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder parser = factory.newDocumentBuilder();
			InputSource source = new InputSource(reader);
			if (baseDir != null)
				source.setSystemId(baseDir);
			Document document = parser.parse(source);
			NodeList list = document.getChildNodes();
			for (int i = 0; i < list.getLength(); i++) {
				Node node = list.item(i);
				if (node instanceof Element)
					return new XMLMemento(document, (Element) node);
			}
		} catch (ParserConfigurationException e) {
			exception = e;
			messageKey = "XMLMemento.parserConfigError"; //$NON-NLS-1$
		} catch (IOException e) {
			exception = e;
			messageKey = "XMLMemento.ioError"; //$NON-NLS-1$
		} catch (SAXException e) {
			exception = e;
			messageKey = "XMLMemento.formatError"; //$NON-NLS-1$
		}
		
		String problemText = null;
		if (exception != null)
			problemText = exception.getMessage();
		//if (problemText == null || problemText.length() == 0)
		//	problemText = TeamException.getString(messageKey);
		throw new TeamException(problemText);
	}
	
	/**
	 * Returns a root memento for writing a document.
	 * 
	 * @param type the element node type to create on the document
	 * @return the root memento for writing a document
	 */
	public static XMLMemento createWriteRoot(String type) {
        Document document;
        try {
            document = DocumentBuilderFactory
                            .newInstance()
                            .newDocumentBuilder()
                            .newDocument();
            Element element = document.createElement(type);
            document.appendChild(element);
            return new XMLMemento(document, element);            
        }
        catch (ParserConfigurationException e) {
            throw new Error(e);
        }
	}
	
	/**
	 * Creates a memento for the specified document and element.
	 * <p>
	 * Clients should use <code>createReadRoot</code> and
	 * <code>createWriteRoot</code> to create the initial
	 * memento on a document.
	 * </p>
	 * 
	 * @param document the document for the memento
	 * @param element the element node for the memento
	 */
	public XMLMemento(Document document, Element element) {
		super();
		this.factory = document;
		this.element = element;
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public IMemento createChild(String type) {
		Element child = factory.createElement(type);
		element.appendChild(child);
		return new XMLMemento(factory, child);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public IMemento createChild(String type, String id) {
		Element child = factory.createElement(type);
		child.setAttribute(TAG_ID, id == null ? "" : id); //$NON-NLS-1$
		element.appendChild(child);
		return new XMLMemento(factory, child);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public IMemento copyChild(IMemento child) {
		Element childElement = ((XMLMemento) child).element;
		Element newElement = (Element) factory.importNode(childElement, true);
		element.appendChild(newElement);
		return new XMLMemento(factory, newElement);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public IMemento getChild(String type) {

		// Get the nodes.
		NodeList nodes = element.getChildNodes();
		int size = nodes.getLength();
		if (size == 0)
			return null;

		// Find the first node which is a child of this node.
		for (int nX = 0; nX < size; nX++) {
			Node node = nodes.item(nX);
			if (node instanceof Element) {
				Element element = (Element) node;
				if (element.getNodeName().equals(type))
					return new XMLMemento(factory, element);
			}
		}

		// A child was not found.
		return null;
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public IMemento[] getChildren(String type) {

		// Get the nodes.
		NodeList nodes = element.getChildNodes();
		int size = nodes.getLength();
		if (size == 0)
			return new IMemento[0];

		// Extract each node with given type.
		ArrayList list = new ArrayList(size);
		for (int nX = 0; nX < size; nX++) {
			Node node = nodes.item(nX);
			if (node instanceof Element) {
				Element element = (Element) node;
				if (element.getNodeName().equals(type))
					list.add(element);
			}
		}

		// Create a memento for each node.
		size = list.size();
		IMemento[] results = new IMemento[size];
		for (int x = 0; x < size; x++) {
			results[x] = new XMLMemento(factory, (Element) list.get(x));
		}
		return results;
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public Float getFloat(String key) {
		Attr attr = element.getAttributeNode(key);
		if (attr == null)
			return null;
		String strValue = attr.getValue();
		try {
			return new Float(strValue);
		} catch (NumberFormatException e) {
			TeamPlugin.log(IStatus.ERROR, "Memento problem - Invalid float for key: " //$NON-NLS-1$
			+ key + " value: " + strValue, null); //$NON-NLS-1$
			return null;
		}
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public String getID() {
		return element.getAttribute(TAG_ID);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public Integer getInteger(String key) {
		Attr attr = element.getAttributeNode(key);
		if (attr == null)
			return null;
		String strValue = attr.getValue();
		try {
			return new Integer(strValue);
		} catch (NumberFormatException e) {
			TeamPlugin.log(IStatus.ERROR, "Memento problem - invalid integer for key: " + key //$NON-NLS-1$
			+ " value: " + strValue, null); //$NON-NLS-1$
			return null;
		}
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public String getString(String key) {
		Attr attr = element.getAttributeNode(key);
		if (attr == null)
			return null;
		return attr.getValue();
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public String getTextData() {
		Text textNode = getTextNode();
		if (textNode != null) {
			return textNode.getData();
		} else {
			return null;
		}
	}

	/**
	 * Returns the Text node of the memento. Each memento is allowed only 
	 * one Text node.
	 * 
	 * @return the Text node of the memento, or <code>null</code> if
	 * the memento has no Text node.
	 */
	private Text getTextNode() {
		// Get the nodes.
		NodeList nodes = element.getChildNodes();
		int size = nodes.getLength();
		if (size == 0)
			return null;
		for (int nX = 0; nX < size; nX++) {
			Node node = nodes.item(nX);
			if (node instanceof Text) {
				return (Text) node;
			}
		}
		// a Text node was not found
		return null;
	}

	/**
	 * Places the element's attributes into the document.
	 */
	private void putElement(Element element) {
		NamedNodeMap nodeMap = element.getAttributes();
		int size = nodeMap.getLength();
		for (int i = 0; i < size; i++) {
			Attr attr = (Attr) nodeMap.item(i);
			putString(attr.getName(), attr.getValue());
		}

		NodeList nodes = element.getChildNodes();
		size = nodes.getLength();
		for (int i = 0; i < size; i++) {
			Node node = nodes.item(i);
			if (node instanceof Element) {
				XMLMemento child = (XMLMemento) createChild(node.getNodeName());
				child.putElement((Element) node);
			}
		}
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public void putFloat(String key, float f) {
		element.setAttribute(key, String.valueOf(f));
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public void putInteger(String key, int n) {
		element.setAttribute(key, String.valueOf(n));
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public void putMemento(IMemento memento) {
		putElement(((XMLMemento) memento).element);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public void putString(String key, String value) {
		if (value == null)
			return;
		element.setAttribute(key, value);
	}
	
	/* (non-Javadoc)
	 * Method declared in IMemento.
	 */
	public void putTextData(String data) {
		Text textNode = getTextNode();
		if (textNode == null) {
			textNode = factory.createTextNode(data);
			element.appendChild(textNode);
		} else {
			textNode.setData(data);
		}
	}
	
	/**
	 * Saves this memento's document current values to the
	 * specified writer. 
	 * 
	 * @param writer the writer used to save the memento's document
     * @throws IOException if there is a problem serializing the document to the stream.
	 */
	public void save(Writer writer) throws IOException {
        Result result = new StreamResult(writer);
        Source source = new DOMSource(factory);
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
            transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
            transformer.transform(source, result);            
        }
        catch (TransformerConfigurationException e) {
            throw (IOException) (new IOException().initCause(e));
        }
        catch (TransformerException e) {
            throw (IOException) (new IOException().initCause(e));
        }
	}
}

Back to the top