1 /*******************************************************************************
2 * Copyright (c) 2010, 2014 Ericsson
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
10 * Patrick Tasse - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.tracecompass
.tmf
.core
.parsers
.custom
;
15 import java
.io
.ByteArrayInputStream
;
17 import java
.io
.IOException
;
18 import java
.io
.RandomAccessFile
;
19 import java
.nio
.ByteBuffer
;
21 import javax
.xml
.parsers
.DocumentBuilder
;
22 import javax
.xml
.parsers
.DocumentBuilderFactory
;
23 import javax
.xml
.parsers
.ParserConfigurationException
;
25 import org
.eclipse
.core
.resources
.IProject
;
26 import org
.eclipse
.core
.resources
.IResource
;
27 import org
.eclipse
.core
.runtime
.IStatus
;
28 import org
.eclipse
.core
.runtime
.Status
;
29 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.Activator
;
30 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.parsers
.custom
.CustomEventAspects
;
31 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
32 import org
.eclipse
.tracecompass
.tmf
.core
.event
.aspect
.ITmfEventAspect
;
33 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
34 import org
.eclipse
.tracecompass
.tmf
.core
.io
.BufferedRandomAccessFile
;
35 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimestamp
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfContext
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfEventParser
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfContext
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTrace
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TraceValidationStatus
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.ITmfPersistentlyIndexable
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.TmfBTreeTraceIndexer
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.checkpoint
.ITmfCheckpoint
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpoint
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.location
.ITmfLocation
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.location
.TmfLongLocation
;
48 import org
.w3c
.dom
.Document
;
49 import org
.w3c
.dom
.Element
;
50 import org
.w3c
.dom
.Node
;
51 import org
.w3c
.dom
.NodeList
;
52 import org
.xml
.sax
.EntityResolver
;
53 import org
.xml
.sax
.ErrorHandler
;
54 import org
.xml
.sax
.InputSource
;
55 import org
.xml
.sax
.SAXException
;
56 import org
.xml
.sax
.SAXParseException
;
59 * Trace object for custom XML trace parsers.
61 * @author Patrick Tassé
64 public class CustomXmlTrace
extends TmfTrace
implements ITmfEventParser
, ITmfPersistentlyIndexable
{
66 private static final TmfLongLocation NULL_LOCATION
= new TmfLongLocation(-1L);
67 private static final int DEFAULT_CACHE_SIZE
= 100;
68 private static final int MAX_LINES
= 100;
69 private static final int CONFIDENCE
= 100;
71 private final CustomXmlTraceDefinition fDefinition
;
72 private final CustomXmlEventType fEventType
;
73 private final CustomXmlInputElement fRecordInputElement
;
74 private BufferedRandomAccessFile fFile
;
82 public CustomXmlTrace(final CustomXmlTraceDefinition definition
) {
83 fDefinition
= definition
;
84 fEventType
= new CustomXmlEventType(fDefinition
);
85 fRecordInputElement
= getRecordInputElement(fDefinition
.rootInputElement
);
86 setCacheSize(DEFAULT_CACHE_SIZE
);
97 * Path to the trace/log file
100 * @throws TmfTraceException
101 * If the trace/log couldn't be opened
103 public CustomXmlTrace(final IResource resource
,
104 final CustomXmlTraceDefinition definition
, final String path
,
105 final int pageSize
) throws TmfTraceException
{
107 setCacheSize((pageSize
> 0) ? pageSize
: DEFAULT_CACHE_SIZE
);
108 initTrace(resource
, path
, CustomXmlEvent
.class);
112 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> eventType
) throws TmfTraceException
{
113 super.initTrace(resource
, path
, eventType
);
115 fFile
= new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
116 } catch (IOException e
) {
117 throw new TmfTraceException(e
.getMessage(), e
);
122 public synchronized void dispose() {
127 } catch (IOException e
) {
135 public ITmfTraceIndexer
getIndexer() {
136 return super.getIndexer();
140 public Iterable
<ITmfEventAspect
> getEventAspects() {
141 return CustomEventAspects
.generateAspects(fDefinition
);
145 public synchronized TmfContext
seekEvent(final ITmfLocation location
) {
146 final CustomXmlTraceContext context
= new CustomXmlTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
147 if (NULL_LOCATION
.equals(location
) || fFile
== null) {
151 if (location
== null) {
153 } else if (location
.getLocationInfo() instanceof Long
) {
154 fFile
.seek((Long
) location
.getLocationInfo());
156 long rawPos
= fFile
.getFilePointer();
157 String line
= fFile
.getNextLine();
158 while (line
!= null) {
159 final int idx
= indexOfElement(fRecordInputElement
.getElementName(), line
, 0);
161 context
.setLocation(new TmfLongLocation(rawPos
+ idx
));
164 rawPos
= fFile
.getFilePointer();
165 line
= fFile
.getNextLine();
168 } catch (final IOException e
) {
169 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
176 public synchronized TmfContext
seekEvent(final double ratio
) {
178 return new CustomTxtTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
181 long pos
= Math
.round(ratio
* fFile
.length());
184 if (fFile
.read() == '\n') {
189 final ITmfLocation location
= new TmfLongLocation(pos
);
190 final TmfContext context
= seekEvent(location
);
191 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
193 } catch (final IOException e
) {
194 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
195 return new CustomXmlTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
200 public synchronized double getLocationRatio(final ITmfLocation location
) {
205 if (location
.getLocationInfo() instanceof Long
) {
206 return ((Long
) location
.getLocationInfo()).doubleValue() / fFile
.length();
208 } catch (final IOException e
) {
209 Activator
.logError("Error getting location ration. File: " + getPath(), e
); //$NON-NLS-1$
215 public ITmfLocation
getCurrentLocation() {
216 // TODO Auto-generated method stub
221 public synchronized CustomXmlEvent
parseEvent(final ITmfContext tmfContext
) {
222 ITmfContext context
= seekEvent(tmfContext
.getLocation());
223 return parse(context
);
227 public synchronized CustomXmlEvent
getNext(final ITmfContext context
) {
228 final ITmfContext savedContext
= new TmfContext(context
.getLocation(), context
.getRank());
229 final CustomXmlEvent event
= parse(context
);
231 updateAttributes(savedContext
, event
.getTimestamp());
232 context
.increaseRank();
237 private synchronized CustomXmlEvent
parse(final ITmfContext tmfContext
) {
241 if (!(tmfContext
instanceof CustomXmlTraceContext
)) {
245 final CustomXmlTraceContext context
= (CustomXmlTraceContext
) tmfContext
;
246 if (context
.getLocation() == null || !(context
.getLocation().getLocationInfo() instanceof Long
) || NULL_LOCATION
.equals(context
.getLocation())) {
250 CustomXmlEvent event
= null;
252 // Below +1 for the <
253 if (fFile
.getFilePointer() != (Long
) context
.getLocation().getLocationInfo() + 1) {
254 fFile
.seek((Long
) context
.getLocation().getLocationInfo() + 1);
256 final StringBuffer elementBuffer
= new StringBuffer("<"); //$NON-NLS-1$
257 readElement(elementBuffer
, fFile
);
258 final Element element
= parseElementBuffer(elementBuffer
);
260 event
= extractEvent(element
, fRecordInputElement
);
261 ((StringBuffer
) event
.getContent().getValue()).append(elementBuffer
);
263 long rawPos
= fFile
.getFilePointer();
264 String line
= fFile
.getNextLine();
265 while (line
!= null) {
266 final int idx
= indexOfElement(fRecordInputElement
.getElementName(), line
, 0);
268 context
.setLocation(new TmfLongLocation(rawPos
+ idx
));
271 rawPos
= fFile
.getFilePointer();
272 line
= fFile
.getNextLine();
274 } catch (final IOException e
) {
275 Activator
.logError("Error parsing event. File: " + getPath(), e
); //$NON-NLS-1$
278 context
.setLocation(NULL_LOCATION
);
282 private Element
parseElementBuffer(final StringBuffer elementBuffer
) {
284 final DocumentBuilderFactory dbf
= DocumentBuilderFactory
.newInstance();
285 final DocumentBuilder db
= dbf
.newDocumentBuilder();
287 // The following allows xml parsing without access to the dtd
288 final EntityResolver resolver
= new EntityResolver() {
290 public InputSource
resolveEntity(final String publicId
, final String systemId
) {
291 final String empty
= ""; //$NON-NLS-1$
292 final ByteArrayInputStream bais
= new ByteArrayInputStream(empty
.getBytes());
293 return new InputSource(bais
);
296 db
.setEntityResolver(resolver
);
298 // The following catches xml parsing exceptions
299 db
.setErrorHandler(new ErrorHandler() {
301 public void error(final SAXParseException saxparseexception
) throws SAXException
{
305 public void warning(final SAXParseException saxparseexception
) throws SAXException
{
309 public void fatalError(final SAXParseException saxparseexception
) throws SAXException
{
310 throw saxparseexception
;
314 final Document doc
= db
.parse(new ByteArrayInputStream(elementBuffer
.toString().getBytes()));
315 return doc
.getDocumentElement();
316 } catch (final ParserConfigurationException e
) {
317 Activator
.logError("Error parsing element buffer. File:" + getPath(), e
); //$NON-NLS-1$
318 } catch (final SAXException e
) {
319 Activator
.logError("Error parsing element buffer. File:" + getPath(), e
); //$NON-NLS-1$
320 } catch (final IOException e
) {
321 Activator
.logError("Error parsing element buffer. File: " + getPath(), e
); //$NON-NLS-1$
326 private static int indexOfElement(String elementName
, String line
, int fromIndex
) {
327 final String recordElementStart
= '<' + elementName
;
328 int index
= line
.indexOf(recordElementStart
, fromIndex
);
332 int nextCharIndex
= index
+ recordElementStart
.length();
333 if (nextCharIndex
< line
.length()) {
334 char c
= line
.charAt(nextCharIndex
);
335 // Check that the match is not just a substring of another element
336 if (Character
.isLetterOrDigit(c
)) {
337 return indexOfElement(elementName
, line
, nextCharIndex
);
343 private void readElement(final StringBuffer buffer
, final RandomAccessFile raFile
) {
346 boolean startTagClosed
= false;
348 while ((i
= raFile
.read()) != -1) {
350 final char c
= (char) i
;
353 readQuote(buffer
, raFile
, '"');
354 } else if (c
== '\'') {
355 readQuote(buffer
, raFile
, '\'');
356 } else if (c
== '<') {
357 readElement(buffer
, raFile
);
358 } else if (c
== '/' && numRead
== 1) {
360 } else if (c
== '-' && numRead
== 3 && buffer
.substring(buffer
.length() - 3, buffer
.length() - 1).equals("!-")) { //$NON-NLS-1$
361 readComment(buffer
, raFile
); // found "<!--"
362 } else if (i
== '>') {
363 if (buffer
.charAt(buffer
.length() - 2) == '/') {
365 } else if (startTagClosed
) {
366 break; // found "<...>...</...>"
369 startTagClosed
= true; // found "<...>"
374 } catch (final IOException e
) {
379 private static void readQuote(final StringBuffer buffer
,
380 final RandomAccessFile raFile
, final char eq
) {
383 while ((i
= raFile
.read()) != -1) {
384 final char c
= (char) i
;
388 break; // found matching end-quote
392 } catch (final IOException e
) {
397 private static void readComment(final StringBuffer buffer
,
398 final RandomAccessFile raFile
) {
402 while ((i
= raFile
.read()) != -1) {
404 final char c
= (char) i
;
406 if (c
== '>' && numRead
>= 2 && buffer
.substring(buffer
.length() - 3, buffer
.length() - 1).equals("--")) //$NON-NLS-1$
408 break; // found "-->"
412 } catch (final IOException e
) {
418 * Parse an XML element.
420 * @param parentElement
423 * The contents to parse
424 * @return The parsed content
426 public static StringBuffer
parseElement(final Element parentElement
, final StringBuffer buffer
) {
427 final NodeList nodeList
= parentElement
.getChildNodes();
428 String separator
= null;
429 for (int i
= 0; i
< nodeList
.getLength(); i
++) {
430 final Node node
= nodeList
.item(i
);
431 if (node
.getNodeType() == Node
.ELEMENT_NODE
) {
432 if (separator
== null) {
433 separator
= " | "; //$NON-NLS-1$
435 buffer
.append(separator
);
437 final Element element
= (Element
) node
;
438 if (!element
.hasChildNodes()) {
439 buffer
.append(element
.getNodeName());
440 } else if (element
.getChildNodes().getLength() == 1 && element
.getFirstChild().getNodeType() == Node
.TEXT_NODE
) {
441 buffer
.append(element
.getNodeName() + ":" + element
.getFirstChild().getNodeValue().trim()); //$NON-NLS-1$
443 buffer
.append(element
.getNodeName());
444 buffer
.append(" [ "); //$NON-NLS-1$
445 parseElement(element
, buffer
);
446 buffer
.append(" ]"); //$NON-NLS-1$
448 } else if (node
.getNodeType() == Node
.TEXT_NODE
) {
449 if (node
.getNodeValue().trim().length() != 0) {
450 buffer
.append(node
.getNodeValue().trim());
458 * Get an input element if it is a valid record input. If not, we will look
459 * into its children for valid inputs.
461 * @param inputElement
462 * The main element to check for.
463 * @return The record element
465 public CustomXmlInputElement
getRecordInputElement(final CustomXmlInputElement inputElement
) {
466 if (inputElement
.isLogEntry()) {
468 } else if (inputElement
.getChildElements() != null) {
469 for (final CustomXmlInputElement childInputElement
: inputElement
.getChildElements()) {
470 final CustomXmlInputElement recordInputElement
= getRecordInputElement(childInputElement
);
471 if (recordInputElement
!= null) {
472 return recordInputElement
;
480 * Extract a trace event from an XML element.
484 * @param inputElement
486 * @return The extracted event
488 public CustomXmlEvent
extractEvent(final Element element
, final CustomXmlInputElement inputElement
) {
489 final CustomXmlEvent event
= new CustomXmlEvent(fDefinition
, this, TmfTimestamp
.ZERO
, fEventType
);
490 event
.setContent(new CustomEventContent(event
, new StringBuffer()));
491 parseElement(element
, event
, inputElement
);
495 private void parseElement(final Element element
, final CustomXmlEvent event
, final CustomXmlInputElement inputElement
) {
496 if (inputElement
.getInputName() != null && !inputElement
.getInputName().equals(CustomXmlTraceDefinition
.TAG_IGNORE
)) {
497 event
.parseInput(parseElement(element
, new StringBuffer()).toString(), inputElement
.getInputName(), inputElement
.getInputAction(), inputElement
.getInputFormat());
499 if (inputElement
.getAttributes() != null) {
500 for (final CustomXmlInputAttribute attribute
: inputElement
.getAttributes()) {
501 event
.parseInput(element
.getAttribute(attribute
.getAttributeName()), attribute
.getInputName(), attribute
.getInputAction(), attribute
.getInputFormat());
504 final NodeList childNodes
= element
.getChildNodes();
505 if (inputElement
.getChildElements() != null) {
506 for (int i
= 0; i
< childNodes
.getLength(); i
++) {
507 final Node node
= childNodes
.item(i
);
508 if (node
instanceof Element
) {
509 for (final CustomXmlInputElement child
: inputElement
.getChildElements()) {
510 if (node
.getNodeName().equals(child
.getElementName())) {
511 parseElement((Element
) node
, event
, child
);
522 * Retrieve the trace definition.
524 * @return The trace definition
526 public CustomTraceDefinition
getDefinition() {
533 * The default implementation sets the confidence to 100 if any of the first
534 * 100 lines of the file contains a valid record input element, and 0
538 public IStatus
validate(IProject project
, String path
) {
539 File file
= new File(path
);
540 if (!file
.exists() || !file
.isFile() || !file
.canRead()) {
541 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, Messages
.CustomTrace_FileNotFound
+ ": " + path
); //$NON-NLS-1$
543 try (BufferedRandomAccessFile rafile
= new BufferedRandomAccessFile(path
, "r")) { //$NON-NLS-1$
546 String line
= rafile
.getNextLine();
547 while ((line
!= null) && (lineCount
++ < MAX_LINES
)) {
548 final int idx
= indexOfElement(fRecordInputElement
.getElementName(), line
, 0);
550 rafile
.seek(rawPos
+ idx
+ 1); // +1 is for the <
551 final StringBuffer elementBuffer
= new StringBuffer("<"); //$NON-NLS-1$
552 readElement(elementBuffer
, rafile
);
553 final Element element
= parseElementBuffer(elementBuffer
);
554 if (element
!= null) {
556 return new TraceValidationStatus(CONFIDENCE
, Activator
.PLUGIN_ID
);
559 rawPos
= rafile
.getFilePointer();
560 line
= rafile
.getNextLine();
562 } catch (IOException e
) {
563 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, "IOException validating file: " + path
, e
); //$NON-NLS-1$
565 return new TraceValidationStatus(0, Activator
.PLUGIN_ID
);
568 private static int fCheckpointSize
= -1;
571 public synchronized int getCheckpointSize() {
572 if (fCheckpointSize
== -1) {
573 TmfCheckpoint c
= new TmfCheckpoint(TmfTimestamp
.ZERO
, new TmfLongLocation(0L), 0);
574 ByteBuffer b
= ByteBuffer
.allocate(ITmfCheckpoint
.MAX_SERIALIZE_SIZE
);
577 fCheckpointSize
= b
.position();
580 return fCheckpointSize
;
584 public ITmfLocation
restoreLocation(ByteBuffer bufferIn
) {
585 return new TmfLongLocation(bufferIn
);
589 protected ITmfTraceIndexer
createIndexer(int interval
) {
590 return new TmfBTreeTraceIndexer(this, interval
);