Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 00f246a1c2923c25ee916d6f92ab2d60097e04d1 (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
/*******************************************************************************
 * Copyright (c) 2001, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Jens Lukowski/Innoopract - initial renaming/restructuring
 *     
 *******************************************************************************/
package org.eclipse.wst.sse.ui.preferences;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

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

import org.eclipse.wst.sse.core.preferences.PreferenceChangeListener;
import org.eclipse.wst.sse.ui.internal.Logger;
import org.eclipse.wst.sse.ui.nls.ResourceHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 * @deprecated no longer need a special PreferenceManager for our component.
 *             All preferences should be accessible using the base preference
 *             manager.
 */
public abstract class PreferenceManager {

	protected class EmptyNodeList implements NodeList {
		protected EmptyNodeList() {
			super();
		}

		public int getLength() {
			return 0;
		}

		public Node item(int param1) {
			return null;
		}
	}

	/**
	 * The PreferenceRuntimeException is often thrown by methods when a
	 * service we use throws a checked exception, but we want to convert and
	 * treat as a runtime exception.
	 */
	class PreferenceRuntimeException extends RuntimeException {
		/**
		 * Comment for <code>serialVersionUID</code>
		 */
		private static final long serialVersionUID = 1L;
		private Throwable originalException;

		public PreferenceRuntimeException() {
			super();
		}

		/**
		 * This form of the constructor is used to wrapper another exception.
		 */
		public PreferenceRuntimeException(Throwable t) {
			this();
			originalException = t;
		}

		public String getMessage() {
			String result = super.getMessage();
			if ((result != null) && (!result.endsWith("."))) //$NON-NLS-1$
				result = result + "."; //$NON-NLS-1$
			if (originalException != null) {
				String embeddedMessage = originalException.getMessage();
				embeddedMessage = originalException.getClass().getName() + ": " + originalException.getMessage(); //$NON-NLS-1$
				// not all exceptions have messages (e.g. many
				// NullPointerException)
				String originalError = ResourceHandler.getString("PreferenceManager.0"); //$NON-NLS-1$
				if (result == null)
					result = ""; //$NON-NLS-1$
				if (embeddedMessage != null)
					result = result + "  " + originalError + " " + embeddedMessage; //$NON-NLS-2$//$NON-NLS-1$
				else
					result = result + "  " + originalError + " " + originalException.toString(); //$NON-NLS-2$//$NON-NLS-1$
			}
			return result;
		}

		public Throwable getOriginalException() {
			return originalException;
		}

		public String toString() {
			// we don't put super.toString or getClass to "hide" that it was a
			// SourceEditing exception (otherwise, focus goes on that,
			// instead of original exception.
			String message = getMessage();
			// message should never be null ... but just in case
			return (message != null) ? message : super.toString();
		}
	}

	protected Document document = null;

	protected String fileName = null;
	private List preferenceChangeListeners = new ArrayList(1);

	protected Document _getNewDocumentDOM2() {
		Document result = null;
		// settings
		DocumentBuilder builder = getDocumentBuilder();
		result = builder.newDocument();
		Element settings = result.createElement(getRootElementName());
		result.appendChild(settings);
		return result;

	}

	protected Document _getParsedDocumentDOM2(String filename) {
		Document result = null;
		DocumentBuilder builder = getDocumentBuilder();
		try {
			Reader inputReader = new FileReader(getFilename());
			InputSource inputSource = new InputSource(inputReader);
			result = builder.parse(inputSource);
		} catch (FileNotFoundException e) {
			// file not found is "ok" ... it'll be created if we return null
			result = null;
		} catch (IOException e) {
			result = null;
		} catch (SAXException e) {
			result = null;
		}

		return result;

	}

	public void addPreferenceChangeListener(PreferenceChangeListener l) {
		if (!preferenceChangeListeners.contains(l))
			preferenceChangeListeners.add(l);
	}

	/**
	 * Returns a new document containing the defaults for this manager. This
	 * SHOULD NOT overwrite the actual document stored within this manager,
	 * and while a root element MAY BE created by the DOM implementation, it
	 * is recommended that subclasses NOT RELY upon it being there.
	 * 
	 * @return org.w3c.dom.Document
	 */
	public Document createDefaultPreferences() {
		Document txobj = null;
		txobj = _getNewDocumentDOM2();
		return txobj;
	}

	protected void firePreferenceChangeListeners() {
		if (preferenceChangeListeners != null)
			for (int i = 0; i < preferenceChangeListeners.size(); ++i)
				((PreferenceChangeListener) preferenceChangeListeners.get(i)).preferencesChanged();
	}

	/**
	 * 
	 * @return Document
	 */
	public Document getDocument() {
		if (document == null)
			load();
		return document;
	}

	private DocumentBuilder getDocumentBuilder() {
		DocumentBuilder result = null;
		try {
			result = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			Logger.logException(e);
		}
		return result;
	}

	/*************************************************************************
	 * Takes a single string of the form "a/b/c" and ensures that that
	 * structure exists below the head element, down through 'c', and returns
	 * a <em>single</em> element 'c'. For multiple elements (such as
	 * multiple &lt;macro&gt; elements contained within a single
	 * &lt;macros&gt; element, full DOM access is required for searching and
	 * child element manipulation.
	 ************************************************************************/
	public Element getElement(String name) {
		if (document == null)
			load();
		if (document != null)
			return (Element) getNode(getRootElement(), name);
		else
			return null;
	}

	protected abstract String getFilename();

	protected Node getNamedChild(Node parent, String childName) {
		if (parent == null) {
			return null;
		}
		NodeList childList = parent.getChildNodes();
		for (int i = 0; i < childList.getLength(); i++) {
			if (childList.item(i).getNodeName().equals(childName))
				return childList.item(i);
		}
		return null;
	}

	/*************************************************************************
	 * Takes a single string of the form "a/b/c" and ensures that that
	 * structure exists below the head element, down through 'c', and returns
	 * the element 'c'.
	 ************************************************************************/
	public Node getNode(Node node, String name) {
		StringTokenizer tokenizer = new StringTokenizer(name, "/"); //$NON-NLS-1$
		String token = null;
		while (tokenizer.hasMoreTokens()) {
			token = tokenizer.nextToken();
			if (getNamedChild(node, token) == null) {
				Document localDocument = node.getOwnerDocument();
				node.appendChild(localDocument.createElement(token));
			}
			node = getNamedChild(node, token);
		}
		return node;
	}

	protected Document getParsedDocument(String filename) {
		Document result = null;
		// file name is almost never null,
		// but can be if preferences are being ran
		// outside of a workbench application
		if (filename != null) {
			File existenceTester = new File(filename);
			if (!existenceTester.exists())
				result = null;
			else
				result = _getParsedDocumentDOM2(filename);
		}
		return result;

	}

	/**
	 * Returns the root element of the current document
	 * 
	 * @return org.w3c.dom.Element
	 */
	public Node getRootElement() {
		return getRootElement(getDocument());
	}

	/**
	 * Returns the root element of the current document
	 * 
	 * @return org.w3c.dom.Element
	 */
	public Node getRootElement(Document doc) {
		if (doc == null)
			return null;
		Node rootElement = doc.getFirstChild();
		while (rootElement != null && rootElement.getNodeType() != Node.ELEMENT_NODE && !rootElement.getNodeName().equals(getRootElementName())) {
			rootElement = rootElement.getNextSibling();
		}
		return rootElement;
	}

	/**
	 * The intended name for the root Element of the Document; what is also
	 * listed within the DOCTYPE declaration.
	 * 
	 * @return String
	 */
	public String getRootElementName() {
		return "settings"; //$NON-NLS-1$
	}

	public void load() {
		document = getParsedDocument(getFilename());

		if (document == null) {
			document = createDefaultPreferences();
		}
	}

	public void removePreferenceChangeListener(PreferenceChangeListener l) {
		preferenceChangeListeners.remove(l);
	}

	public void save() {
		if (document == null) {
			document = createDefaultPreferences();
		}
		try {
			// pa_TODO is this still going to be done like this?
			FileWriter output = new FileWriter(getFilename());
			saveDocument(document, output);
			output.flush();
			output.close();
		} catch (IOException e) {
			Logger.logException("Program Error: PreferenceManager::save. Exception saving preferences ", e); //$NON-NLS-1$
			throw new PreferenceRuntimeException(e);
		}
		firePreferenceChangeListeners();
	}

	public void saveDocument(Document document, Writer writer) throws IOException {

		serialize(document, writer);
	}

	private void serialize(Document sourceDocument, Writer writer) throws IOException {
		Source domSource = new DOMSource(sourceDocument);
		try {
			Transformer serializer = TransformerFactory.newInstance().newTransformer();
			try {
				serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
				serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
			} catch (IllegalArgumentException e) {
				// unsupported properties
			}
			serializer.transform(domSource, new StreamResult(writer));
		} catch (TransformerConfigurationException e) {
			throw new IOException(e.getMessage());
		} catch (TransformerFactoryConfigurationError e) {
			throw new IOException(e.getMessage());
		} catch (TransformerException e) {
			throw new IOException(e.getMessage());
		}
	}

}

Back to the top