KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > intro > impl > model > util > ModelUtil


1 /*******************************************************************************
2  * Copyright (c) 2004, 2007 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  *******************************************************************************/

11
12 package org.eclipse.ui.internal.intro.impl.model.util;
13
14 import java.util.Enumeration JavaDoc;
15 import java.util.Properties JavaDoc;
16 import java.util.Vector JavaDoc;
17
18 import org.eclipse.core.runtime.FileLocator;
19 import org.eclipse.core.runtime.IConfigurationElement;
20 import org.eclipse.core.runtime.IPath;
21 import org.eclipse.core.runtime.Path;
22 import org.eclipse.core.runtime.Platform;
23 import org.eclipse.ui.internal.intro.impl.model.AbstractIntroPage;
24 import org.eclipse.ui.internal.intro.impl.model.IntroExtensionContent;
25 import org.eclipse.ui.internal.intro.impl.model.url.IntroURLParser;
26 import org.eclipse.ui.internal.intro.impl.util.Log;
27 import org.osgi.framework.Bundle;
28 import org.w3c.dom.Document JavaDoc;
29 import org.w3c.dom.Element JavaDoc;
30 import org.w3c.dom.Node JavaDoc;
31 import org.w3c.dom.NodeList JavaDoc;
32
33
34 /**
35  * Util class for model. Has methods for resolving model attributes, and methods
36  * for manipulating XHTML DOM.
37  */

38 public class ModelUtil {
39
40     private static String JavaDoc TAG_BODY = "body"; //$NON-NLS-1$
41
private static String JavaDoc TAG_HEAD = "head"; //$NON-NLS-1$
42
private static String JavaDoc TAG_BASE = "base"; //$NON-NLS-1$
43
public static String JavaDoc TAG_DIV = "div"; //$NON-NLS-1$
44
public static String JavaDoc TAG_HEAD_LINK = "link"; //$NON-NLS-1$
45
private static String JavaDoc TAG_PARAM = "param"; //$NON-NLS-1$
46
private static String JavaDoc ATT_SRC = "src"; //$NON-NLS-1$
47
private static String JavaDoc ATT_HREF = "href"; //$NON-NLS-1$
48
private static String JavaDoc ATT_CITE = "cite"; //$NON-NLS-1$
49
private static String JavaDoc ATT_LONGDESC = "longdesc"; //$NON-NLS-1$
50
private static String JavaDoc ATT_DATA = "data"; //$NON-NLS-1$
51
private static String JavaDoc ATT_CODEBASE = "codebase"; //$NON-NLS-1$
52
private static String JavaDoc ATT_VALUE = "value"; //$NON-NLS-1$
53
private static String JavaDoc ATT_VALUE_TYPE = "valuetype"; //$NON-NLS-1$
54
private static String JavaDoc ATT_REL = "rel"; //$NON-NLS-1$
55
private static String JavaDoc ATT_TYPE = "type"; //$NON-NLS-1$
56

57
58
59     /*
60      * ********* Model util methods ************************************
61      */

62
63     /**
64      * Checks to see if the passed string is a valid URL (has a protocol), if
65      * yes, returns it as is. If no, treats it as a resource relative to the
66      * declaring plugin. Return the plugin relative location, fully qualified.
67      * Retruns null if the passed string itself is null.
68      *
69      * @param resource
70      * @param pluginDesc
71      * @return returns the URL as is if it had a protocol.
72      */

73     public static String JavaDoc resolveURL(String JavaDoc url, String JavaDoc pluginId) {
74         Bundle bundle = null;
75         if (pluginId != null)
76             // if pluginId is not null, use it.
77
bundle = Platform.getBundle(pluginId);
78         return resolveURL("", url, bundle); //$NON-NLS-1$
79
}
80
81
82
83     /**
84      * Checks to see if the passed string is a valid URL (has a protocol), if
85      * yes, returns it as is. If no, treats it as a resource relative to the
86      * declaring plugin. Return the plugin relative location, fully qualified.
87      * Retruns null if the passed string itself is null.
88      *
89      * @param resource
90      * @param pluginDesc
91      * @return returns the URL as is if it had a protocol.
92      */

93     public static String JavaDoc resolveURL(String JavaDoc url, IConfigurationElement element) {
94         Bundle bundle = BundleUtil.getBundleFromConfigurationElement(element);
95         return resolveURL("", url, bundle); //$NON-NLS-1$
96
}
97
98
99
100     /**
101      * @see resolveURL(String url, IConfigurationElement element)
102      */

103     public static String JavaDoc resolveURL(String JavaDoc base, String JavaDoc url, Bundle bundle) {
104         // quick exit
105
if (url == null)
106             return null;
107         IntroURLParser parser = new IntroURLParser(url);
108         if (parser.hasProtocol())
109             return url;
110         // make plugin relative url. Only now we need the bundle.
111
return BundleUtil.getResolvedResourceLocation(base, url, bundle);
112     }
113
114     /**
115      * Ensures that a file:// URL exists for the bundle root. This will
116      * cause jarred bundles to be extracted into a cache directory.
117      */

118     public static void ensureFileURLsExist(Bundle bundle, String JavaDoc contentFile) {
119         try {
120             FileLocator.toFileURL(bundle.getEntry("/")); //$NON-NLS-1$
121
} catch (Exception JavaDoc e) {
122             if (contentFile != null)
123                 Log.error("Failed to extract Intro content folder for: " //$NON-NLS-1$
124
+ contentFile, e);
125         }
126     }
127
128
129     /**
130      * Returns the path to the parent folder containing the passed content xml
131      * file. It is assumed that the path is a local url representing a content
132      * file.
133      */

134     public static String JavaDoc getParentFolderToString(String JavaDoc contentFilePath) {
135         IPath path = getParentFolderPath(contentFilePath);
136         return path.toString();
137     }
138
139
140     /*
141      *
142      * ******** XHTML DOM util methods *********************************
143      */

144
145     /**
146      * Returns the path to the parent folder containing the passed content xml
147      * file. It is assumed that the path is a local url representing a content
148      * file.
149      */

150     public static String JavaDoc getParentFolderOSString(String JavaDoc contentFilePath) {
151         IPath path = getParentFolderPath(contentFilePath);
152         return path.toOSString();
153     }
154
155     /**
156      * Returns the parent folder of the given path.
157      */

158     public static IPath getParentFolderPath(String JavaDoc contentFilePath) {
159         IPath path = new Path(contentFilePath);
160         path = path.removeLastSegments(1).addTrailingSeparator();
161         return path;
162     }
163
164
165
166
167     public static void insertBase(Document JavaDoc dom, String JavaDoc baseURL) {
168         // there should only be one head and one base element dom.
169
NodeList JavaDoc headList = dom.getElementsByTagName(TAG_HEAD);
170         Element head = (Element) headList.item(0);
171         NodeList JavaDoc baseList = head.getElementsByTagName(TAG_BASE);
172         if (baseList.getLength() == 0) {
173             // insert a base element, since one is not defined already.
174
Element base = dom.createElement(TAG_BASE);
175             base.setAttribute(ATT_HREF, baseURL);
176             head.insertBefore(base, head.getFirstChild());
177         }
178     }
179
180
181     public static Element getBase(Document JavaDoc dom) {
182         // there should only be one head and one base element dom.
183
NodeList JavaDoc headList = dom.getElementsByTagName(TAG_HEAD);
184         Element head = (Element) headList.item(0);
185         NodeList JavaDoc baseList = head.getElementsByTagName(TAG_BASE);
186         if (baseList.getLength() == 0)
187             // no base defined, signal failure.
188
return null;
189
190         return (Element) baseList.item(baseList.getLength() - 1);
191
192     }
193
194
195     // <link rel="stylesheet" HREF="shared.css" type="text/css" />
196
public static void insertStyle(Document JavaDoc dom, String JavaDoc cssUrl) {
197         // there should only be one head and one base element dom.
198
NodeList JavaDoc headList = dom.getElementsByTagName(TAG_HEAD);
199         Element head = null;
200         // Element base = getBase(dom);
201
NodeList JavaDoc styleList = null;
202         // there can be more than one style. DO not add style if it exists.
203
if (headList.getLength() >= 1) {
204             head = (Element) headList.item(0);
205             styleList = head.getElementsByTagName(TAG_HEAD_LINK);
206             for (int i = 0; i < styleList.getLength(); i++) {
207                 Element style = (Element) styleList.item(0);
208                 String JavaDoc styleString = style.getAttribute(ATT_HREF);
209                 if (styleString.equals(cssUrl))
210                     return;
211             }
212         }
213
214         // insert the style, since it is not defined.
215
Element styleToAdd = dom.createElement(TAG_HEAD_LINK);
216         styleToAdd.setAttribute(ATT_HREF, cssUrl);
217         styleToAdd.setAttribute(ATT_REL, "stylesheet"); //$NON-NLS-1$
218
styleToAdd.setAttribute(ATT_TYPE, "text/css"); //$NON-NLS-1$
219
if (styleList != null && styleList.getLength() >= 1)
220             styleList.item(0).getParentNode().insertBefore(styleToAdd,
221                 styleList.item(0));
222         else
223             head.appendChild(styleToAdd);
224
225     }
226
227     /**
228      * Returns a reference to the body of the DOM.
229      *
230      * @param dom
231      * @return
232      */

233     public static Element getBodyElement(Document JavaDoc dom) {
234         // there should only be one body element dom.
235
NodeList JavaDoc bodyList = dom.getElementsByTagName(TAG_BODY);
236         Element body = (Element) bodyList.item(0);
237         return body;
238     }
239
240
241
242     public static Element createElement(Document JavaDoc dom, String JavaDoc elementName,
243             Properties JavaDoc attributes) {
244
245         // make sure to create element with any namespace uri to enable finding
246
// it again using Dom.getElementsByTagNameNS()
247
Element element = dom.createElementNS("", elementName); //$NON-NLS-1$
248
if (attributes != null) {
249             Enumeration JavaDoc e = attributes.keys();
250             while (e.hasMoreElements()) {
251                 String JavaDoc key = (String JavaDoc) e.nextElement();
252                 element.setAttribute(key, attributes.getProperty(key));
253             }
254         }
255         return element;
256     }
257
258     public static Element createAndAppendChild(Element parentElement,
259             String JavaDoc elementName, Properties JavaDoc attributes) {
260
261         Element element = createElement(parentElement.getOwnerDocument(),
262             elementName, attributes);
263         parentElement.appendChild(element);
264         return element;
265     }
266
267
268
269     /**
270      * Returns an Element array of all first level descendant Elements with a
271      * given tag name, in the order in which they are encountered in the DOM.
272      * Unlike the JAXP apis, which returns preorder traversal of this Element
273      * tree, this method filters out children deeper than first level child
274      * nodes.
275      */

276     public static Element[] getElementsByTagName(Element parent, String JavaDoc tagName) {
277         NodeList JavaDoc allChildElements = parent.getElementsByTagName(tagName);
278         Vector JavaDoc vector = new Vector JavaDoc();
279         for (int i = 0; i < allChildElements.getLength(); i++) {
280             // we know that the nodelist is of elements.
281
Element aElement = (Element) allChildElements.item(i);
282             if (aElement.getParentNode().equals(parent))
283                 // first level child element. add it.
284
vector.add(aElement);
285         }
286         Element[] filteredElements = new Element[vector.size()];
287         vector.copyInto(filteredElements);
288         return filteredElements;
289     }
290
291     /**
292      * Same as getElementsByTagName(Element parent, String tagName) but the
293      * parent element is assumed to be the root of the document.
294      *
295      * @see getElementsByTagName(Element parent, String tagName)
296      */

297     public static Element[] getElementsByTagName(Document JavaDoc dom, String JavaDoc tagName) {
298         NodeList JavaDoc allChildElements = dom.getElementsByTagName(tagName);
299         Vector JavaDoc vector = new Vector JavaDoc();
300         for (int i = 0; i < allChildElements.getLength(); i++) {
301             // we know that the nodelist is of elements.
302
Element aElement = (Element) allChildElements.item(i);
303             if (aElement.getParentNode().equals(dom.getDocumentElement()))
304                 // first level child element. add it. Cant use getParent
305
// here.
306
vector.add(aElement);
307         }
308         Element[] filteredElements = new Element[vector.size()];
309         vector.copyInto(filteredElements);
310         return filteredElements;
311     }
312
313
314     /*
315      * Util method similar to DOM getElementById() method, but it works without
316      * an id attribute being specified. Deep searches all children in this
317      * container's DOM for the first child with the given id. The element
318      * retrieved must have the passed local name. Note that in an XHTML file
319      * (aka DOM) elements should have a unique id within the scope of a
320      * document. We use local name because this allows for finding intro
321      * anchors, includes and dynamic content element regardless of whether or
322      * not an xmlns was used in the xml.
323      */

324     public static Element getElementById(Document JavaDoc dom, String JavaDoc id,
325             String JavaDoc localElementName) {
326         
327         NodeList JavaDoc children = dom.getElementsByTagNameNS("*", localElementName); //$NON-NLS-1$
328
for (int i = 0; i < children.getLength(); i++) {
329             Element element = (Element) children.item(i);
330             if (element.getAttribute("id").equals(id)) //$NON-NLS-1$
331
return element;
332         }
333         // non found.
334
return null;
335
336     }
337
338     public static Element getElementById(Document JavaDoc dom, String JavaDoc id) {
339         return getElementById(dom, id, "*"); //$NON-NLS-1$
340
}
341     
342     public static void updateResourceAttributes(Element element,
343             AbstractIntroPage page) {
344         updateResourceAttributes(element, page.getBase(), page.getBundle());
345     }
346
347
348     public static void updateResourceAttributes(Element element,
349             IntroExtensionContent extensionContent) {
350         updateResourceAttributes(element, extensionContent.getBase(),
351             extensionContent.getBundle());
352     }
353
354     /**
355      * Updates all the resource attributes of the passed element to point to a
356      * local resolved url.
357      *
358      * @param element
359      * @param extensionContent
360      */

361     private static void updateResourceAttributes(Element element, String JavaDoc base,
362             Bundle bundle) {
363         // doUpdateResourceAttributes(element, base, bundle);
364
NodeList JavaDoc children = element.getElementsByTagName("*"); //$NON-NLS-1$
365
for (int i = 0; i < children.getLength(); i++) {
366             Element child = (Element) children.item(i);
367             doUpdateResourceAttributes(child, base, bundle);
368         }
369     }
370
371     private static void doUpdateResourceAttributes(Element element,
372             String JavaDoc base, Bundle bundle) {
373         qualifyAttribute(element, ATT_SRC, base, bundle);
374         qualifyAttribute(element, ATT_HREF, base, bundle);
375         qualifyAttribute(element, ATT_CITE, base, bundle);
376         qualifyAttribute(element, ATT_LONGDESC, base, bundle);
377         qualifyAttribute(element, ATT_CODEBASE, base, bundle);
378         qualifyAttribute(element, ATT_DATA, base, bundle);
379         qualifyValueAttribute(element, base, bundle);
380     }
381
382     private static void qualifyAttribute(Element element, String JavaDoc attributeName,
383             String JavaDoc base, Bundle bundle) {
384         if (element.hasAttribute(attributeName)) {
385             String JavaDoc attributeValue = element.getAttribute(attributeName);
386             if (new IntroURLParser(attributeValue).hasProtocol())
387                 return;
388
389             // resolve the resource against the nl mechanism.
390
String JavaDoc attributePath = BundleUtil.getResolvedResourceLocation(base,
391                 attributeValue, bundle);
392             element.setAttribute(attributeName, attributePath);
393         }
394     }
395
396     private static void qualifyValueAttribute(Element element, String JavaDoc base,
397             Bundle bundle) {
398         if (element.hasAttribute(ATT_VALUE)
399                 && element.hasAttribute(ATT_VALUE_TYPE)
400                 && element.getAttribute(ATT_VALUE_TYPE).equals("ref") //$NON-NLS-1$
401
&& element.getLocalName().equals(TAG_PARAM)) {
402             String JavaDoc value = element.getAttribute(ATT_VALUE);
403             if (new IntroURLParser(value).hasProtocol())
404                 return;
405             // resolve the resource against the nl mechanism.
406
String JavaDoc attributePath = BundleUtil.getResolvedResourceLocation(base,
407                 value, bundle);
408             element.setAttribute(ATT_VALUE, attributePath);
409         }
410     }
411
412
413     /**
414      * Returns an array version of the passed NodeList. Used to work around DOM
415      * design issues.
416      */

417     public static Node JavaDoc[] getArray(NodeList JavaDoc nodeList) {
418         Node JavaDoc[] nodes = new Node JavaDoc[nodeList.getLength()];
419         for (int i = 0; i < nodeList.getLength(); i++)
420             nodes[i] = nodeList.item(i);
421         return nodes;
422     }
423
424
425     /**
426      * Remove all instances of the element from the DOM.
427      *
428      */

429     public static void removeAllElements(Document JavaDoc dom, String JavaDoc elementLocalName) {
430         // get all elements in DOM and remove them.
431
NodeList JavaDoc elements = dom.getElementsByTagNameNS("*", //$NON-NLS-1$
432
elementLocalName);
433         // get the array version of the nodelist to work around DOM api design.
434
Node JavaDoc[] elementsArray = ModelUtil.getArray(elements);
435         for (int i = 0; i < elementsArray.length; i++) {
436             Node JavaDoc element = elementsArray[i];
437             element.getParentNode().removeChild(element);
438         }
439
440     }
441
442
443
444 }
445
Popular Tags