1 /*******************************************************************************
2 * Copyright (c) 2014, 2016 É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
.tracecompass
.tmf
.analysis
.xml
.core
.module
;
15 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.nullToEmptyString
;
18 import java
.io
.FileInputStream
;
19 import java
.io
.FileOutputStream
;
20 import java
.io
.IOException
;
22 import java
.nio
.channels
.FileChannel
;
23 import java
.util
.ArrayList
;
24 import java
.util
.Collections
;
25 import java
.util
.HashMap
;
26 import java
.util
.List
;
29 import javax
.xml
.XMLConstants
;
30 import javax
.xml
.parsers
.DocumentBuilder
;
31 import javax
.xml
.parsers
.DocumentBuilderFactory
;
32 import javax
.xml
.parsers
.ParserConfigurationException
;
33 import javax
.xml
.transform
.Source
;
34 import javax
.xml
.transform
.stream
.StreamSource
;
35 import javax
.xml
.validation
.Schema
;
36 import javax
.xml
.validation
.SchemaFactory
;
37 import javax
.xml
.validation
.Validator
;
39 import org
.eclipse
.core
.runtime
.IPath
;
40 import org
.eclipse
.core
.runtime
.IStatus
;
41 import org
.eclipse
.core
.runtime
.Path
;
42 import org
.eclipse
.core
.runtime
.Status
;
43 import org
.eclipse
.jdt
.annotation
.NonNull
;
44 import org
.eclipse
.jdt
.annotation
.Nullable
;
45 import org
.eclipse
.osgi
.util
.NLS
;
46 import org
.eclipse
.tracecompass
.internal
.tmf
.analysis
.xml
.core
.Activator
;
47 import org
.eclipse
.tracecompass
.tmf
.analysis
.xml
.core
.stateprovider
.TmfXmlStrings
;
48 import org
.w3c
.dom
.Document
;
49 import org
.w3c
.dom
.Element
;
50 import org
.w3c
.dom
.Node
;
51 import org
.w3c
.dom
.NodeList
;
52 import org
.xml
.sax
.SAXException
;
53 import org
.xml
.sax
.SAXParseException
;
56 * Class containing some utilities for the XML plug-in packages: for example, it
57 * manages the XML files and validates them
59 * @author Geneviève Bastien
61 public class XmlUtils
{
63 /** Sub-directory of the plug-in where XML files are stored */
64 private static final String XML_DIRECTORY
= "xml_files"; //$NON-NLS-1$
66 /** Name of the XSD schema file */
67 private static final String XSD
= "xmlDefinition.xsd"; //$NON-NLS-1$
70 * Extension for XML files
73 public static final String XML_EXTENSION
= "xml"; //$NON-NLS-1$
75 /** Make this class non-instantiable */
81 * Get the path where the XML files are stored. Create it if it does not
84 * @return path to XML files
86 public static IPath
getXmlFilesPath() {
87 IPath path
= Activator
.getDefault().getStateLocation();
88 path
= path
.addTrailingSeparator().append(XML_DIRECTORY
);
90 /* Check if directory exists, otherwise create it */
91 File dir
= path
.toFile();
92 if (!dir
.exists() || !dir
.isDirectory()) {
100 * Validate the XML file input with the XSD schema
103 * XML file to validate
104 * @return True if the XML validates
106 public static IStatus
xmlValidate(File xmlFile
) {
107 URL url
= XmlUtils
.class.getResource(XSD
);
108 SchemaFactory schemaFactory
= SchemaFactory
.newInstance(XMLConstants
.W3C_XML_SCHEMA_NS_URI
);
109 Source xmlSource
= new StreamSource(xmlFile
);
111 Schema schema
= schemaFactory
.newSchema(url
);
112 Validator validator
= schema
.newValidator();
113 validator
.validate(xmlSource
);
114 } catch (SAXParseException e
) {
115 String error
= NLS
.bind(Messages
.XmlUtils_XmlParseError
, e
.getLineNumber(), e
.getLocalizedMessage());
116 Activator
.logError(error
);
117 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
118 } catch (SAXException e
) {
119 String error
= NLS
.bind(Messages
.XmlUtils_XmlValidationError
, e
.getLocalizedMessage());
120 Activator
.logError(error
);
121 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
122 } catch (IOException e
) {
123 String error
= Messages
.XmlUtils_XmlValidateError
;
124 Activator
.logError("IO exception occurred", e
); //$NON-NLS-1$
125 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
127 return Status
.OK_STATUS
;
131 * Adds an XML file to the plugin's path. The XML file should have been
132 * validated using the {@link XmlUtils#xmlValidate(File)} method before
133 * calling this method.
136 * The XML file to add
137 * @return Whether the file was successfully added
139 public static IStatus
addXmlFile(File fromFile
) {
141 /* Copy file to path */
142 File toFile
= getXmlFilesPath().addTrailingSeparator().append(fromFile
.getName()).toFile();
144 return copyXmlFile(fromFile
, toFile
);
148 * List all files under the XML analysis files path. It returns a map where
149 * the key is the file name.
151 * @return A map with all the XML analysis files
154 public static synchronized @NonNull Map
<String
, File
> listFiles() {
155 IPath pathToFiles
= XmlUtils
.getXmlFilesPath();
156 File folder
= pathToFiles
.toFile();
158 Map
<String
, File
> fileMap
= new HashMap
<>();
159 if ((folder
.isDirectory() && folder
.exists())) {
160 File
[] listOfFiles
= folder
.listFiles();
161 if (listOfFiles
!= null) {
162 for (File file
: listOfFiles
) {
163 IPath path
= new Path(file
.getName());
164 if (path
.getFileExtension().equals(XML_EXTENSION
)) {
165 fileMap
.put(file
.getName(), file
);
169 Activator
.logError("I/O error occured while accessing files in folder " + folder
.getPath()); //$NON-NLS-1$
172 return Collections
.unmodifiableMap(fileMap
);
176 * Delete an XML analysis file
179 * The XML file to delete
182 public static void deleteFile(String name
) {
183 Map
<String
, File
> files
= listFiles();
184 File file
= files
.get(name
);
192 * Export an XML analysis file to an external path
195 * The name of the file to export
197 * The full path of the file to write to
198 * @return Whether the file was successfully exported
201 public static IStatus
exportXmlFile(String from
, String to
) {
203 /* Copy file to path */
204 File fromFile
= getXmlFilesPath().addTrailingSeparator().append(from
).toFile();
206 if (!fromFile
.exists()) {
207 Activator
.logError("Failed to find XML analysis file " + fromFile
.getName()); //$NON-NLS-1$
208 return Status
.CANCEL_STATUS
;
211 File toFile
= new File(to
);
213 return copyXmlFile(fromFile
, toFile
);
216 private static IStatus
copyXmlFile(File fromFile
, File toFile
) {
218 if (!toFile
.exists()) {
219 toFile
.createNewFile();
221 } catch (IOException e
) {
222 String error
= Messages
.XmlUtils_ErrorCopyingFile
;
223 Activator
.logError(error
, e
);
224 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
227 try (FileInputStream fis
= new FileInputStream(fromFile
);
228 FileOutputStream fos
= new FileOutputStream(toFile
);
229 FileChannel source
= fis
.getChannel();
230 FileChannel destination
= fos
.getChannel();) {
231 destination
.transferFrom(source
, 0, source
.size());
232 } catch (IOException e
) {
233 String error
= Messages
.XmlUtils_ErrorCopyingFile
;
234 Activator
.logError(error
, e
);
235 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, error
, e
);
237 return Status
.OK_STATUS
;
241 * Get the IDs of all the analysis described in a single file
245 * @return The list of IDs
248 public static List
<String
> getAnalysisIdsFromFile(String fileName
) {
249 List
<String
> ids
= new ArrayList
<>();
250 File file
= getXmlFilesPath().addTrailingSeparator().append(fileName
).toFile();
253 /* Load the XML File */
254 DocumentBuilderFactory dbFactory
= DocumentBuilderFactory
.newInstance();
255 DocumentBuilder dBuilder
;
256 dBuilder
= dbFactory
.newDocumentBuilder();
257 Document doc
= dBuilder
.parse(file
);
258 doc
.getDocumentElement().normalize();
260 /* get State Providers modules */
261 NodeList stateproviderNodes
= doc
.getElementsByTagName(TmfXmlStrings
.STATE_PROVIDER
);
262 for (int i
= 0; i
< stateproviderNodes
.getLength(); i
++) {
263 ids
.add(nullToEmptyString(((Element
) stateproviderNodes
.item(i
)).getAttribute(TmfXmlStrings
.ID
)));
266 /* get patterns modules */
267 NodeList patternNodes
= doc
.getElementsByTagName(TmfXmlStrings
.PATTERN
);
268 for (int i
= 0; i
< patternNodes
.getLength(); i
++) {
269 ids
.add(nullToEmptyString(((Element
) patternNodes
.item(i
)).getAttribute(TmfXmlStrings
.ID
)));
271 } catch (ParserConfigurationException
| SAXException
| IOException e
) {
272 Activator
.logError("Failed to get analyses IDs from " + fileName
); //$NON-NLS-1$
279 * Get only the XML element children of an XML element.
282 * The parent element to get children from
283 * @return The list of children Element of the parent
285 public static List
<@Nullable Element
> getChildElements(Element parent
) {
286 NodeList childNodes
= parent
.getChildNodes();
287 List
<@Nullable Element
> childElements
= new ArrayList
<>();
288 for (int index
= 0; index
< childNodes
.getLength(); index
++) {
289 if (childNodes
.item(index
).getNodeType() == Node
.ELEMENT_NODE
) {
290 childElements
.add((Element
) childNodes
.item(index
));
293 return childElements
;
297 * Get the XML children element of an XML element, but only those of a
301 * The parent element to get the children from
303 * The tag of the elements to return
304 * @return The list of children {@link Element} of the parent
306 public static List
<@NonNull Element
> getChildElements(Element parent
, String elementTag
) {
307 /* get the state providers and find the corresponding one */
308 NodeList nodes
= parent
.getElementsByTagName(elementTag
);
309 List
<@NonNull Element
> childElements
= new ArrayList
<>();
311 for (int i
= 0; i
< nodes
.getLength(); i
++) {
312 Element node
= (Element
) nodes
.item(i
);
313 if (node
.getParentNode().equals(parent
)) {
314 childElements
.add(node
);
317 return childElements
;
321 * Return the node element corresponding to the requested type in the file.
323 * TODO: Nothing prevents from having duplicate type -> id in a same file.
324 * That should not be allowed. If you want an element with the same ID as
325 * another one, it should be in a different file and we should check it at
329 * The absolute path to the XML file
331 * The type of top level element to search for
333 * The ID of the desired element
334 * @return The XML element or <code>null</code> if not found
336 public static Element
getElementInFile(String filePath
, @NonNull String elementType
, @NonNull String elementId
) {
338 if (filePath
== null) {
342 IPath path
= new Path(filePath
);
343 File file
= path
.toFile();
344 if (file
== null || !file
.exists() || !file
.isFile() || !xmlValidate(file
).isOK()) {
349 /* Load the XML File */
350 DocumentBuilderFactory dbFactory
= DocumentBuilderFactory
.newInstance();
351 DocumentBuilder dBuilder
;
353 dBuilder
= dbFactory
.newDocumentBuilder();
354 Document doc
= dBuilder
.parse(file
);
355 doc
.getDocumentElement().normalize();
357 /* get the state providers and find the corresponding one */
358 NodeList nodes
= doc
.getElementsByTagName(elementType
);
359 Element foundNode
= null;
361 for (int i
= 0; i
< nodes
.getLength(); i
++) {
362 Element node
= (Element
) nodes
.item(i
);
363 String id
= node
.getAttribute(TmfXmlStrings
.ID
);
364 if (id
.equals(elementId
)) {
369 } catch (ParserConfigurationException
| SAXException
| IOException e
) {