tmf : Add manager for XML analysis files
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.analysis.xml.core / src / org / eclipse / tracecompass / tmf / analysis / xml / core / module / XmlUtils.java
CommitLineData
e11e382c 1/*******************************************************************************
f98e9dbe 2 * Copyright (c) 2014, 2016 École Polytechnique de Montréal
e11e382c
FW
3 *
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
8 *
9 * Contributors:
10 * Geneviève Bastien - Initial API and implementation
11 *******************************************************************************/
12
2bdf0193 13package org.eclipse.tracecompass.tmf.analysis.xml.core.module;
e11e382c 14
f98e9dbe
JCK
15import static org.eclipse.tracecompass.common.core.NonNullUtils.nullToEmptyString;
16
e11e382c
FW
17import java.io.File;
18import java.io.FileInputStream;
19import java.io.FileOutputStream;
20import java.io.IOException;
21import java.net.URL;
22import java.nio.channels.FileChannel;
0f7276b6 23import java.util.ArrayList;
f98e9dbe
JCK
24import java.util.Collections;
25import java.util.HashMap;
0f7276b6 26import java.util.List;
f98e9dbe 27import java.util.Map;
e11e382c
FW
28
29import javax.xml.XMLConstants;
6d20d989
GB
30import javax.xml.parsers.DocumentBuilder;
31import javax.xml.parsers.DocumentBuilderFactory;
32import javax.xml.parsers.ParserConfigurationException;
e11e382c
FW
33import javax.xml.transform.Source;
34import javax.xml.transform.stream.StreamSource;
35import javax.xml.validation.Schema;
36import javax.xml.validation.SchemaFactory;
37import javax.xml.validation.Validator;
38
39import org.eclipse.core.runtime.IPath;
40import org.eclipse.core.runtime.IStatus;
6d20d989 41import org.eclipse.core.runtime.Path;
e11e382c 42import org.eclipse.core.runtime.Status;
6d20d989 43import org.eclipse.jdt.annotation.NonNull;
4c4e2816 44import org.eclipse.jdt.annotation.Nullable;
e11e382c 45import org.eclipse.osgi.util.NLS;
2bdf0193
AM
46import org.eclipse.tracecompass.internal.tmf.analysis.xml.core.Activator;
47import org.eclipse.tracecompass.tmf.analysis.xml.core.stateprovider.TmfXmlStrings;
6d20d989 48import org.w3c.dom.Document;
0f7276b6
GB
49import org.w3c.dom.Element;
50import org.w3c.dom.Node;
51import org.w3c.dom.NodeList;
e11e382c
FW
52import org.xml.sax.SAXException;
53import org.xml.sax.SAXParseException;
54
55/**
56 * Class containing some utilities for the XML plug-in packages: for example, it
57 * manages the XML files and validates them
58 *
59 * @author Geneviève Bastien
60 */
61public class XmlUtils {
62
63 /** Sub-directory of the plug-in where XML files are stored */
64 private static final String XML_DIRECTORY = "xml_files"; //$NON-NLS-1$
65
66 /** Name of the XSD schema file */
f47f1bbe 67 private static final String XSD = "xmlDefinition.xsd"; //$NON-NLS-1$
e11e382c 68
f98e9dbe
JCK
69 /**
70 * Extension for XML files
71 * @since 2.0
72 */
73 public static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$
74
e11e382c
FW
75 /** Make this class non-instantiable */
76 private XmlUtils() {
77
78 }
79
80 /**
81 * Get the path where the XML files are stored. Create it if it does not
82 * exist
83 *
84 * @return path to XML files
85 */
86 public static IPath getXmlFilesPath() {
87 IPath path = Activator.getDefault().getStateLocation();
88 path = path.addTrailingSeparator().append(XML_DIRECTORY);
89
90 /* Check if directory exists, otherwise create it */
91 File dir = path.toFile();
92 if (!dir.exists() || !dir.isDirectory()) {
93 dir.mkdirs();
94 }
95
96 return path;
97 }
98
99 /**
100 * Validate the XML file input with the XSD schema
101 *
102 * @param xmlFile
103 * XML file to validate
104 * @return True if the XML validates
105 */
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);
110 try {
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);
0f7276b6 117 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e);
e11e382c
FW
118 } catch (SAXException e) {
119 String error = NLS.bind(Messages.XmlUtils_XmlValidationError, e.getLocalizedMessage());
120 Activator.logError(error);
0f7276b6 121 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e);
e11e382c
FW
122 } catch (IOException e) {
123 String error = Messages.XmlUtils_XmlValidateError;
124 Activator.logError("IO exception occurred", e); //$NON-NLS-1$
0f7276b6 125 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e);
e11e382c
FW
126 }
127 return Status.OK_STATUS;
128 }
129
130 /**
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.
134 *
135 * @param fromFile
136 * The XML file to add
137 * @return Whether the file was successfully added
138 */
139 public static IStatus addXmlFile(File fromFile) {
140
141 /* Copy file to path */
142 File toFile = getXmlFilesPath().addTrailingSeparator().append(fromFile.getName()).toFile();
143
f98e9dbe
JCK
144 return copyXmlFile(fromFile, toFile);
145 }
146
147 /**
148 * List all files under the XML analysis files path. It returns a map where
149 * the key is the file name.
150 *
151 * @return A map with all the XML analysis files
152 * @since 2.0
153 */
154 public static synchronized Map<String, File> listFile() {
155 Map<String, File> files = new HashMap<>();
156 File[] listOfFiles = getXmlFilesPath().toFile().listFiles();
157 for (File file : listOfFiles) {
158 files.put(file.getName(), file);
159 }
160 return Collections.unmodifiableMap(files);
161 }
162
163 /**
164 * Delete an XML analysis file
165 *
166 * @param name
167 * The XML file to delete
168 * @since 2.0
169 */
170 public static void deleteFile(String name) {
171 Map<String, File> files = listFile();
172 File file = files.get(name);
173 if (file == null) {
174 return;
175 }
176 file.delete();
177 }
178
179 /**
180 * Export an XML analysis file to an external path
181 *
182 * @param from
183 * The name of the file to export
184 * @param to
185 * The full path of the file to write to
186 * @return Whether the file was successfully exported
187 * @since 2.0
188 */
189 public static IStatus exportXmlFile(String from, String to) {
190
191 /* Copy file to path */
192 File fromFile = getXmlFilesPath().addTrailingSeparator().append(from).toFile();
193
194 if (!fromFile.exists()) {
195 Activator.logError("Failed to find XML analysis file " + fromFile.getName()); //$NON-NLS-1$
196 return Status.CANCEL_STATUS;
197 }
198
199 File toFile = new File(to);
200
201 return copyXmlFile(fromFile, toFile);
202 }
203
204 private static IStatus copyXmlFile(File fromFile, File toFile) {
e11e382c
FW
205 try {
206 if (!toFile.exists()) {
207 toFile.createNewFile();
208 }
209 } catch (IOException e) {
210 String error = Messages.XmlUtils_ErrorCopyingFile;
211 Activator.logError(error, e);
0f7276b6 212 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e);
e11e382c
FW
213 }
214
215 try (FileInputStream fis = new FileInputStream(fromFile);
216 FileOutputStream fos = new FileOutputStream(toFile);
217 FileChannel source = fis.getChannel();
218 FileChannel destination = fos.getChannel();) {
219 destination.transferFrom(source, 0, source.size());
220 } catch (IOException e) {
221 String error = Messages.XmlUtils_ErrorCopyingFile;
222 Activator.logError(error, e);
0f7276b6 223 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e);
e11e382c
FW
224 }
225 return Status.OK_STATUS;
226 }
227
f98e9dbe
JCK
228 /**
229 * Get the IDs of all the analysis described in a single file
230 *
231 * @param fileName
232 * The file name
233 * @return The list of IDs
234 * @since 2.0
235 */
236 public static List<String> getAnalysisIdsFromFile(String fileName) {
237 List<String> ids = new ArrayList<>();
238 File file = getXmlFilesPath().addTrailingSeparator().append(fileName).toFile();
239 if (file.exists()) {
240 try {
241 /* Load the XML File */
242 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
243 DocumentBuilder dBuilder;
244 dBuilder = dbFactory.newDocumentBuilder();
245 Document doc = dBuilder.parse(file);
246 doc.getDocumentElement().normalize();
247
248 /* get State Providers modules */
249 NodeList stateproviderNodes = doc.getElementsByTagName(TmfXmlStrings.STATE_PROVIDER);
250 for (int i = 0; i < stateproviderNodes.getLength(); i++) {
251 ids.add(nullToEmptyString(((Element) stateproviderNodes.item(i)).getAttribute(TmfXmlStrings.ID)));
252 }
253 } catch (ParserConfigurationException | SAXException | IOException e) {
254 Activator.logError("Failed to get analyses IDs from " + fileName); //$NON-NLS-1$
255 }
256 }
257 return ids;
258 }
259
0f7276b6
GB
260 /**
261 * Get only the XML element children of an XML element.
262 *
263 * @param parent
264 * The parent element to get children from
265 * @return The list of children Element of the parent
266 */
4c4e2816 267 public static List<@Nullable Element> getChildElements(Element parent) {
0f7276b6 268 NodeList childNodes = parent.getChildNodes();
4c4e2816 269 List<@Nullable Element> childElements = new ArrayList<>();
0f7276b6
GB
270 for (int index = 0; index < childNodes.getLength(); index++) {
271 if (childNodes.item(index).getNodeType() == Node.ELEMENT_NODE) {
272 childElements.add((Element) childNodes.item(index));
273 }
274 }
275 return childElements;
276 }
277
6d20d989
GB
278 /**
279 * Get the XML children element of an XML element, but only those of a
280 * certain type
281 *
282 * @param parent
283 * The parent element to get the children from
284 * @param elementTag
285 * The tag of the elements to return
286 * @return The list of children {@link Element} of the parent
287 */
4c4e2816 288 public static List<@NonNull Element> getChildElements(Element parent, String elementTag) {
6d20d989
GB
289 /* get the state providers and find the corresponding one */
290 NodeList nodes = parent.getElementsByTagName(elementTag);
4c4e2816 291 List<@NonNull Element> childElements = new ArrayList<>();
6d20d989
GB
292
293 for (int i = 0; i < nodes.getLength(); i++) {
294 Element node = (Element) nodes.item(i);
66471052
GB
295 if (node.getParentNode().equals(parent)) {
296 childElements.add(node);
297 }
6d20d989
GB
298 }
299 return childElements;
300 }
301
302 /**
303 * Return the node element corresponding to the requested type in the file.
304 *
305 * TODO: Nothing prevents from having duplicate type -> id in a same file.
306 * That should not be allowed. If you want an element with the same ID as
307 * another one, it should be in a different file and we should check it at
308 * validation time.
309 *
310 * @param filePath
311 * The absolute path to the XML file
312 * @param elementType
313 * The type of top level element to search for
314 * @param elementId
315 * The ID of the desired element
316 * @return The XML element or <code>null</code> if not found
317 */
318 public static Element getElementInFile(String filePath, @NonNull String elementType, @NonNull String elementId) {
319
320 if (filePath == null) {
321 return null;
322 }
323
324 IPath path = new Path(filePath);
325 File file = path.toFile();
326 if (file == null || !file.exists() || !file.isFile() || !xmlValidate(file).isOK()) {
327 return null;
328 }
329
330 try {
331 /* Load the XML File */
332 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
333 DocumentBuilder dBuilder;
334
335 dBuilder = dbFactory.newDocumentBuilder();
336 Document doc = dBuilder.parse(file);
337 doc.getDocumentElement().normalize();
338
339 /* get the state providers and find the corresponding one */
340 NodeList nodes = doc.getElementsByTagName(elementType);
341 Element foundNode = null;
342
343 for (int i = 0; i < nodes.getLength(); i++) {
344 Element node = (Element) nodes.item(i);
345 String id = node.getAttribute(TmfXmlStrings.ID);
346 if (id.equals(elementId)) {
347 foundNode = node;
348 }
349 }
350 return foundNode;
351 } catch (ParserConfigurationException | SAXException | IOException e) {
352 return null;
353 }
354
355 }
e11e382c 356}
This page took 0.080222 seconds and 5 git commands to generate.