087c5bd20c7f4b35273d75aa2d1ecfd90d505440
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / parsers / custom / CustomTxtTraceDefinition.java
1 /*******************************************************************************
2 * Copyright (c) 2010, 2015 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 parsers
12 *******************************************************************************/
13
14 package org.eclipse.tracecompass.tmf.core.parsers.custom;
15
16 import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
17
18 import java.io.File;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.StringWriter;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Comparator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.TreeSet;
29 import java.util.regex.Pattern;
30 import java.util.regex.PatternSyntaxException;
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.TransformerConfigurationException;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.TransformerFactory;
40 import javax.xml.transform.TransformerFactoryConfigurationError;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
43
44 import org.eclipse.core.runtime.Platform;
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.SAXException;
52
53 /**
54 * Trace definition for custom text traces.
55 *
56 * @author Patrick Tassé
57 */
58 public class CustomTxtTraceDefinition extends CustomTraceDefinition {
59
60 /** Input lines */
61 public List<InputLine> inputs;
62
63 /**
64 * Custom text label used internally and therefore should not be
65 * externalized
66 */
67 public static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$
68
69
70 /** File name of the default definition file */
71 protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_FILE_NAME = "custom_txt_default_parsers.xml"; //$NON-NLS-1$
72 /** File name of the definition file */
73 protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME = "custom_txt_parsers.xml"; //$NON-NLS-1$
74
75 /** Path of the definition file */
76 protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_PATH_NAME =
77 Platform.getInstallLocation().getURL().getPath() + "templates/org.eclipse.linuxtools.tmf.core/" + //$NON-NLS-1$
78 CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_FILE_NAME;
79 /** Path of the definition file */
80 protected static final String CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME =
81 Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME).toString();
82
83 /**
84 * Legacy path to the XML definitions file (in the UI plug-in of linuxtools) TODO Remove
85 * once we feel the transition phase is over.
86 */
87 private static final String CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI =
88 Activator.getDefault().getStateLocation().removeLastSegments(1).addTrailingSeparator()
89 .append("org.eclipse.linuxtools.tmf.ui") //$NON-NLS-1$
90 .append(CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME).toString();
91
92 /**
93 * Legacy path to the XML definitions file (in the core plug-in of linuxtools) TODO Remove
94 * once we feel the transition phase is over.
95 */
96 private static final String CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE =
97 Activator.getDefault().getStateLocation().removeLastSegments(1).addTrailingSeparator()
98 .append("org.eclipse.linuxtools.tmf.core") //$NON-NLS-1$
99 .append(CUSTOM_TXT_TRACE_DEFINITIONS_FILE_NAME).toString();
100
101 private static final String CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomTxtTraceDefinition_definitionRootElement;
102 private static final String DEFINITION_ELEMENT = Messages.CustomTxtTraceDefinition_definition;
103 private static final String CATEGORY_ATTRIBUTE = Messages.CustomTxtTraceDefinition_category;
104 private static final String NAME_ATTRIBUTE = Messages.CustomTxtTraceDefinition_name;
105 private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomTxtTraceDefinition_timestampOutputFormat;
106 private static final String INPUT_LINE_ELEMENT = Messages.CustomTxtTraceDefinition_inputLine;
107 private static final String CARDINALITY_ELEMENT = Messages.CustomTxtTraceDefinition_cardinality;
108 private static final String MIN_ATTRIBUTE = Messages.CustomTxtTraceDefinition_min;
109 private static final String MAX_ATTRIBUTE = Messages.CustomTxtTraceDefinition_max;
110 private static final String REGEX_ELEMENT = Messages.CustomTxtTraceDefinition_regEx;
111 private static final String INPUT_DATA_ELEMENT = Messages.CustomTxtTraceDefinition_inputData;
112 private static final String ACTION_ATTRIBUTE = Messages.CustomTxtTraceDefinition_action;
113 private static final String FORMAT_ATTRIBUTE = Messages.CustomTxtTraceDefinition_format;
114 private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomTxtTraceDefinition_outputColumn;
115
116 /**
117 * Default constructor.
118 */
119 public CustomTxtTraceDefinition() {
120 this(CUSTOM_TXT_CATEGORY, "", new ArrayList<InputLine>(0), new ArrayList<OutputColumn>(0), ""); //$NON-NLS-1$ //$NON-NLS-2$
121 }
122
123 /**
124 * Full constructor.
125 *
126 * @param category
127 * Category of the trace type
128 * @param traceType
129 * Name of the trace type
130 * @param inputs
131 * List of inputs
132 * @param outputs
133 * List of output columns
134 * @param timeStampOutputFormat
135 * The timestamp format to use
136 */
137 public CustomTxtTraceDefinition(String category, String traceType, List<InputLine> inputs,
138 List<OutputColumn> outputs, String timeStampOutputFormat) {
139 this.categoryName = category;
140 this.definitionName = traceType;
141 this.inputs = inputs;
142 this.outputs = outputs;
143 this.timeStampOutputFormat = timeStampOutputFormat;
144 }
145
146 /**
147 * Wrapper to store a line of the log file
148 */
149 public static class InputLine {
150
151 /** Data columns of this line */
152 public List<InputData> columns;
153
154 /** Cardinality of this line (see {@link Cardinality}) */
155 public Cardinality cardinality;
156
157 /** Parent line */
158 public InputLine parentInput;
159
160 /** Level of this line */
161 public int level;
162
163 /** Next input line in the file */
164 public InputLine nextInput;
165
166 /** Children of this line (if one "event" spans many lines) */
167 public List<InputLine> childrenInputs;
168
169 private String regex;
170 private Pattern pattern;
171
172 /**
173 * Default (empty) constructor.
174 */
175 public InputLine() {
176 }
177
178 /**
179 * Constructor.
180 *
181 * @param cardinality
182 * Cardinality of this line.
183 * @param regex
184 * Regex
185 * @param columns
186 * Columns to use
187 */
188 public InputLine(Cardinality cardinality, String regex, List<InputData> columns) {
189 this.cardinality = cardinality;
190 this.regex = regex;
191 this.columns = columns;
192 }
193
194 /**
195 * Set the regex of this input line
196 *
197 * @param regex
198 * Regex to set
199 */
200 public void setRegex(String regex) {
201 this.regex = regex;
202 this.pattern = null;
203 }
204
205 /**
206 * Get the current regex
207 *
208 * @return The current regex
209 */
210 public String getRegex() {
211 return regex;
212 }
213
214 /**
215 * Get the Pattern object of this line's regex
216 *
217 * @return The Pattern
218 * @throws PatternSyntaxException
219 * If the regex does not parse correctly
220 */
221 public Pattern getPattern() throws PatternSyntaxException {
222 if (pattern == null) {
223 pattern = Pattern.compile(regex);
224 }
225 return pattern;
226 }
227
228 /**
229 * Add a child line to this line.
230 *
231 * @param input
232 * The child input line
233 */
234 public void addChild(InputLine input) {
235 if (childrenInputs == null) {
236 childrenInputs = new ArrayList<>(1);
237 } else if (childrenInputs.size() > 0) {
238 InputLine last = childrenInputs.get(childrenInputs.size() - 1);
239 last.nextInput = input;
240 }
241 childrenInputs.add(input);
242 input.parentInput = this;
243 input.level = this.level + 1;
244 }
245
246 /**
247 * Set the next input line.
248 *
249 * @param input
250 * The next input line
251 */
252 public void addNext(InputLine input) {
253 if (parentInput != null) {
254 int index = parentInput.childrenInputs.indexOf(this);
255 parentInput.childrenInputs.add(index + 1, input);
256 InputLine next = nextInput;
257 nextInput = input;
258 input.nextInput = next;
259 }
260 input.parentInput = this.parentInput;
261 input.level = this.level;
262 }
263
264 /**
265 * Move this line up in its parent's children.
266 */
267 public void moveUp() {
268 if (parentInput != null) {
269 int index = parentInput.childrenInputs.indexOf(this);
270 if (index > 0) {
271 parentInput.childrenInputs.add(index - 1, parentInput.childrenInputs.remove(index));
272 parentInput.childrenInputs.get(index).nextInput = nextInput;
273 nextInput = parentInput.childrenInputs.get(index);
274 }
275 }
276 }
277
278 /**
279 * Move this line down in its parent's children.
280 */
281 public void moveDown() {
282 if (parentInput != null) {
283 int index = parentInput.childrenInputs.indexOf(this);
284 if (index < parentInput.childrenInputs.size() - 1) {
285 parentInput.childrenInputs.add(index + 1, parentInput.childrenInputs.remove(index));
286 nextInput = parentInput.childrenInputs.get(index).nextInput;
287 parentInput.childrenInputs.get(index).nextInput = this;
288 }
289 }
290 }
291
292 /**
293 * Add a data column to this line
294 *
295 * @param column
296 * The column to add
297 */
298 public void addColumn(InputData column) {
299 if (columns == null) {
300 columns = new ArrayList<>(1);
301 }
302 columns.add(column);
303 }
304
305 /**
306 * Get the next input lines.
307 *
308 * @param countMap
309 * The map of line "sets".
310 * @return The next list of lines.
311 */
312 public List<InputLine> getNextInputs(Map<InputLine, Integer> countMap) {
313 List<InputLine> nextInputs = new ArrayList<>();
314 InputLine next = nextInput;
315 while (next != null) {
316 nextInputs.add(next);
317 if (next.cardinality.min > 0) {
318 return nextInputs;
319 }
320 next = next.nextInput;
321 }
322 if (parentInput != null && parentInput.level > 0) {
323 int parentCount = checkNotNull(countMap.get(parentInput));
324 if (parentCount < parentInput.getMaxCount()) {
325 nextInputs.add(parentInput);
326 }
327 if (parentCount < parentInput.getMinCount()) {
328 return nextInputs;
329 }
330 nextInputs.addAll(parentInput.getNextInputs(countMap));
331 }
332 return nextInputs;
333 }
334
335 /**
336 * Get the minimum possible amount of entries.
337 *
338 * @return The minimum
339 */
340 public int getMinCount() {
341 return cardinality.min;
342 }
343
344 /**
345 * Get the maximum possible amount of entries.
346 *
347 * @return The maximum
348 */
349 public int getMaxCount() {
350 return cardinality.max;
351 }
352
353 @Override
354 public String toString() {
355 return regex + " " + cardinality; //$NON-NLS-1$
356 }
357 }
358
359 /**
360 * Data column for input lines.
361 */
362 public static class InputData {
363
364 /** Name of this column */
365 public String name;
366
367 /** Action id */
368 public int action;
369
370 /** Format */
371 public String format;
372
373 /**
374 * Default (empty) constructor
375 */
376 public InputData() {
377 }
378
379 /**
380 * Full constructor
381 *
382 * @param name
383 * Name
384 * @param action
385 * Action
386 * @param format
387 * Format
388 */
389 public InputData(String name, int action, String format) {
390 this.name = name;
391 this.action = action;
392 this.format = format;
393 }
394
395 /**
396 * Constructor with default format
397 *
398 * @param name
399 * Name
400 * @param action
401 * Action
402 */
403 public InputData(String name, int action) {
404 this.name = name;
405 this.action = action;
406 }
407 }
408
409 /**
410 * Input line cardinality
411 */
412 public static class Cardinality {
413
414 /** Representation of infinity */
415 public static final int INF = Integer.MAX_VALUE;
416
417 /** Preset for [1, 1] */
418 public static final Cardinality ONE = new Cardinality(1, 1);
419
420 /** Preset for [1, inf] */
421 public static final Cardinality ONE_OR_MORE = new Cardinality(1, INF);
422
423 /** Preset for [0, 1] */
424 public static final Cardinality ZERO_OR_ONE = new Cardinality(0, 1);
425
426 /** Preset for [0, inf] */
427 public static final Cardinality ZERO_OR_MORE = new Cardinality(0, INF);
428
429 private final int min;
430 private final int max;
431
432 /**
433 * Constructor.
434 *
435 * @param min
436 * Minimum
437 * @param max
438 * Maximum
439 */
440 public Cardinality(int min, int max) {
441 this.min = min;
442 this.max = max;
443 }
444
445 @Override
446 public String toString() {
447 return "(" + (min >= 0 ? min : "?") + ',' + (max == INF ? "\u221E" : (max >= 0 ? max : "?")) + ')'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
448 }
449
450 @Override
451 public int hashCode() {
452 final int prime = 31;
453 int result = 1;
454 result = prime * result + max;
455 result = prime * result + min;
456 return result;
457 }
458
459 @Override
460 public boolean equals(Object obj) {
461 if (this == obj) {
462 return true;
463 }
464 if (obj == null) {
465 return false;
466 }
467 if (!(obj instanceof Cardinality)) {
468 return false;
469 }
470 Cardinality other = (Cardinality) obj;
471 return (this.min == other.min && this.max == other.max);
472 }
473 }
474
475 @Override
476 public void save() {
477 save(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME);
478 }
479
480 @Override
481 public void save(String path) {
482 try {
483 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
484 DocumentBuilder db = dbf.newDocumentBuilder();
485
486 // The following allows xml parsing without access to the dtd
487 db.setEntityResolver(createEmptyEntityResolver());
488
489 // The following catches xml parsing exceptions
490 db.setErrorHandler(createErrorHandler());
491
492 Document doc = null;
493 File file = new File(path);
494 if (file.canRead()) {
495 doc = db.parse(file);
496 if (!doc.getDocumentElement().getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
497 return;
498 }
499 } else {
500 doc = db.newDocument();
501 Node node = doc.createElement(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT);
502 doc.appendChild(node);
503 }
504
505 Element root = doc.getDocumentElement();
506
507 Element oldDefinitionElement = findDefinitionElement(root, categoryName, definitionName);
508 if (oldDefinitionElement != null) {
509 root.removeChild(oldDefinitionElement);
510 }
511 Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
512 root.appendChild(definitionElement);
513 definitionElement.setAttribute(CATEGORY_ATTRIBUTE, categoryName);
514 definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);
515
516 Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
517 definitionElement.appendChild(formatElement);
518 formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));
519
520 if (inputs != null) {
521 for (InputLine inputLine : inputs) {
522 definitionElement.appendChild(createInputLineElement(inputLine, doc));
523 }
524 }
525
526 if (outputs != null) {
527 for (OutputColumn output : outputs) {
528 Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
529 definitionElement.appendChild(outputColumnElement);
530 outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
531 }
532 }
533
534 Transformer transformer = TransformerFactory.newInstance().newTransformer();
535 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
536
537 // initialize StreamResult with File object to save to file
538 StreamResult result = new StreamResult(new StringWriter());
539 DOMSource source = new DOMSource(doc);
540 transformer.transform(source, result);
541 String xmlString = result.getWriter().toString();
542
543 try (FileWriter writer = new FileWriter(file);) {
544 writer.write(xmlString);
545 }
546
547 TmfTraceType.addCustomTraceType(CustomTxtTrace.class, categoryName, definitionName);
548
549 } catch (ParserConfigurationException e) {
550 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
551 } catch (TransformerConfigurationException e) {
552 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
553 } catch (TransformerFactoryConfigurationError e) {
554 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
555 } catch (TransformerException e) {
556 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
557 } catch (IOException e) {
558 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
559 } catch (SAXException e) {
560 Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
561 }
562 }
563
564 private Element createInputLineElement(InputLine inputLine, Document doc) {
565 Element inputLineElement = doc.createElement(INPUT_LINE_ELEMENT);
566
567 Element cardinalityElement = doc.createElement(CARDINALITY_ELEMENT);
568 inputLineElement.appendChild(cardinalityElement);
569 cardinalityElement.setAttribute(MIN_ATTRIBUTE, Integer.toString(inputLine.cardinality.min));
570 cardinalityElement.setAttribute(MAX_ATTRIBUTE, Integer.toString(inputLine.cardinality.max));
571
572 Element regexElement = doc.createElement(REGEX_ELEMENT);
573 inputLineElement.appendChild(regexElement);
574 regexElement.appendChild(doc.createTextNode(inputLine.regex));
575
576 if (inputLine.columns != null) {
577 for (InputData inputData : inputLine.columns) {
578 Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT);
579 inputLineElement.appendChild(inputDataElement);
580 inputDataElement.setAttribute(NAME_ATTRIBUTE, inputData.name);
581 inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputData.action));
582 if (inputData.format != null) {
583 inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputData.format);
584 }
585 }
586 }
587
588 if (inputLine.childrenInputs != null) {
589 for (InputLine childInputLine : inputLine.childrenInputs) {
590 inputLineElement.appendChild(createInputLineElement(childInputLine, doc));
591 }
592 }
593
594 return inputLineElement;
595 }
596
597 /**
598 * Load all custom text trace definitions, including the user-defined and
599 * default (built-in) parsers.
600 *
601 * @return The loaded trace definitions
602 */
603 public static CustomTxtTraceDefinition[] loadAll() {
604 return loadAll(true);
605 }
606
607 /**
608 * Load all custom text trace definitions, including the user-defined and,
609 * optionally, the default (built-in) parsers.
610 *
611 * @param includeDefaults
612 * if true, the default (built-in) parsers are included
613 *
614 * @return The loaded trace definitions
615 */
616 public static CustomTxtTraceDefinition[] loadAll(boolean includeDefaults) {
617 File defaultFile = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME);
618 File legacyFileCore = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE);
619 File legacyFileUI = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI);
620
621 /*
622 * If there is no file at the expected location, check the legacy
623 * locations instead.
624 */
625 if (!defaultFile.exists()) {
626 if (legacyFileCore.exists()) {
627 transferDefinitions(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_CORE);
628 } else if (legacyFileUI.exists()) {
629 transferDefinitions(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME_LEGACY_UI);
630 }
631 }
632
633 Set<CustomTxtTraceDefinition> defs = new TreeSet<>(new Comparator<CustomTxtTraceDefinition>() {
634 @Override
635 public int compare(CustomTxtTraceDefinition o1, CustomTxtTraceDefinition o2) {
636 int result = o1.categoryName.compareTo(o2.categoryName);
637 if (result != 0) {
638 return result;
639 }
640 return o1.definitionName.compareTo(o2.definitionName);
641 }
642 });
643 defs.addAll(Arrays.asList(loadAll(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME)));
644 if (includeDefaults) {
645 defs.addAll(Arrays.asList(loadAll(CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_PATH_NAME)));
646 }
647 return defs.toArray(new CustomTxtTraceDefinition[0]);
648
649 }
650
651 private static void transferDefinitions(String defFile) {
652 CustomTxtTraceDefinition[] oldDefs = loadAll(defFile);
653 for (CustomTxtTraceDefinition def : oldDefs) {
654 /* Save in the new location */
655 def.save();
656 }
657 }
658
659 /**
660 * Load a specific text trace definition file.
661 *
662 * @param path
663 * The path to the file to load
664 * @return The loaded trace definitions
665 */
666 public static CustomTxtTraceDefinition[] loadAll(String path) {
667 try {
668 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
669 DocumentBuilder db = dbf.newDocumentBuilder();
670
671 // The following allows xml parsing without access to the dtd
672 db.setEntityResolver(createEmptyEntityResolver());
673
674 // The following catches xml parsing exceptions
675 db.setErrorHandler(createErrorHandler());
676
677 File file = new File(path);
678 if (!file.canRead()) {
679 return new CustomTxtTraceDefinition[0];
680 }
681 Document doc = db.parse(file);
682
683 Element root = doc.getDocumentElement();
684 if (!root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
685 return new CustomTxtTraceDefinition[0];
686 }
687
688 ArrayList<CustomTxtTraceDefinition> defList = new ArrayList<>();
689 NodeList nodeList = root.getChildNodes();
690 for (int i = 0; i < nodeList.getLength(); i++) {
691 Node node = nodeList.item(i);
692 if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) {
693 CustomTxtTraceDefinition def = extractDefinition((Element) node);
694 if (def != null) {
695 defList.add(def);
696 }
697 }
698 }
699 return defList.toArray(new CustomTxtTraceDefinition[0]);
700 } catch (ParserConfigurationException e) {
701 Activator.logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
702 } catch (SAXException e) {
703 Activator.logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
704 } catch (IOException e) {
705 Activator.logError("Error loading all in CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
706 }
707 return new CustomTxtTraceDefinition[0];
708 }
709
710 /**
711 * Load a single definition.
712 *
713 * @param categoryName
714 * Category of the definition to load
715 * @param definitionName
716 * Name of the definition to load
717 * @return The loaded trace definition
718 */
719 public static CustomTxtTraceDefinition load(String categoryName, String definitionName) {
720 try {
721 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
722 DocumentBuilder db = dbf.newDocumentBuilder();
723
724 // The following allows xml parsing without access to the dtd
725 db.setEntityResolver(createEmptyEntityResolver());
726
727 // The following catches xml parsing exceptions
728 db.setErrorHandler(createErrorHandler());
729
730 CustomTxtTraceDefinition value = lookupDefinition(categoryName, definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME);
731 if (value == null) {
732 return lookupDefinition(categoryName, definitionName, db, CUSTOM_TXT_TRACE_DEFINITIONS_DEFAULT_PATH_NAME);
733 }
734 return value;
735 } catch (ParserConfigurationException | SAXException | IOException e) {
736 Activator.logError("Error loading CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
737 }
738 return null;
739 }
740
741 private static CustomTxtTraceDefinition lookupDefinition(String categoryName, String definitionName, DocumentBuilder db, String source) throws SAXException, IOException {
742 File file = new File(source);
743 if (!file.exists()) {
744 return null;
745 }
746 Document doc = db.parse(file);
747
748 Element root = doc.getDocumentElement();
749 if (!root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
750 return null;
751 }
752
753 Element definitionElement = findDefinitionElement(root, categoryName, definitionName);
754 if (definitionElement != null) {
755 return extractDefinition(definitionElement);
756 }
757 return null;
758 }
759
760 private static Element findDefinitionElement(Element root, String categoryName, String definitionName) {
761 NodeList nodeList = root.getChildNodes();
762 for (int i = 0; i < nodeList.getLength(); i++) {
763 Node node = nodeList.item(i);
764 if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) {
765 Element element = (Element) node;
766 String categoryAttribute = element.getAttribute(CATEGORY_ATTRIBUTE);
767 if (categoryAttribute.isEmpty()) {
768 categoryAttribute = CUSTOM_TXT_CATEGORY;
769 }
770 String nameAttribute = element.getAttribute(NAME_ATTRIBUTE);
771 if (categoryName.equals(categoryAttribute) &&
772 definitionName.equals(nameAttribute)) {
773 return element;
774 }
775 }
776 }
777 return null;
778 }
779
780 /**
781 * Get the definition from a definition element.
782 *
783 * @param definitionElement
784 * The Element to extract from
785 * @return The loaded trace definition
786 */
787 public static CustomTxtTraceDefinition extractDefinition(Element definitionElement) {
788 CustomTxtTraceDefinition def = new CustomTxtTraceDefinition();
789
790 def.categoryName = definitionElement.getAttribute(CATEGORY_ATTRIBUTE);
791 if (def.categoryName.isEmpty()) {
792 def.categoryName = CUSTOM_TXT_CATEGORY;
793 }
794 def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE);
795 if (def.definitionName.isEmpty()) {
796 return null;
797 }
798
799 NodeList nodeList = definitionElement.getChildNodes();
800 for (int i = 0; i < nodeList.getLength(); i++) {
801 Node node = nodeList.item(i);
802 String nodeName = node.getNodeName();
803 if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) {
804 Element formatElement = (Element) node;
805 def.timeStampOutputFormat = formatElement.getTextContent();
806 } else if (nodeName.equals(INPUT_LINE_ELEMENT)) {
807 InputLine inputLine = extractInputLine((Element) node);
808 if (inputLine != null) {
809 def.inputs.add(inputLine);
810 }
811 } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) {
812 Element outputColumnElement = (Element) node;
813 OutputColumn outputColumn = new OutputColumn();
814 outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE);
815 def.outputs.add(outputColumn);
816 }
817 }
818 return def;
819 }
820
821 private static InputLine extractInputLine(Element inputLineElement) {
822 InputLine inputLine = new InputLine();
823 NodeList nodeList = inputLineElement.getChildNodes();
824 for (int i = 0; i < nodeList.getLength(); i++) {
825 Node node = nodeList.item(i);
826 String nodeName = node.getNodeName();
827 if (nodeName.equals(CARDINALITY_ELEMENT)) {
828 Element cardinalityElement = (Element) node;
829 try {
830 int min = Integer.parseInt(cardinalityElement.getAttribute(MIN_ATTRIBUTE));
831 int max = Integer.parseInt(cardinalityElement.getAttribute(MAX_ATTRIBUTE));
832 inputLine.cardinality = new Cardinality(min, max);
833 } catch (NumberFormatException e) {
834 return null;
835 }
836 } else if (nodeName.equals(REGEX_ELEMENT)) {
837 Element regexElement = (Element) node;
838 inputLine.regex = regexElement.getTextContent();
839 } else if (nodeName.equals(INPUT_DATA_ELEMENT)) {
840 Element inputDataElement = (Element) node;
841 InputData inputData = new InputData();
842 inputData.name = inputDataElement.getAttribute(NAME_ATTRIBUTE);
843 inputData.action = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE));
844 inputData.format = inputDataElement.getAttribute(FORMAT_ATTRIBUTE);
845 inputLine.addColumn(inputData);
846 } else if (nodeName.equals(INPUT_LINE_ELEMENT)) {
847 Element childInputLineElement = (Element) node;
848 InputLine childInputLine = extractInputLine(childInputLineElement);
849 if (childInputLine != null) {
850 inputLine.addChild(childInputLine);
851 }
852 }
853 }
854 return inputLine;
855 }
856
857 /**
858 * Delete a definition from the currently loaded ones.
859 *
860 * @param categoryName
861 * The category of the definition to delete
862 * @param definitionName
863 * The name of the definition to delete
864 */
865 public static void delete(String categoryName, String definitionName) {
866 try {
867 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
868 DocumentBuilder db = dbf.newDocumentBuilder();
869
870 // The following allows xml parsing without access to the dtd
871 db.setEntityResolver(createEmptyEntityResolver());
872
873 // The following catches xml parsing exceptions
874 db.setErrorHandler(createErrorHandler());
875
876 File file = new File(CUSTOM_TXT_TRACE_DEFINITIONS_PATH_NAME);
877 Document doc = db.parse(file);
878
879 Element root = doc.getDocumentElement();
880 if (!root.getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
881 return;
882 }
883
884 Element definitionElement = findDefinitionElement(root, categoryName, definitionName);
885 if (definitionElement != null) {
886 root.removeChild(definitionElement);
887 }
888
889 Transformer transformer = TransformerFactory.newInstance().newTransformer();
890 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
891
892 // initialize StreamResult with File object to save to file
893 StreamResult result = new StreamResult(new StringWriter());
894 DOMSource source = new DOMSource(doc);
895 transformer.transform(source, result);
896 String xmlString = result.getWriter().toString();
897
898 try (FileWriter writer = new FileWriter(file);) {
899 writer.write(xmlString);
900 }
901
902 TmfTraceType.removeCustomTraceType(CustomTxtTrace.class, categoryName, definitionName);
903 // Check if default definition needs to be reloaded
904 TmfTraceType.addCustomTraceType(CustomTxtTrace.class, categoryName, definitionName);
905
906 } catch (ParserConfigurationException | SAXException | IOException | TransformerFactoryConfigurationError | TransformerException e) {
907 Activator.logError("Error deleting CustomTxtTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
908 }
909 }
910 }
This page took 0.062012 seconds and 4 git commands to generate.