blob: 16da926575d7e15d8e258d258185e5c4257c5eaf [file] [log] [blame]
david_williamscfdb2cd2004-11-11 08:37:49 +00001/*******************************************************************************
amywuecebb042007-04-10 20:07:35 +00002 * Copyright (c) 2001, 2006 IBM Corporation and others.
david_williamscfdb2cd2004-11-11 08:37:49 +00003 * 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
amywuecebb042007-04-10 20:07:35 +00007 *
david_williamscfdb2cd2004-11-11 08:37:49 +00008 * Contributors:
9 * IBM Corporation - initial API and implementation
10 * Jens Lukowski/Innoopract - initial renaming/restructuring
11 *
12 *******************************************************************************/
david_williams1d37d7a2005-10-21 20:18:39 +000013package org.eclipse.wst.sse.internal.contentproperties;
david_williamscfdb2cd2004-11-11 08:37:49 +000014
15
16
17import java.io.File;
18import java.io.IOException;
19import java.io.OutputStream;
20import java.util.HashMap;
21import java.util.Hashtable;
22import java.util.Iterator;
23import java.util.Map;
24import java.util.Set;
25
26import javax.xml.parsers.DocumentBuilderFactory;
27import javax.xml.parsers.FactoryConfigurationError;
28import javax.xml.parsers.ParserConfigurationException;
29import javax.xml.transform.OutputKeys;
30import javax.xml.transform.Source;
31import javax.xml.transform.Transformer;
32import javax.xml.transform.TransformerConfigurationException;
33import javax.xml.transform.TransformerException;
34import javax.xml.transform.TransformerFactory;
35import javax.xml.transform.TransformerFactoryConfigurationError;
36import javax.xml.transform.dom.DOMSource;
37import javax.xml.transform.stream.StreamResult;
38
david_williams1d37d7a2005-10-21 20:18:39 +000039import org.eclipse.wst.sse.core.internal.Logger;
david_williamscfdb2cd2004-11-11 08:37:49 +000040import org.w3c.dom.Attr;
41import org.w3c.dom.Document;
42import org.w3c.dom.Element;
43import org.w3c.dom.NamedNodeMap;
44import org.w3c.dom.Node;
45import org.w3c.dom.NodeList;
46import org.w3c.dom.traversal.NodeIterator;
47import org.xml.sax.SAXException;
48
amywu3a205672006-02-23 05:05:23 +000049/**
50* @deprecated This is package protected so no one cares anyways.
51*/
david_williamscfdb2cd2004-11-11 08:37:49 +000052class SimpleNodeOperator {
53
54 class CreateContentSettingsFailureException extends Exception {
david_williams16f26a82004-11-12 07:30:49 +000055 /**
56 * Comment for <code>serialVersionUID</code>
57 */
58 private static final long serialVersionUID = 1L;
59
david_williamscfdb2cd2004-11-11 08:37:49 +000060 public CreateContentSettingsFailureException(String reason) {
61 super(reason);
62 }
63 }
64
65
66 class ReadContentSettingsFailureException extends Exception {
david_williams16f26a82004-11-12 07:30:49 +000067 /**
68 * Comment for <code>serialVersionUID</code>
69 */
70 private static final long serialVersionUID = 1L;
71
david_williamscfdb2cd2004-11-11 08:37:49 +000072 public ReadContentSettingsFailureException(String reason) {
73 super(reason);
74 }
75 }
76
77 static class WriteContentSettingsFailureException extends Exception {
david_williams16f26a82004-11-12 07:30:49 +000078 /**
79 * Comment for <code>serialVersionUID</code>
80 */
81 private static final long serialVersionUID = 1L;
82
david_williamscfdb2cd2004-11-11 08:37:49 +000083 public WriteContentSettingsFailureException(String reason) {
84 super(reason);
85 }
86 }
87
88 // writer class for .contentSettings.
89 class XMLDocumentWriter {
90 OutputStream fOut;
91
92 protected XMLDocumentWriter(OutputStream out) {
93 this.fOut = out;
94 }
95
96 protected final void close() {
97 try {
98 fOut.close();
99 } catch (IOException e) {
100 // do nothing, shouldn't matter
101 }
102 }
103
104 protected void serialize(Document sourceDocument) throws WriteContentSettingsFailureException {
105 // JAXP transformation
106 Source domSource = new DOMSource(sourceDocument);
107 try {
108 Transformer serializer = TransformerFactory.newInstance().newTransformer();
109 try {
110 serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
111 serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
112 } catch (IllegalArgumentException e) {
113 // unsupported properties
114 }
115 serializer.transform(domSource, new StreamResult(fOut));
116 } catch (TransformerConfigurationException e) {
117 throw new WriteContentSettingsFailureException(e.getMessage());
118 } catch (TransformerFactoryConfigurationError e) {
119 throw new WriteContentSettingsFailureException(e.getMessage());
120 } catch (TransformerException e) {
121 throw new WriteContentSettingsFailureException(e.getMessage());
122 }
123 }
124 }
125
126 public static void main(String[] args) {
127 SimpleNodeOperator a = null;
128 try {
129 a = new SimpleNodeOperator("workspace/org.eclipse.examples.contentsettings/.contentsettings.xml");//$NON-NLS-1$
130 } catch (Exception e) {
131 System.exit(0);
132 }
133
134 // print all Elements
135 //a.printTree(iter);
136
137 // add Element
138 Map attMap = new Hashtable();
139 attMap.put("path", "hogepath");//$NON-NLS-1$ //$NON-NLS-2$
140 attMap.put("fDocument-type", "documenthogehoge");//$NON-NLS-1$ //$NON-NLS-2$
141 a.addElementUnderRoot("file", attMap);//$NON-NLS-1$
142
143 try {
144 a.writeDocument(System.out);
145 } catch (Exception e) {
146 System.err.println(e.toString());
147 }
148
149 }
150
151 //never used
152 //private DOMParser parser;
153 private Document fDocument;
154 private Node root;
155
156 private String settingsFileName;
157
158
159 public SimpleNodeOperator(Document doc) throws CreateContentSettingsFailureException {
160
161 if (doc == null)
162 throw new CreateContentSettingsFailureException("Document doc==null");//$NON-NLS-1$
163 fDocument = doc;
164 root = fDocument.getLastChild();
165 if (root == null)
166 throw new CreateContentSettingsFailureException("Node root==null");//$NON-NLS-1$
167 }
168
169 public SimpleNodeOperator(String fullPath) throws ReadContentSettingsFailureException {
170 this.settingsFileName = fullPath;
171 createObjectOfDocument();
172 }
173
174 // add attribute(attName=attValue) of ele without checking overlapping of
175 // another attributes of ele.
176 // if overlapping ,override
177 protected Node addAttributeAt(Element ele, String attName, String attValue) {
178 Attr att = fDocument.createAttribute(attName);
179 att.setValue(attValue);
180 if (ele != null)
181 ele.setAttributeNode(att);
182 return ele;
183 }
184
185 protected Node addElementUnder(Node parent, String tagName, Map attMap) {
186 if (parent == null || tagName == null)
187 return null;
188 Element e = fDocument.createElement(tagName);
189 if (attMap != null) {
190 if (!attMap.isEmpty()) {
191 Set attKeys = attMap.keySet();
192 Iterator iter = attKeys.iterator();
193 while (iter.hasNext()) {
194 String key = (String) iter.next();
195 e.setAttribute(key, (String) attMap.get(key));
196 }
197 }
198 }
199 parent.appendChild(e);
200 return e;
201 }
202
203 protected final Node addElementUnderRoot(String tagName) {
204 return addElementUnder(root, tagName, null);
205 }
206
207 // add element with attMap as attribute without checking overlapping.
208 protected final Node addElementUnderRoot(String tagName, Map attMap) {
209 return addElementUnder(root, tagName, attMap);
210 }
211
david_williamscfdb2cd2004-11-11 08:37:49 +0000212 private void createObjectOfDocument() throws ReadContentSettingsFailureException {
213 try {
214 fDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(settingsFileName));
215 } catch (SAXException e) {
216 Logger.logException("exception parsing" + settingsFileName, e); //$NON-NLS-1$
217 } catch (IOException e) {
218 Logger.logException("I/O exception parsing" + settingsFileName, e); //$NON-NLS-1$
219 } catch (ParserConfigurationException e) {
220 Logger.logException("exception accessing DOMImplementation", e); //$NON-NLS-1$
221 } catch (FactoryConfigurationError e) {
222 Logger.logException("exception accessing DOMImplementation", e); //$NON-NLS-1$
223 }
224 //get the root of the XML fDocument
225 root = fDocument.getLastChild();
226 if (root == null) {
227 throw new ReadContentSettingsFailureException("Error: Node root==null");//$NON-NLS-1$
228 }
229 }
230
231 protected Map getAttributesOf(Node node) {
232 if (!node.hasAttributes())
233 return null;
234 Map map = new HashMap();
235 NamedNodeMap attrs = node.getAttributes();
236 int size = attrs.getLength();
237 for (int i = 0; i < size; i++) {
238 Attr attr = (Attr) attrs.item(i);
239 map.put(attr.getName(), attr.getValue());
240 }
241 return (map);
242 }
243
244 private Node getElementWithAttribute(Node first, String attName, String attValue) {
245 Node navpoint = first;
246 while (navpoint != null) {
247 if (navpoint.getNodeType() == Node.ELEMENT_NODE) {
248 NamedNodeMap m = navpoint.getAttributes();
249 if (m == null)
250 continue;
251 if (m.getNamedItem(attName) != null) {
252 if (attValue.equals(((Attr) m.getNamedItem(attName)).getNodeValue()))
253 return navpoint;
254 }
255 NodeList childNodes = navpoint.getChildNodes();
256 if (childNodes != null && childNodes.getLength() > 0) {
257 Node holdNode = getElementWithAttribute(navpoint.getFirstChild(), attName, attValue);
258 if (holdNode != null) {
259 return holdNode;
260 }
261 }
262 }
263 navpoint = navpoint.getNextSibling();
264 }
265 return null;
266 }
267
268
269 // return a (first) Element with attr(attName=attValue) it if exists,
270 // otherwise return null
271 protected Node getElementWithAttribute(String attName, String attValue) {
272 if (attName == null || attValue == null || !fDocument.hasChildNodes())
273 return null;
274 return getElementWithAttribute(fDocument.getFirstChild(), attName, attValue);
275 }
276
277 // retrun Element which has nodeName as Node Name
278 protected Node getElementWithNodeName(String nodeName) {
279 if (nodeName == null)
280 return null;
281 NodeList nodes = fDocument.getElementsByTagName(nodeName);
282 if (nodes.getLength() > 0) {
283 return nodes.item(0);
284 }
285 return null;
286 }
287
288 public void printTree(NodeIterator iter) {
289 Node n;
290 while ((n = iter.nextNode()) != null) {
291 System.out.println(n.getNodeName() + ":");//$NON-NLS-1$
292 NamedNodeMap m = n.getAttributes();
293 if (m == null)
294 continue;
295 for (int i = 0; i < m.getLength(); i++) {
296 String attName = m.item(i).getNodeName();
297 System.out.print(" " + attName + "=" + m.item(i).getNodeValue());//$NON-NLS-1$ //$NON-NLS-2$
298 }
299 System.out.println("");//$NON-NLS-1$
300 }
301 }
302
303
304 // remove attribute(attName) at ele.
305 protected Attr removeAttributeAt(Element ele, String attName) {
306 if (ele == null || attName == null)
307 return null;
308 Attr att = ele.getAttributeNode(attName);
309 ele.removeAttribute(attName);
310 return att;
311 }
312
313 protected Element removeElementWith(String nodeName) {
314 NodeList nodes = fDocument.getElementsByTagName(nodeName);
315 for (int i = 0; i < nodes.getLength(); i++) {
316 nodes.item(i).getParentNode().removeChild(nodes.item(i));
317 }
318 return null;
319 }
320
321 // remove a (first) Element with attr(attName=attValue) and return it if
322 // exists, otherwise return null
323 protected Element removeElementWith(String attName, String attValue) {
324 if (fDocument.hasChildNodes()) {
325 Node element = getElementWithAttribute(attName, attValue);
326 if (element != null && element.getNodeType() == Node.ELEMENT_NODE) {
327 element.getParentNode().removeChild(element);
328 return (Element) element;
329 }
330 }
331 return null;
332
333 }
334
335 // update attribute(attName=newValue) at ele if both ele and attribute of
336 // ele exist
337 protected void updateAttributeAt(Element ele, String attName, String newValue) {
338 Attr att = null;
339 if (ele != null)
340 if ((att = ele.getAttributeNode(attName)) != null)
341 att.setValue(newValue);
342 }
343
344 protected void writeDocument(OutputStream out) throws WriteContentSettingsFailureException {
345 XMLDocumentWriter writer = new XMLDocumentWriter(out);
346 try {
347 writer.serialize(fDocument);
348 } finally {
349 writer.close();
350 }
351 }
352
353
354}