1 /*******************************************************************************
2 * Copyright (c) 2014 École Polytechnique de Montréal
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Geneviève Bastien - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.linuxtools
.tmf
.analysis
.xml
.core
.module
;
16 import java
.io
.FileInputStream
;
17 import java
.io
.FileOutputStream
;
18 import java
.io
.IOException
;
20 import java
.nio
.channels
.FileChannel
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import javax
.xml
.XMLConstants
;
25 import javax
.xml
.parsers
.DocumentBuilder
;
26 import javax
.xml
.parsers
.DocumentBuilderFactory
;
27 import javax
.xml
.parsers
.ParserConfigurationException
;
28 import javax
.xml
.transform
.Source
;
29 import javax
.xml
.transform
.stream
.StreamSource
;
30 import javax
.xml
.validation
.Schema
;
31 import javax
.xml
.validation
.SchemaFactory
;
32 import javax
.xml
.validation
.Validator
;
34 import org
.eclipse
.core
.runtime
.IPath
;
35 import org
.eclipse
.core
.runtime
.IStatus
;
36 import org
.eclipse
.core
.runtime
.Path
;
37 import org
.eclipse
.core
.runtime
.Status
;
38 import org
.eclipse
.jdt
.annotation
.NonNull
;
39 import org
.eclipse
.linuxtools
.internal
.tmf
.analysis
.xml
.core
.Activator
;
40 import org
.eclipse
.linuxtools
.tmf
.analysis
.xml
.core
.stateprovider
.TmfXmlStrings
;
41 import org
.eclipse
.osgi
.util
.NLS
;
42 import org
.w3c
.dom
.Document
;
43 import org
.w3c
.dom
.Element
;
44 import org
.w3c
.dom
.Node
;
45 import org
.w3c
.dom
.NodeList
;
46 import org
.xml
.sax
.SAXException
;
47 import org
.xml
.sax
.SAXParseException
;
50 * Class containing some utilities for the XML plug-in packages: for example, it
51 * manages the XML files and validates them
53 * @author Geneviève Bastien
55 public class XmlUtils
{
57 /** Sub-directory of the plug-in where XML files are stored */
58 private static final String XML_DIRECTORY
= "xml_files"; //$NON-NLS-1$
60 /** Name of the XSD schema file */
61 private static final String XSD
= "xmlDefinition.xsd"; //$NON-NLS-1$
63 /** Make this class non-instantiable */
69 * Get the path where the XML files are stored. Create it if it does not
72 * @return path to XML files
74 public static IPath
getXmlFilesPath() {
75 IPath path
= Activator
.getDefault().getStateLocation();
76 path
= path
.addTrailingSeparator().append(XML_DIRECTORY
);
78 /* Check if directory exists, otherwise create it */
79 File dir
= path
.toFile();
80 if (!dir
.exists() || !dir
.isDirectory()) {
88 * Validate the XML file input with the XSD schema
91 * XML file to validate
92 * @return True if the XML validates
94 public static IStatus
xmlValidate(File xmlFile
) {
95 URL url
= XmlUtils
.class.getResource(XSD
);
96 SchemaFactory schemaFactory
= SchemaFactory
.newInstance(XMLConstants
.W3C_XML_SCHEMA_NS_URI
);
97 Source xmlSource
= new StreamSource(xmlFile
);
99 Schema schema
= schemaFactory
.newSchema(url
);
100 Validator validator
= schema
.newValidator();
101 validator
.validate(xmlSource
);
102 } catch (SAXParseException e
) {
103 String error
= NLS
.bind(Messages
.XmlUtils_XmlParseError
, e
.getLineNumber(), e
.getLocalizedMessage());
104 Activator
.logError(error
);
105 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
106 } catch (SAXException e
) {
107 String error
= NLS
.bind(Messages
.XmlUtils_XmlValidationError
, e
.getLocalizedMessage());
108 Activator
.logError(error
);
109 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
110 } catch (IOException e
) {
111 String error
= Messages
.XmlUtils_XmlValidateError
;
112 Activator
.logError("IO exception occurred", e
); //$NON-NLS-1$
113 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
115 return Status
.OK_STATUS
;
119 * Adds an XML file to the plugin's path. The XML file should have been
120 * validated using the {@link XmlUtils#xmlValidate(File)} method before
121 * calling this method.
124 * The XML file to add
125 * @return Whether the file was successfully added
127 public static IStatus
addXmlFile(File fromFile
) {
129 /* Copy file to path */
130 File toFile
= getXmlFilesPath().addTrailingSeparator().append(fromFile
.getName()).toFile();
133 if (!toFile
.exists()) {
134 toFile
.createNewFile();
136 } catch (IOException e
) {
137 String error
= Messages
.XmlUtils_ErrorCopyingFile
;
138 Activator
.logError(error
, e
);
139 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
142 try (FileInputStream fis
= new FileInputStream(fromFile
);
143 FileOutputStream fos
= new FileOutputStream(toFile
);
144 FileChannel source
= fis
.getChannel();
145 FileChannel destination
= fos
.getChannel();) {
146 destination
.transferFrom(source
, 0, source
.size());
147 } catch (IOException e
) {
148 String error
= Messages
.XmlUtils_ErrorCopyingFile
;
149 Activator
.logError(error
, e
);
150 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
152 return Status
.OK_STATUS
;
156 * Get only the XML element children of an XML element.
159 * The parent element to get children from
160 * @return The list of children Element of the parent
162 public static List
<Element
> getChildElements(Element parent
) {
163 NodeList childNodes
= parent
.getChildNodes();
164 List
<Element
> childElements
= new ArrayList
<>();
165 for (int index
= 0; index
< childNodes
.getLength(); index
++) {
166 if (childNodes
.item(index
).getNodeType() == Node
.ELEMENT_NODE
) {
167 childElements
.add((Element
) childNodes
.item(index
));
170 return childElements
;
174 * Get the XML children element of an XML element, but only those of a
178 * The parent element to get the children from
180 * The tag of the elements to return
181 * @return The list of children {@link Element} of the parent
183 public static List
<Element
> getChildElements(Element parent
, String elementTag
) {
184 /* get the state providers and find the corresponding one */
185 NodeList nodes
= parent
.getElementsByTagName(elementTag
);
186 List
<Element
> childElements
= new ArrayList
<>();
188 for (int i
= 0; i
< nodes
.getLength(); i
++) {
189 Element node
= (Element
) nodes
.item(i
);
190 if (node
.getParentNode().equals(parent
)) {
191 childElements
.add(node
);
194 return childElements
;
198 * Return the node element corresponding to the requested type in the file.
200 * TODO: Nothing prevents from having duplicate type -> id in a same file.
201 * That should not be allowed. If you want an element with the same ID as
202 * another one, it should be in a different file and we should check it at
206 * The absolute path to the XML file
208 * The type of top level element to search for
210 * The ID of the desired element
211 * @return The XML element or <code>null</code> if not found
213 public static Element
getElementInFile(String filePath
, @NonNull String elementType
, @NonNull String elementId
) {
215 if (filePath
== null) {
219 IPath path
= new Path(filePath
);
220 File file
= path
.toFile();
221 if (file
== null || !file
.exists() || !file
.isFile() || !xmlValidate(file
).isOK()) {
226 /* Load the XML File */
227 DocumentBuilderFactory dbFactory
= DocumentBuilderFactory
.newInstance();
228 DocumentBuilder dBuilder
;
230 dBuilder
= dbFactory
.newDocumentBuilder();
231 Document doc
= dBuilder
.parse(file
);
232 doc
.getDocumentElement().normalize();
234 /* get the state providers and find the corresponding one */
235 NodeList nodes
= doc
.getElementsByTagName(elementType
);
236 Element foundNode
= null;
238 for (int i
= 0; i
< nodes
.getLength(); i
++) {
239 Element node
= (Element
) nodes
.item(i
);
240 String id
= node
.getAttribute(TmfXmlStrings
.ID
);
241 if (id
.equals(elementId
)) {
246 } catch (ParserConfigurationException
| SAXException
| IOException e
) {