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