7b28785e7187cd749f3c214a6eb0aebf7afd2708
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / parsers / custom / CustomXmlTraceDefinition.java
1 /*******************************************************************************
2 * Copyright (c) 2010, 2016 Ericsson
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 * Patrick Tasse - Initial API and implementation
11 * Matthew Khouzam - Add support for default xml parsers
12 *******************************************************************************/
13
14 package org.eclipse.tracecompass.tmf.core.parsers.custom;
15
16 import java.io.ByteArrayInputStream;
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.StringWriter;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.TreeSet;
31
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.OutputKeys;
36 import javax.xml.transform.Transformer;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.TransformerFactoryConfigurationError;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stream.StreamResult;
42
43 import org.eclipse.core.runtime.Platform;
44 import org.eclipse.jdt.annotation.NonNull;
45 import org.eclipse.tracecompass.internal.tmf.core.Activator;
46 import org.eclipse.tracecompass.tmf.core.project.model.TmfTraceType;
47 import org.w3c.dom.Document;
48 import org.w3c.dom.Element;
49 import org.w3c.dom.Node;
50 import org.w3c.dom.NodeList;
51 import org.xml.sax.EntityResolver;
52 import org.xml.sax.ErrorHandler;
53 import org.xml.sax.InputSource;
54 import org.xml.sax.SAXException;
55 import org.xml.sax.SAXParseException;
56
57 /**
58 * Trace definition for custom XML traces.
59 *
60 * @author Patrick Tassé
61 */
62 public class CustomXmlTraceDefinition extends CustomTraceDefinition {
63
64 /** Ignore tag
65 * @deprecated Use {@link org.eclipse.tracecompass.tmf.core.parsers.custom.CustomTraceDefinition.Tag#IGNORE} instead. */
66 @Deprecated
67 public static final String TAG_IGNORE = Messages.CustomXmlTraceDefinition_ignoreTag;
68
69 /**
70 * Custom XML label used internally and therefore should not be externalized
71 */
72 public static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$
73
74
75 /** Name of the default XML definitions file */
76 protected static final String CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_FILE_NAME = "custom_xml_default_parsers.xml"; //$NON-NLS-1$
77
78 /** Name of the XML definitions file */
79 protected static final String CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME = "custom_xml_parsers.xml"; //$NON-NLS-1$
80
81 /** Path to the XML definitions file */
82 protected static final String CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME =
83 Platform.getInstallLocation().getURL().getPath() + "templates/org.eclipse.linuxtools.tmf.core/" + //$NON-NLS-1$
84 CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_FILE_NAME;
85
86 /** Path to the XML definitions file */
87 protected static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME =
88 Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString();
89
90 /**
91 * Legacy path to the XML definitions file (in the UI plug-in of linux tools) TODO Remove
92 * once we feel the transition phase is over.
93 */
94 private static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI =
95 Activator.getDefault().getStateLocation().removeLastSegments(1).addTrailingSeparator()
96 .append("org.eclipse.linuxtools.tmf.ui") //$NON-NLS-1$
97 .append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString();
98
99 /**
100 * Legacy path to the XML definitions file (in the core plug-in of linux tools) TODO Remove
101 * once we feel the transition phase is over.
102 */
103 private static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE =
104 Activator.getDefault().getStateLocation().removeLastSegments(1).addTrailingSeparator()
105 .append("org.eclipse.linuxtools.tmf.core") //$NON-NLS-1$
106 .append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString();
107
108 // TODO: These strings should not be externalized
109 private static final String CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomXmlTraceDefinition_definitionRootElement;
110 private static final String DEFINITION_ELEMENT = Messages.CustomXmlTraceDefinition_definition;
111 private static final String CATEGORY_ATTRIBUTE = Messages.CustomXmlTraceDefinition_category;
112 private static final String TAG_ATTRIBUTE = Messages.CustomXmlTraceDefinition_tag;
113 private static final String NAME_ATTRIBUTE = Messages.CustomXmlTraceDefinition_name;
114 private static final String LOG_ENTRY_ATTRIBUTE = Messages.CustomXmlTraceDefinition_logEntry;
115 private static final String EVENT_TYPE_ATTRIBUTE = Messages.CustomXmlTraceDefinition_eventType;
116 private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomXmlTraceDefinition_timestampOutputFormat;
117 private static final String INPUT_ELEMENT_ELEMENT = Messages.CustomXmlTraceDefinition_inputElement;
118 private static final String ATTRIBUTE_ELEMENT = Messages.CustomXmlTraceDefinition_attribute;
119 private static final String INPUT_DATA_ELEMENT = Messages.CustomXmlTraceDefinition_inputData;
120 private static final String ACTION_ATTRIBUTE = Messages.CustomXmlTraceDefinition_action;
121 private static final String FORMAT_ATTRIBUTE = Messages.CustomXmlTraceDefinition_format;
122 private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomXmlTraceDefinition_outputColumn;
123
124 /**
125 * This is the value that the extension sets for traceContentType to be able
126 * to load an XML parser
127 **/
128 private static final String TRACE_CONTENT_TYPE_ATTRIBUTE_VALUE = "xml"; //$NON-NLS-1$
129
130 /** Top-level input element */
131 public CustomXmlInputElement rootInputElement;
132
133 /**
134 * Default constructor
135 */
136 public CustomXmlTraceDefinition() {
137 this(CUSTOM_XML_CATEGORY, "", null, new ArrayList<OutputColumn>(), ""); //$NON-NLS-1$ //$NON-NLS-2$
138 }
139
140 /**
141 * Full constructor
142 *
143 * @param category
144 * Category of the trace type
145 * @param traceType
146 * Name of the trace type
147 * @param rootElement
148 * The top-level XML element
149 * @param outputs
150 * The list of output columns
151 * @param timeStampOutputFormat
152 * The timestamp format to use
153 */
154 public CustomXmlTraceDefinition(String category, String traceType, CustomXmlInputElement rootElement,
155 List<OutputColumn> outputs, String timeStampOutputFormat) {
156 this.categoryName = category;
157 this.definitionName = traceType;
158 this.rootInputElement = rootElement;
159 this.outputs = outputs;
160 this.timeStampOutputFormat = timeStampOutputFormat;
161 }
162
163 @Override
164 public void save() {
165 save(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
166 }
167
168 @Override
169 public void save(String path) {
170 try {
171 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
172 DocumentBuilder db = dbf.newDocumentBuilder();
173
174 // The following allows xml parsing without access to the dtd
175 db.setEntityResolver(createEmptyEntityResolver());
176
177 // The following catches xml parsing exceptions
178 db.setErrorHandler(createErrorHandler());
179
180 Document doc = null;
181 File file = new File(path);
182 if (file.canRead()) {
183 doc = db.parse(file);
184 if (!doc.getDocumentElement().getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
185 Activator.logError(String.format("Error saving CustomXmlTraceDefinition: path=%s is not a valid custom parser file", path)); //$NON-NLS-1$
186 return;
187 }
188 } else {
189 doc = db.newDocument();
190 Node node = doc.createElement(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT);
191 doc.appendChild(node);
192 }
193
194 Element root = doc.getDocumentElement();
195
196 Element oldDefinitionElement = findDefinitionElement(root, categoryName, definitionName);
197 if (oldDefinitionElement != null) {
198 root.removeChild(oldDefinitionElement);
199 }
200 Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
201 root.appendChild(definitionElement);
202 definitionElement.setAttribute(CATEGORY_ATTRIBUTE, categoryName);
203 definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);
204
205 if (timeStampOutputFormat != null && !timeStampOutputFormat.isEmpty()) {
206 Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
207 definitionElement.appendChild(formatElement);
208 formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));
209 }
210
211 if (rootInputElement != null) {
212 definitionElement.appendChild(createInputElementElement(rootInputElement, doc));
213 }
214
215 if (outputs != null) {
216 for (OutputColumn output : outputs) {
217 Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
218 definitionElement.appendChild(outputColumnElement);
219 outputColumnElement.setAttribute(TAG_ATTRIBUTE, output.tag.name());
220 outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
221 }
222 }
223
224 Transformer transformer = TransformerFactory.newInstance().newTransformer();
225 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
226
227 // initialize StreamResult with File object to save to file
228 StreamResult result = new StreamResult(new StringWriter());
229 DOMSource source = new DOMSource(doc);
230 transformer.transform(source, result);
231 String xmlString = result.getWriter().toString();
232
233 try (FileWriter writer = new FileWriter(file);) {
234 writer.write(xmlString);
235 }
236
237 TmfTraceType.addCustomTraceType(CustomXmlTrace.class, categoryName, definitionName);
238
239 } catch (ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException | IOException | SAXException e) {
240 Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
241 }
242 }
243
244 private Element createInputElementElement(CustomXmlInputElement inputElement, Document doc) {
245 Element inputElementElement = doc.createElement(INPUT_ELEMENT_ELEMENT);
246 inputElementElement.setAttribute(NAME_ATTRIBUTE, inputElement.getElementName());
247
248 if (inputElement.isLogEntry()) {
249 inputElementElement.setAttribute(LOG_ENTRY_ATTRIBUTE, Boolean.toString(inputElement.isLogEntry()));
250 }
251
252 if (inputElement.getEventType() != null) {
253 inputElementElement.setAttribute(EVENT_TYPE_ATTRIBUTE, inputElement.getEventType());
254 }
255
256 if (inputElement.getParentElement() != null) {
257 Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT);
258 inputElementElement.appendChild(inputDataElement);
259 inputDataElement.setAttribute(TAG_ATTRIBUTE, inputElement.getInputTag().name());
260 inputDataElement.setAttribute(NAME_ATTRIBUTE, inputElement.getInputName());
261 inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputElement.getInputAction()));
262 String inputFormat = inputElement.getInputFormat();
263 if (inputFormat != null && !inputFormat.isEmpty()) {
264 inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputFormat);
265 }
266 }
267
268 if (inputElement.getAttributes() != null) {
269 for (CustomXmlInputAttribute attribute : inputElement.getAttributes()) {
270 Element inputAttributeElement = doc.createElement(ATTRIBUTE_ELEMENT);
271 inputElementElement.appendChild(inputAttributeElement);
272 inputAttributeElement.setAttribute(NAME_ATTRIBUTE, attribute.getAttributeName());
273 Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT);
274 inputAttributeElement.appendChild(inputDataElement);
275 inputDataElement.setAttribute(TAG_ATTRIBUTE, attribute.getInputTag().name());
276 inputDataElement.setAttribute(NAME_ATTRIBUTE, attribute.getInputName());
277 inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(attribute.getInputAction()));
278 String inputFormat = attribute.getInputFormat();
279 if (inputFormat != null && !inputFormat.isEmpty()) {
280 inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputFormat);
281 }
282 }
283 }
284
285 if (inputElement.getChildElements() != null) {
286 for (CustomXmlInputElement childInputElement : inputElement.getChildElements()) {
287 inputElementElement.appendChild(createInputElementElement(childInputElement, doc));
288 }
289 }
290
291 return inputElementElement;
292 }
293
294 /**
295 * Load all custom XML trace definitions, including the user-defined and
296 * default (built-in) parsers.
297 *
298 * @return The loaded trace definitions
299 */
300 public static CustomXmlTraceDefinition[] loadAll() {
301 return loadAll(true);
302 }
303
304 /**
305 * Load all custom XML trace definitions, including the user-defined and,
306 * optionally, the default (built-in) parsers.
307 *
308 * @param includeDefaults
309 * if true, the default (built-in) parsers are included
310 *
311 * @return The loaded trace definitions
312 */
313 public static CustomXmlTraceDefinition[] loadAll(boolean includeDefaults) {
314 File defaultFile = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
315 File legacyFileUI = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI);
316 File legacyFileCore = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE);
317
318 /*
319 * If there is no file at the expected location, check the legacy
320 * locations instead.
321 */
322 if (!defaultFile.exists()) {
323 if (legacyFileCore.exists()) {
324 transferDefinitions(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE);
325 } else if (legacyFileUI.exists()) {
326 transferDefinitions(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI);
327 }
328 }
329
330 Set<CustomXmlTraceDefinition> defs = new TreeSet<>(new Comparator<CustomXmlTraceDefinition>() {
331 @Override
332 public int compare(CustomXmlTraceDefinition o1, CustomXmlTraceDefinition o2) {
333 int result = o1.categoryName.compareTo(o2.categoryName);
334 if (result != 0) {
335 return result;
336 }
337 return o1.definitionName.compareTo(o2.definitionName);
338 }
339 });
340 defs.addAll(Arrays.asList(loadAll(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME)));
341 if (includeDefaults) {
342 defs.addAll(Arrays.asList(loadAll(CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME)));
343
344 // Also load definitions contributed by extensions
345 Collection<String> paths = getExtensionDefinitionsPaths(TRACE_CONTENT_TYPE_ATTRIBUTE_VALUE);
346 for (String customTraceDefinitionPath : paths) {
347 defs.addAll(Arrays.asList(loadAll(customTraceDefinitionPath)));
348 }
349 }
350 return defs.toArray(new CustomXmlTraceDefinition[0]);
351 }
352
353 private static void transferDefinitions(String defFile) {
354 CustomXmlTraceDefinition[] oldDefs = loadAll(defFile);
355 for (CustomXmlTraceDefinition def : oldDefs) {
356 /* Save in the new location */
357 def.save();
358 }
359 }
360
361
362 /**
363 * Load all the XML trace definitions in the given definitions file.
364 *
365 * @param path
366 * Path to the definitions file to load
367 * @return The loaded trace definitions
368 */
369 public static CustomXmlTraceDefinition[] loadAll(String path) {
370 File file = new File(path);
371 if (!file.canRead()) {
372 return new CustomXmlTraceDefinition[0];
373 }
374 try (FileInputStream fis = new FileInputStream(file);) {
375 return loadAll(fis);
376 } catch (IOException e) {
377 Activator.logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
378 }
379 return new CustomXmlTraceDefinition[0];
380 }
381
382 /**
383 * Load all the XML trace definitions from the given stream
384 *
385 * @param stream
386 * An input stream from which to read the definitions
387 * @return The loaded trace definitions
388 */
389 public static CustomXmlTraceDefinition[] loadAll(InputStream stream) {
390 try {
391 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
392 DocumentBuilder db = dbf.newDocumentBuilder();
393
394 // The following allows xml parsing without access to the dtd
395 db.setEntityResolver(createEmptyEntityResolver());
396
397 // The following catches xml parsing exceptions
398 db.setErrorHandler(createErrorHandler());
399
400 Document doc = db.parse(stream);
401 Element root = doc.getDocumentElement();
402 if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
403 return new CustomXmlTraceDefinition[0];
404 }
405
406 ArrayList<CustomXmlTraceDefinition> defList = new ArrayList<>();
407 NodeList nodeList = root.getChildNodes();
408 for (int i = 0; i < nodeList.getLength(); i++) {
409 Node node = nodeList.item(i);
410 if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) {
411 CustomXmlTraceDefinition def = extractDefinition((Element) node);
412 if (def != null) {
413 defList.add(def);
414 }
415 }
416 }
417 return defList.toArray(new CustomXmlTraceDefinition[0]);
418 } catch (ParserConfigurationException | SAXException | IOException e) {
419 Activator.logError("Error loading all in CustomXmlTraceDefinition: path=" + stream, e); //$NON-NLS-1$
420 }
421 return new CustomXmlTraceDefinition[0];
422 }
423
424 /**
425 * Load the given trace definition.
426 *
427 * @param categoryName
428 * Category of the definition to load
429 * @param definitionName
430 * Name of the XML trace definition to load
431 * @return The loaded trace definition
432 */
433 public static CustomXmlTraceDefinition load(String categoryName, String definitionName) {
434 try {
435 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
436 DocumentBuilder db = dbf.newDocumentBuilder();
437
438 // The following allows xml parsing without access to the dtd
439 EntityResolver resolver = new EntityResolver() {
440 @Override
441 public InputSource resolveEntity(String publicId, String systemId) {
442 String empty = ""; //$NON-NLS-1$
443 ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
444 return new InputSource(bais);
445 }
446 };
447 db.setEntityResolver(resolver);
448
449 // The following catches xml parsing exceptions
450 db.setErrorHandler(new ErrorHandler() {
451 @Override
452 public void error(SAXParseException saxparseexception) throws SAXException {
453 }
454
455 @Override
456 public void warning(SAXParseException saxparseexception) throws SAXException {
457 }
458
459 @Override
460 public void fatalError(SAXParseException saxparseexception) throws SAXException {
461 throw saxparseexception;
462 }
463 });
464
465 CustomXmlTraceDefinition value = lookupXmlDefinition(categoryName, definitionName, db, CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
466 if (value == null) {
467 value = lookupXmlDefinition(categoryName, definitionName, db, CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME);
468 }
469 return value;
470 } catch (ParserConfigurationException | SAXException | IOException e) {
471 Activator.logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
472 }
473 return null;
474 }
475
476 private static CustomXmlTraceDefinition lookupXmlDefinition(String categoryName, String definitionName, DocumentBuilder db, String source) throws SAXException, IOException {
477 File file = new File(source);
478 if (!file.exists()) {
479 return null;
480 }
481
482 Document doc = db.parse(file);
483
484 Element root = doc.getDocumentElement();
485 if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
486 return null;
487 }
488
489 Element definitionElement = findDefinitionElement(root, categoryName, definitionName);
490 if (definitionElement != null) {
491 return extractDefinition(definitionElement);
492 }
493 return null;
494 }
495
496 private static Element findDefinitionElement(Element root, String categoryName, String definitionName) {
497 NodeList nodeList = root.getChildNodes();
498 for (int i = 0; i < nodeList.getLength(); i++) {
499 Node node = nodeList.item(i);
500 if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) {
501 Element element = (Element) node;
502 String categoryAttribute = element.getAttribute(CATEGORY_ATTRIBUTE);
503 if (categoryAttribute.isEmpty()) {
504 categoryAttribute = CUSTOM_XML_CATEGORY;
505 }
506 String nameAttribute = element.getAttribute(NAME_ATTRIBUTE);
507 if (categoryName.equals(categoryAttribute) &&
508 definitionName.equals(nameAttribute)) {
509 return element;
510 }
511 }
512 }
513 return null;
514 }
515
516 /**
517 * Extract a trace definition from an XML element.
518 *
519 * @param definitionElement
520 * Definition element
521 * @return The extracted trace definition
522 */
523 public static CustomXmlTraceDefinition extractDefinition(Element definitionElement) {
524 CustomXmlTraceDefinition def = new CustomXmlTraceDefinition();
525
526 def.categoryName = definitionElement.getAttribute(CATEGORY_ATTRIBUTE);
527 if (def.categoryName.isEmpty()) {
528 def.categoryName = CUSTOM_XML_CATEGORY;
529 }
530 def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE);
531 if (def.definitionName.isEmpty()) {
532 return null;
533 }
534
535 NodeList nodeList = definitionElement.getChildNodes();
536 for (int i = 0; i < nodeList.getLength(); i++) {
537 Node node = nodeList.item(i);
538 String nodeName = node.getNodeName();
539 if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) {
540 Element formatElement = (Element) node;
541 def.timeStampOutputFormat = formatElement.getTextContent();
542 } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) {
543 CustomXmlInputElement inputElement = extractInputElement((Element) node);
544 if (inputElement != null) {
545 if (def.rootInputElement == null) {
546 def.rootInputElement = inputElement;
547 } else {
548 return null;
549 }
550 }
551 } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) {
552 Element outputColumnElement = (Element) node;
553 Entry<@NonNull Tag, @NonNull String> entry = extractTagAndName(outputColumnElement, TAG_ATTRIBUTE, NAME_ATTRIBUTE);
554 OutputColumn outputColumn = new OutputColumn(entry.getKey(), entry.getValue());
555 def.outputs.add(outputColumn);
556 }
557 }
558 return def;
559 }
560
561 private static CustomXmlInputElement extractInputElement(Element inputElementElement) {
562 CustomXmlInputElement inputElement = new CustomXmlInputElement();
563 inputElement.setElementName(inputElementElement.getAttribute(NAME_ATTRIBUTE));
564 inputElement.setLogEntry((Boolean.toString(true).equals(inputElementElement.getAttribute(LOG_ENTRY_ATTRIBUTE))) ? true : false);
565 String eventType = inputElementElement.getAttribute(EVENT_TYPE_ATTRIBUTE);
566 inputElement.setEventType(eventType.isEmpty() ? null : eventType);
567 NodeList nodeList = inputElementElement.getChildNodes();
568 for (int i = 0; i < nodeList.getLength(); i++) {
569 Node node = nodeList.item(i);
570 String nodeName = node.getNodeName();
571 if (nodeName.equals(INPUT_DATA_ELEMENT)) {
572 Element inputDataElement = (Element) node;
573 Entry<@NonNull Tag, @NonNull String> entry = extractTagAndName(inputDataElement, TAG_ATTRIBUTE, NAME_ATTRIBUTE);
574 inputElement.setInputTag(entry.getKey());
575 inputElement.setInputName(entry.getValue());
576 inputElement.setInputAction(Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE)));
577 inputElement.setInputFormat(inputDataElement.getAttribute(FORMAT_ATTRIBUTE));
578 } else if (nodeName.equals(ATTRIBUTE_ELEMENT)) {
579 Element attributeElement = (Element) node;
580
581 String attributeName = attributeElement.getAttribute(NAME_ATTRIBUTE);
582 NodeList attributeNodeList = attributeElement.getChildNodes();
583 for (int j = 0; j < attributeNodeList.getLength(); j++) {
584 Node attributeNode = attributeNodeList.item(j);
585 String attributeNodeName = attributeNode.getNodeName();
586 if (attributeNodeName.equals(INPUT_DATA_ELEMENT)) {
587 Element inputDataElement = (Element) attributeNode;
588 Entry<@NonNull Tag, @NonNull String> entry = extractTagAndName(inputDataElement, TAG_ATTRIBUTE, NAME_ATTRIBUTE);
589 int action = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE));
590 String format = inputDataElement.getAttribute(FORMAT_ATTRIBUTE);
591 inputElement.addAttribute(new CustomXmlInputAttribute(attributeName, entry.getKey(), entry.getValue(), action, format));
592 break;
593 }
594 }
595 } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) {
596 Element childInputElementElement = (Element) node;
597 CustomXmlInputElement childInputElement = extractInputElement(childInputElementElement);
598 if (childInputElement != null) {
599 inputElement.addChild(childInputElement);
600 }
601 }
602 }
603 return inputElement;
604 }
605
606 /**
607 * Delete a definition from the currently loaded ones.
608 *
609 * @param categoryName
610 * The category of the definition to delete
611 * @param definitionName
612 * The name of the definition to delete
613 */
614 public static void delete(String categoryName, String definitionName) {
615 try {
616 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
617 DocumentBuilder db = dbf.newDocumentBuilder();
618
619 // The following allows xml parsing without access to the dtd
620 EntityResolver resolver = new EntityResolver() {
621 @Override
622 public InputSource resolveEntity(String publicId, String systemId) {
623 String empty = ""; //$NON-NLS-1$
624 ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
625 return new InputSource(bais);
626 }
627 };
628 db.setEntityResolver(resolver);
629
630 // The following catches xml parsing exceptions
631 db.setErrorHandler(new ErrorHandler() {
632 @Override
633 public void error(SAXParseException saxparseexception) throws SAXException {
634 }
635
636 @Override
637 public void warning(SAXParseException saxparseexception) throws SAXException {
638 }
639
640 @Override
641 public void fatalError(SAXParseException saxparseexception) throws SAXException {
642 throw saxparseexception;
643 }
644 });
645
646 File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
647 Document doc = db.parse(file);
648
649 Element root = doc.getDocumentElement();
650 if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
651 return;
652 }
653
654 Element definitionElement = findDefinitionElement(root, categoryName, definitionName);
655 if (definitionElement != null) {
656 root.removeChild(definitionElement);
657 }
658
659 Transformer transformer = TransformerFactory.newInstance().newTransformer();
660 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
661
662 // initialize StreamResult with File object to save to file
663 StreamResult result = new StreamResult(new StringWriter());
664 DOMSource source = new DOMSource(doc);
665 transformer.transform(source, result);
666 String xmlString = result.getWriter().toString();
667
668 try (FileWriter writer = new FileWriter(file);) {
669 writer.write(xmlString);
670 }
671
672 TmfTraceType.removeCustomTraceType(CustomXmlTrace.class, categoryName, definitionName);
673 // Check if default definition needs to be reloaded
674 TmfTraceType.addCustomTraceType(CustomXmlTrace.class, categoryName, definitionName);
675
676 } catch (ParserConfigurationException | SAXException | IOException | TransformerFactoryConfigurationError | TransformerException e) {
677 Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
678 }
679 }
680 }
This page took 0.044344 seconds and 4 git commands to generate.