Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 44da114ea66fb05a10ea937be93d3bf0d11cfa45 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
/*******************************************************************************
 * Copyright (c) 2010, 2014 Ericsson
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Patrick Tasse - Initial API and implementation
 *   Matthew Khouzam - Add support for default xml parsers
 *******************************************************************************/

package org.eclipse.linuxtools.tmf.core.parsers.custom;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.runtime.Platform;
import org.eclipse.linuxtools.internal.tmf.core.Activator;
import org.eclipse.linuxtools.tmf.core.project.model.TmfTraceType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Trace definition for custom XML traces.
 *
 * @author Patrick Tassé
 * @since 3.0
 */
public class CustomXmlTraceDefinition extends CustomTraceDefinition {

    /** "ignore" tag */
    public static final String TAG_IGNORE = Messages.CustomXmlTraceDefinition_ignoreTag;

    /** Name of the default XML definitions file */
    protected static final String CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_FILE_NAME = "custom_xml_default_parsers.xml"; //$NON-NLS-1$

    /** Name of the XML definitions file */
    protected static final String CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME = "custom_xml_parsers.xml"; //$NON-NLS-1$

    /** Path to the XML definitions file */
    protected static final String CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME =
            Platform.getInstallLocation().getURL().getPath() +
            "templates/org.eclipse.linuxtools.tmf.core/" + //$NON-NLS-1$
            CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_FILE_NAME;

    /** Path to the XML definitions file */
    protected static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME =
            Activator.getDefault().getStateLocation().addTrailingSeparator().append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString();

    /** Legacy path to the XML definitions file (in the UI plug-in)
     * TODO Remove once we feel the transition phase is over. */
    private static final String CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY =
            Activator.getDefault().getStateLocation().removeLastSegments(1).addTrailingSeparator()
                    .append("org.eclipse.linuxtools.tmf.ui") //$NON-NLS-1$
                    .append(CUSTOM_XML_TRACE_DEFINITIONS_FILE_NAME).toString();

    private static final String CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT = Messages.CustomXmlTraceDefinition_definitionRootElement;
    private static final String DEFINITION_ELEMENT = Messages.CustomXmlTraceDefinition_definition;
    private static final String NAME_ATTRIBUTE = Messages.CustomXmlTraceDefinition_name;
    private static final String LOG_ENTRY_ATTRIBUTE = Messages.CustomXmlTraceDefinition_logEntry;
    private static final String TIME_STAMP_OUTPUT_FORMAT_ELEMENT = Messages.CustomXmlTraceDefinition_timestampOutputFormat;
    private static final String INPUT_ELEMENT_ELEMENT = Messages.CustomXmlTraceDefinition_inputElement;
    private static final String ATTRIBUTE_ELEMENT = Messages.CustomXmlTraceDefinition_attribute;
    private static final String INPUT_DATA_ELEMENT = Messages.CustomXmlTraceDefinition_inputData;
    private static final String ACTION_ATTRIBUTE = Messages.CustomXmlTraceDefinition_action;
    private static final String FORMAT_ATTRIBUTE = Messages.CustomXmlTraceDefinition_format;
    private static final String OUTPUT_COLUMN_ELEMENT = Messages.CustomXmlTraceDefinition_outputColumn;

    /** Top-level input element */
    public InputElement rootInputElement;

    /**
     * Default constructor
     */
    public CustomXmlTraceDefinition() {
        this("", null, new ArrayList<OutputColumn>(), ""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Full constructor
     *
     * @param logtype
     *            Type of trace type
     * @param rootElement
     *            The top-level XML element
     * @param outputs
     *            The list of output columns
     * @param timeStampOutputFormat
     *            The timestamp format to use
     */
    public CustomXmlTraceDefinition(String logtype, InputElement rootElement,
            List<OutputColumn> outputs, String timeStampOutputFormat) {
        this.definitionName = logtype;
        this.rootInputElement = rootElement;
        this.outputs = outputs;
        this.timeStampOutputFormat = timeStampOutputFormat;
    }

    /**
     * Wrapper for input XML elements
     */
    public static class InputElement {

        /** Name of the element */
        public String elementName;

        /** Indicates if this is a log entry */
        public boolean logEntry;

        /** Name of the input element */
        public String inputName;

        /** Input action */
        public int inputAction;

        /** Input format */
        public String inputFormat;

        /** XML attributes of this element */
        public List<InputAttribute> attributes;

        /** Parent element */
        public InputElement parentElement;

        /** Following element in the file */
        public InputElement nextElement;

        /** Child elements */
        public List<InputElement> childElements;

        /**
         * Default (empty) constructor
         */
        public InputElement() {
        }

        /**
         * Constructor
         *
         * @param elementName
         *            Element name
         * @param logEntry
         *            If this element is a log entry
         * @param inputName
         *            Name of the the input
         * @param inputAction
         *            Input action
         * @param inputFormat
         *            Input format
         * @param attributes
         *            XML attributes of this element
         */
        public InputElement(String elementName, boolean logEntry,
                String inputName, int inputAction, String inputFormat,
                List<InputAttribute> attributes) {
            this.elementName = elementName;
            this.logEntry = logEntry;
            this.inputName = inputName;
            this.inputAction = inputAction;
            this.inputFormat = inputFormat;
            this.attributes = attributes;
        }

        /**
         * Add a XML attribute to the element
         *
         * @param attribute
         *            The attribute to add
         */
        public void addAttribute(InputAttribute attribute) {
            if (attributes == null) {
                attributes = new ArrayList<>(1);
            }
            attributes.add(attribute);
        }

        /**
         * Add a child element to this one.
         *
         * @param input
         *            The input element to add as child
         */
        public void addChild(InputElement input) {
            if (childElements == null) {
                childElements = new ArrayList<>(1);
            } else if (childElements.size() > 0) {
                InputElement last = childElements.get(childElements.size() - 1);
                last.nextElement = input;
            }
            childElements.add(input);
            input.parentElement = this;
        }

        /**
         * Set the following input element.
         *
         * @param input
         *            The input element to add as next element
         */
        public void addNext(InputElement input) {
            if (parentElement != null) {
                int index = parentElement.childElements.indexOf(this);
                parentElement.childElements.add(index + 1, input);
                InputElement next = nextElement;
                nextElement = input;
                input.nextElement = next;
            }
            input.parentElement = this.parentElement;
        }

        /**
         * Move this element up in its parent's list of children.
         */
        public void moveUp() {
            if (parentElement != null) {
                int index = parentElement.childElements.indexOf(this);
                if (index > 0) {
                    parentElement.childElements.add(index - 1, parentElement.childElements.remove(index));
                    parentElement.childElements.get(index).nextElement = nextElement;
                    nextElement = parentElement.childElements.get(index);
                }
            }
        }

        /**
         * Move this element down in its parent's list of children.
         */
        public void moveDown() {
            if (parentElement != null) {
                int index = parentElement.childElements.indexOf(this);
                if (index < parentElement.childElements.size() - 1) {
                    parentElement.childElements.add(index + 1, parentElement.childElements.remove(index));
                    nextElement = parentElement.childElements.get(index).nextElement;
                    parentElement.childElements.get(index).nextElement = this;
                }
            }
        }

    }

    /**
     * Wrapper for XML element attributes
     */
    public static class InputAttribute {

        /** Name of the XML attribute */
        public String attributeName;

        /** Input name */
        public String inputName;

        /** Input action */
        public int inputAction;

        /** Input format */
        public String inputFormat;

        /**
         * Default (empty) constructor
         */
        public InputAttribute() {
        }

        /**
         * Constructor
         *
         * @param attributeName
         *            Name of the XML attribute
         * @param inputName
         *            Input name
         * @param inputAction
         *            Input action
         * @param inputFormat
         *            Input format
         */
        public InputAttribute(String attributeName, String inputName,
                int inputAction, String inputFormat) {
            this.attributeName = attributeName;
            this.inputName = inputName;
            this.inputAction = inputAction;
            this.inputFormat = inputFormat;
        }
    }

    @Override
    public void save() {
        save(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
    }

    @Override
    public void save(String path) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // The following allows xml parsing without access to the dtd
            EntityResolver resolver = new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) {
                    String empty = ""; //$NON-NLS-1$
                    ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
                    return new InputSource(bais);
                }
            };
            db.setEntityResolver(resolver);

            // The following catches xml parsing exceptions
            db.setErrorHandler(new ErrorHandler() {
                @Override
                public void error(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void warning(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void fatalError(SAXParseException saxparseexception) throws SAXException {
                    throw saxparseexception;
                }
            });

            Document doc = null;
            File file = new File(path);
            if (file.canRead()) {
                doc = db.parse(file);
                if (!doc.getDocumentElement().getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
                    return;
                }
            } else {
                doc = db.newDocument();
                Node node = doc.createElement(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT);
                doc.appendChild(node);
            }

            Element root = doc.getDocumentElement();

            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element &&
                        node.getNodeName().equals(DEFINITION_ELEMENT) &&
                        definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) {
                    root.removeChild(node);
                }
            }
            Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
            root.appendChild(definitionElement);
            definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);

            Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
            definitionElement.appendChild(formatElement);
            formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));

            if (rootInputElement != null) {
                definitionElement.appendChild(createInputElementElement(rootInputElement, doc));
            }

            if (outputs != null) {
                for (OutputColumn output : outputs) {
                    Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
                    definitionElement.appendChild(outputColumnElement);
                    outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
                }
            }

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

            // initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            String xmlString = result.getWriter().toString();

            try (FileWriter writer = new FileWriter(file);) {
                writer.write(xmlString);
            }

            TmfTraceType.addCustomTraceType(TmfTraceType.CUSTOM_XML_CATEGORY, definitionName);

        } catch (ParserConfigurationException e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (TransformerConfigurationException e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (TransformerFactoryConfigurationError e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (TransformerException e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (IOException e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (SAXException e) {
            Activator.logError("Error saving CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        }
    }

    private Element createInputElementElement(InputElement inputElement, Document doc) {
        Element inputElementElement = doc.createElement(INPUT_ELEMENT_ELEMENT);
        inputElementElement.setAttribute(NAME_ATTRIBUTE, inputElement.elementName);

        if (inputElement.logEntry) {
            inputElementElement.setAttribute(LOG_ENTRY_ATTRIBUTE, Boolean.toString(inputElement.logEntry));
        }

        if (inputElement.parentElement != null) {
            Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT);
            inputElementElement.appendChild(inputDataElement);
            inputDataElement.setAttribute(NAME_ATTRIBUTE, inputElement.inputName);
            inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(inputElement.inputAction));
            if (inputElement.inputFormat != null) {
                inputDataElement.setAttribute(FORMAT_ATTRIBUTE, inputElement.inputFormat);
            }
        }

        if (inputElement.attributes != null) {
            for (InputAttribute attribute : inputElement.attributes) {
                Element inputAttributeElement = doc.createElement(ATTRIBUTE_ELEMENT);
                inputElementElement.appendChild(inputAttributeElement);
                inputAttributeElement.setAttribute(NAME_ATTRIBUTE, attribute.attributeName);
                Element inputDataElement = doc.createElement(INPUT_DATA_ELEMENT);
                inputAttributeElement.appendChild(inputDataElement);
                inputDataElement.setAttribute(NAME_ATTRIBUTE, attribute.inputName);
                inputDataElement.setAttribute(ACTION_ATTRIBUTE, Integer.toString(attribute.inputAction));
                if (attribute.inputFormat != null) {
                    inputDataElement.setAttribute(FORMAT_ATTRIBUTE, attribute.inputFormat);
                }
            }
        }

        if (inputElement.childElements != null) {
            for (InputElement childInputElement : inputElement.childElements) {
                inputElementElement.appendChild(createInputElementElement(childInputElement, doc));
            }
        }

        return inputElementElement;
    }

    /**
     * Load all the XML trace definitions in the default definitions file.
     *
     * @return The loaded trace definitions
     */
    public static CustomXmlTraceDefinition[] loadAll() {
        File defaultFile = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
        File legacyFile = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY);

        /*
         * If there is no file at the expected location, check the legacy
         * location instead.
         */
        if (!defaultFile.exists() && legacyFile.exists()) {
            CustomXmlTraceDefinition[] oldDefs = loadAll(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME_LEGACY);
            for (CustomXmlTraceDefinition def : oldDefs) {
                /* Save in the new location */
                def.save();
            }
        }

        Set<CustomXmlTraceDefinition> defs = new TreeSet<>(new Comparator<CustomXmlTraceDefinition>() {

            @Override
            public int compare(CustomXmlTraceDefinition o1, CustomXmlTraceDefinition o2) {
                return o1.definitionName.compareTo(o2.definitionName);
            }
        });
        defs.addAll(Arrays.asList(loadAll(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME)));
        defs.addAll(Arrays.asList(loadAll(CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME)));
        return defs.toArray(new CustomXmlTraceDefinition[0]);
    }

    /**
     * Load all the XML trace definitions in the given definitions file.
     *
     * @param path
     *            Path to the definitions file to load
     * @return The loaded trace definitions
     */
    public static CustomXmlTraceDefinition[] loadAll(String path) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // The following allows xml parsing without access to the dtd
            EntityResolver resolver = new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) {
                    String empty = ""; //$NON-NLS-1$
                    ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
                    return new InputSource(bais);
                }
            };
            db.setEntityResolver(resolver);

            // The following catches xml parsing exceptions
            db.setErrorHandler(new ErrorHandler() {
                @Override
                public void error(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void warning(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void fatalError(SAXParseException saxparseexception) throws SAXException {
                    throw saxparseexception;
                }
            });

            File file = new File(path);
            if (!file.canRead()) {
                return new CustomXmlTraceDefinition[0];
            }
            Document doc = db.parse(file);

            Element root = doc.getDocumentElement();
            if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
                return new CustomXmlTraceDefinition[0];
            }

            ArrayList<CustomXmlTraceDefinition> defList = new ArrayList<>();
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element && node.getNodeName().equals(DEFINITION_ELEMENT)) {
                    CustomXmlTraceDefinition def = extractDefinition((Element) node);
                    if (def != null) {
                        defList.add(def);
                    }
                }
            }
            return defList.toArray(new CustomXmlTraceDefinition[0]);
        } catch (ParserConfigurationException e) {
            Activator.logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (SAXException e) {
            Activator.logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        } catch (IOException e) {
            Activator.logError("Error loading all in CustomXmlTraceDefinition: path=" + path, e); //$NON-NLS-1$
        }
        return new CustomXmlTraceDefinition[0];
    }

    /**
     * Load the given trace definition.
     *
     * @param definitionName
     *            Name of the XML trace definition to load
     * @return The loaded trace definition
     */
    public static CustomXmlTraceDefinition load(String definitionName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // The following allows xml parsing without access to the dtd
            EntityResolver resolver = new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) {
                    String empty = ""; //$NON-NLS-1$
                    ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
                    return new InputSource(bais);
                }
            };
            db.setEntityResolver(resolver);

            // The following catches xml parsing exceptions
            db.setErrorHandler(new ErrorHandler() {
                @Override
                public void error(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void warning(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void fatalError(SAXParseException saxparseexception) throws SAXException {
                    throw saxparseexception;
                }
            });

            CustomXmlTraceDefinition value = lookupXmlDefinition(definitionName, db, CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
            if (value == null) {
                value = lookupXmlDefinition(definitionName, db, CUSTOM_XML_TRACE_DEFINITIONS_DEFAULT_PATH_NAME);
            }
            return value;
        } catch (ParserConfigurationException e) {
            Activator.logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (SAXException e) {
            Activator.logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (IOException e) {
            Activator.logError("Error loading CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        }
        return null;
    }

    private static CustomXmlTraceDefinition lookupXmlDefinition(String definitionName, DocumentBuilder db, String source) throws SAXException, IOException {
        File file = new File(source);
        if (!file.exists()) {
            return null;
        }

        Document doc = db.parse(file);

        Element root = doc.getDocumentElement();
        if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
            return null;
        }

        NodeList nodeList = root.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element &&
                    node.getNodeName().equals(DEFINITION_ELEMENT) &&
                    definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) {
                return extractDefinition((Element) node);
            }
        }
        return null;
    }

    /**
     * Extract a trace definition from an XML element.
     *
     * @param definitionElement
     *            Definition element
     * @return The extracted trace definition
     */
    public static CustomXmlTraceDefinition extractDefinition(Element definitionElement) {
        CustomXmlTraceDefinition def = new CustomXmlTraceDefinition();

        def.definitionName = definitionElement.getAttribute(NAME_ATTRIBUTE);
        if (def.definitionName == null) {
            return null;
        }

        NodeList nodeList = definitionElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            String nodeName = node.getNodeName();
            if (nodeName.equals(TIME_STAMP_OUTPUT_FORMAT_ELEMENT)) {
                Element formatElement = (Element) node;
                def.timeStampOutputFormat = formatElement.getTextContent();
            } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) {
                InputElement inputElement = extractInputElement((Element) node);
                if (inputElement != null) {
                    if (def.rootInputElement == null) {
                        def.rootInputElement = inputElement;
                    } else {
                        return null;
                    }
                }
            } else if (nodeName.equals(OUTPUT_COLUMN_ELEMENT)) {
                Element outputColumnElement = (Element) node;
                OutputColumn outputColumn = new OutputColumn();
                outputColumn.name = outputColumnElement.getAttribute(NAME_ATTRIBUTE);
                def.outputs.add(outputColumn);
            }
        }
        return def;
    }

    private static InputElement extractInputElement(Element inputElementElement) {
        InputElement inputElement = new InputElement();
        inputElement.elementName = inputElementElement.getAttribute(NAME_ATTRIBUTE);
        inputElement.logEntry = (Boolean.toString(true).equals(inputElementElement.getAttribute(LOG_ENTRY_ATTRIBUTE))) ? true : false;
        NodeList nodeList = inputElementElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            String nodeName = node.getNodeName();
            if (nodeName.equals(INPUT_DATA_ELEMENT)) {
                Element inputDataElement = (Element) node;
                inputElement.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE);
                inputElement.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE));
                inputElement.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE);
            } else if (nodeName.equals(ATTRIBUTE_ELEMENT)) {
                Element attributeElement = (Element) node;
                InputAttribute attribute = new InputAttribute();
                attribute.attributeName = attributeElement.getAttribute(NAME_ATTRIBUTE);
                NodeList attributeNodeList = attributeElement.getChildNodes();
                for (int j = 0; j < attributeNodeList.getLength(); j++) {
                    Node attributeNode = attributeNodeList.item(j);
                    String attributeNodeName = attributeNode.getNodeName();
                    if (attributeNodeName.equals(INPUT_DATA_ELEMENT)) {
                        Element inputDataElement = (Element) attributeNode;
                        attribute.inputName = inputDataElement.getAttribute(NAME_ATTRIBUTE);
                        attribute.inputAction = Integer.parseInt(inputDataElement.getAttribute(ACTION_ATTRIBUTE));
                        attribute.inputFormat = inputDataElement.getAttribute(FORMAT_ATTRIBUTE);
                    }
                }
                inputElement.addAttribute(attribute);
            } else if (nodeName.equals(INPUT_ELEMENT_ELEMENT)) {
                Element childInputElementElement = (Element) node;
                InputElement childInputElement = extractInputElement(childInputElementElement);
                if (childInputElement != null) {
                    inputElement.addChild(childInputElement);
                }
            }
        }
        return inputElement;
    }

    /**
     * Delete the given trace definition from the list of currently loaded ones.
     *
     * @param definitionName
     *            Name of the trace definition to delete
     */
    public static void delete(String definitionName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // The following allows xml parsing without access to the dtd
            EntityResolver resolver = new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) {
                    String empty = ""; //$NON-NLS-1$
                    ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
                    return new InputSource(bais);
                }
            };
            db.setEntityResolver(resolver);

            // The following catches xml parsing exceptions
            db.setErrorHandler(new ErrorHandler() {
                @Override
                public void error(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void warning(SAXParseException saxparseexception) throws SAXException {
                }

                @Override
                public void fatalError(SAXParseException saxparseexception) throws SAXException {
                    throw saxparseexception;
                }
            });

            File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
            Document doc = db.parse(file);

            Element root = doc.getDocumentElement();
            if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
                return;
            }

            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element &&
                        node.getNodeName().equals(DEFINITION_ELEMENT) &&
                        definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) {
                    root.removeChild(node);
                }
            }

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

            // initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            String xmlString = result.getWriter().toString();

            try (FileWriter writer = new FileWriter(file);) {
                writer.write(xmlString);
            }

            TmfTraceType.removeCustomTraceType(TmfTraceType.CUSTOM_XML_CATEGORY, definitionName);

        } catch (ParserConfigurationException e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (SAXException e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (IOException e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (TransformerConfigurationException e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (TransformerFactoryConfigurationError e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        } catch (TransformerException e) {
            Activator.logError("Error deleteing CustomXmlTraceDefinition: definitionName=" + definitionName, e); //$NON-NLS-1$
        }
    }
}

Back to the top