1 /*******************************************************************************
2 * Copyright (c) 2010, 2013 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
.linuxtools
.internal
.tmf
.ui
.parsers
.custom
;
15 import java
.io
.ByteArrayInputStream
;
16 import java
.io
.IOException
;
17 import java
.io
.RandomAccessFile
;
19 import javax
.xml
.parsers
.DocumentBuilder
;
20 import javax
.xml
.parsers
.DocumentBuilderFactory
;
21 import javax
.xml
.parsers
.ParserConfigurationException
;
22 import org
.eclipse
.core
.resources
.IProject
;
23 import org
.eclipse
.core
.resources
.IResource
;
24 import org
.eclipse
.core
.runtime
.IStatus
;
25 import org
.eclipse
.core
.runtime
.Status
;
26 import org
.eclipse
.linuxtools
.internal
.tmf
.ui
.Activator
;
27 import org
.eclipse
.linuxtools
.internal
.tmf
.ui
.parsers
.custom
.CustomXmlTraceDefinition
.InputAttribute
;
28 import org
.eclipse
.linuxtools
.internal
.tmf
.ui
.parsers
.custom
.CustomXmlTraceDefinition
.InputElement
;
29 import org
.eclipse
.linuxtools
.tmf
.core
.event
.ITmfEvent
;
30 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TmfTraceException
;
31 import org
.eclipse
.linuxtools
.tmf
.core
.io
.BufferedRandomAccessFile
;
32 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimestamp
;
33 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.ITmfContext
;
34 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.ITmfEventParser
;
35 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.TmfContext
;
36 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.TmfTrace
;
37 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
38 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.location
.ITmfLocation
;
39 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.location
.TmfLongLocation
;
40 import org
.w3c
.dom
.Document
;
41 import org
.w3c
.dom
.Element
;
42 import org
.w3c
.dom
.Node
;
43 import org
.w3c
.dom
.NodeList
;
44 import org
.xml
.sax
.EntityResolver
;
45 import org
.xml
.sax
.ErrorHandler
;
46 import org
.xml
.sax
.InputSource
;
47 import org
.xml
.sax
.SAXException
;
48 import org
.xml
.sax
.SAXParseException
;
51 * Trace object for custom XML trace parsers.
53 * @author Patrick Tassé
55 public class CustomXmlTrace
extends TmfTrace
implements ITmfEventParser
{
57 private static final TmfLongLocation NULL_LOCATION
= new TmfLongLocation((Long
) null);
58 private static final int DEFAULT_CACHE_SIZE
= 100;
60 private final CustomXmlTraceDefinition fDefinition
;
61 private final CustomXmlEventType fEventType
;
62 private final InputElement fRecordInputElement
;
63 private BufferedRandomAccessFile fFile
;
68 * @param definition Trace definition
70 public CustomXmlTrace(final CustomXmlTraceDefinition definition
) {
71 fDefinition
= definition
;
72 fEventType
= new CustomXmlEventType(fDefinition
);
73 fRecordInputElement
= getRecordInputElement(fDefinition
.rootInputElement
);
74 setCacheSize(DEFAULT_CACHE_SIZE
);
85 * Path to the trace/log file
88 * @throws TmfTraceException
89 * If the trace/log couldn't be opened
91 public CustomXmlTrace(final IResource resource
,
92 final CustomXmlTraceDefinition definition
, final String path
,
93 final int pageSize
) throws TmfTraceException
{
95 setCacheSize((pageSize
> 0) ? pageSize
: DEFAULT_CACHE_SIZE
);
96 initTrace(resource
, path
, CustomXmlEvent
.class);
100 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> eventType
) throws TmfTraceException
{
101 super.initTrace(resource
, path
, eventType
);
103 fFile
= new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
104 } catch (IOException e
) {
105 throw new TmfTraceException(e
.getMessage(), e
);
110 public synchronized void dispose() {
115 } catch (IOException e
) {
123 public ITmfTraceIndexer
getIndexer() {
124 return super.getIndexer();
128 public synchronized TmfContext
seekEvent(final ITmfLocation location
) {
129 final CustomXmlTraceContext context
= new CustomXmlTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
130 if (NULL_LOCATION
.equals(location
) || fFile
== null) {
134 if (location
== null) {
136 } else if (location
.getLocationInfo() instanceof Long
) {
137 fFile
.seek((Long
) location
.getLocationInfo());
140 final String recordElementStart
= "<" + fRecordInputElement
.elementName
; //$NON-NLS-1$
141 long rawPos
= fFile
.getFilePointer();
143 while ((line
= fFile
.getNextLine()) != null) {
144 final int idx
= line
.indexOf(recordElementStart
);
146 context
.setLocation(new TmfLongLocation(rawPos
+ idx
));
149 rawPos
= fFile
.getFilePointer();
152 } catch (final IOException e
) {
153 Activator
.getDefault().logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
160 public synchronized TmfContext
seekEvent(final double ratio
) {
162 return new CustomTxtTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
165 long pos
= Math
.round(ratio
* fFile
.length());
168 if (fFile
.read() == '\n') {
173 final ITmfLocation location
= new TmfLongLocation(pos
);
174 final TmfContext context
= seekEvent(location
);
175 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
177 } catch (final IOException e
) {
178 Activator
.getDefault().logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
179 return new CustomXmlTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
184 public synchronized double getLocationRatio(final ITmfLocation location
) {
189 if (location
.getLocationInfo() instanceof Long
) {
190 return (double) ((Long
) location
.getLocationInfo()) / fFile
.length();
192 } catch (final IOException e
) {
193 Activator
.getDefault().logError("Error getting location ration. File: " + getPath(), e
); //$NON-NLS-1$
199 public ITmfLocation
getCurrentLocation() {
200 // TODO Auto-generated method stub
205 public synchronized CustomXmlEvent
parseEvent(final ITmfContext tmfContext
) {
206 ITmfContext context
= seekEvent(tmfContext
.getLocation());
207 return parse(context
);
211 public synchronized CustomXmlEvent
getNext(final ITmfContext context
) {
212 final ITmfContext savedContext
= new TmfContext(context
.getLocation(), context
.getRank());
213 final CustomXmlEvent event
= parse(context
);
215 updateAttributes(savedContext
, event
.getTimestamp());
216 context
.increaseRank();
221 private synchronized CustomXmlEvent
parse(final ITmfContext tmfContext
) {
225 if (!(tmfContext
instanceof CustomXmlTraceContext
)) {
229 final CustomXmlTraceContext context
= (CustomXmlTraceContext
) tmfContext
;
230 if (context
.getLocation() == null || !(context
.getLocation().getLocationInfo() instanceof Long
) || NULL_LOCATION
.equals(context
.getLocation())) {
234 CustomXmlEvent event
= null;
236 if (fFile
.getFilePointer() != (Long
)context
.getLocation().getLocationInfo() + 1)
238 fFile
.seek((Long
)context
.getLocation().getLocationInfo() + 1); // +1 is for the <
240 final StringBuffer elementBuffer
= new StringBuffer("<"); //$NON-NLS-1$
241 readElement(elementBuffer
, fFile
);
242 final Element element
= parseElementBuffer(elementBuffer
);
244 event
= extractEvent(element
, fRecordInputElement
);
245 ((StringBuffer
) event
.getContent().getValue()).append(elementBuffer
);
248 final String recordElementStart
= "<" + fRecordInputElement
.elementName
; //$NON-NLS-1$
249 long rawPos
= fFile
.getFilePointer();
251 while ((line
= fFile
.getNextLine()) != null) {
252 final int idx
= line
.indexOf(recordElementStart
);
254 context
.setLocation(new TmfLongLocation(rawPos
+ idx
));
257 rawPos
= fFile
.getFilePointer();
259 } catch (final IOException e
) {
260 Activator
.getDefault().logError("Error parsing event. File: " + getPath(), e
); //$NON-NLS-1$
263 context
.setLocation(NULL_LOCATION
);
267 private Element
parseElementBuffer(final StringBuffer elementBuffer
) {
269 final DocumentBuilderFactory dbf
= DocumentBuilderFactory
.newInstance();
270 final DocumentBuilder db
= dbf
.newDocumentBuilder();
272 // The following allows xml parsing without access to the dtd
273 final EntityResolver resolver
= new EntityResolver () {
275 public InputSource
resolveEntity (final String publicId
, final String systemId
) {
276 final String empty
= ""; //$NON-NLS-1$
277 final ByteArrayInputStream bais
= new ByteArrayInputStream(empty
.getBytes());
278 return new InputSource(bais
);
281 db
.setEntityResolver(resolver
);
283 // The following catches xml parsing exceptions
284 db
.setErrorHandler(new ErrorHandler(){
286 public void error(final SAXParseException saxparseexception
) throws SAXException
{}
288 public void warning(final SAXParseException saxparseexception
) throws SAXException
{}
290 public void fatalError(final SAXParseException saxparseexception
) throws SAXException
{
291 throw saxparseexception
;
294 final Document doc
= db
.parse(new ByteArrayInputStream(elementBuffer
.toString().getBytes()));
295 return doc
.getDocumentElement();
296 } catch (final ParserConfigurationException e
) {
297 Activator
.getDefault().logError("Error parsing element buffer. File:" + getPath(), e
); //$NON-NLS-1$
298 } catch (final SAXException e
) {
299 Activator
.getDefault().logError("Error parsing element buffer. File:" + getPath(), e
); //$NON-NLS-1$
300 } catch (final IOException e
) {
301 Activator
.getDefault().logError("Error parsing element buffer. File: " + getPath(), e
); //$NON-NLS-1$
306 private void readElement(final StringBuffer buffer
, final RandomAccessFile raFile
) {
309 boolean startTagClosed
= false;
311 while ((i
= raFile
.read()) != -1) {
313 final char c
= (char)i
;
316 readQuote(buffer
, raFile
, '"');
317 } else if (c
== '\'') {
318 readQuote(buffer
, raFile
, '\'');
319 } else if (c
== '<') {
320 readElement(buffer
, raFile
);
321 } else if (c
== '/' && numRead
== 1) {
323 } else if (c
== '-' && numRead
== 3 && buffer
.substring(buffer
.length() - 3, buffer
.length() - 1).equals("!-")) { //$NON-NLS-1$
324 readComment(buffer
, raFile
); // found "<!--"
325 } else if (i
== '>') {
326 if (buffer
.charAt(buffer
.length() - 2) == '/') {
328 } else if (startTagClosed
) {
329 break; // found "<...>...</...>"
332 startTagClosed
= true; // found "<...>"
337 } catch (final IOException e
) {
342 private static void readQuote(final StringBuffer buffer
,
343 final RandomAccessFile raFile
, final char eq
) {
346 while ((i
= raFile
.read()) != -1) {
347 final char c
= (char)i
;
351 break; // found matching end-quote
355 } catch (final IOException e
) {
360 private static void readComment(final StringBuffer buffer
,
361 final RandomAccessFile raFile
) {
365 while ((i
= raFile
.read()) != -1) {
367 final char c
= (char)i
;
369 if (c
== '>' && numRead
>= 2 && buffer
.substring(buffer
.length() - 3, buffer
.length() - 1).equals("--")) //$NON-NLS-1$
371 break; // found "-->"
375 } catch (final IOException e
) {
381 * Parse an XML element.
383 * @param parentElement
386 * The contents to parse
387 * @return The parsed content
389 public static StringBuffer
parseElement(final Element parentElement
, final StringBuffer buffer
) {
390 final NodeList nodeList
= parentElement
.getChildNodes();
391 String separator
= null;
392 for (int i
= 0; i
< nodeList
.getLength(); i
++) {
393 final Node node
= nodeList
.item(i
);
394 if (node
.getNodeType() == Node
.ELEMENT_NODE
) {
395 if (separator
== null) {
396 separator
= " | "; //$NON-NLS-1$
398 buffer
.append(separator
);
400 final Element element
= (Element
) node
;
401 if (!element
.hasChildNodes()) {
402 buffer
.append(element
.getNodeName());
403 } else if (element
.getChildNodes().getLength() == 1 && element
.getFirstChild().getNodeType() == Node
.TEXT_NODE
) {
404 buffer
.append(element
.getNodeName() + ":" + element
.getFirstChild().getNodeValue().trim()); //$NON-NLS-1$
406 buffer
.append(element
.getNodeName());
407 buffer
.append(" [ "); //$NON-NLS-1$
408 parseElement(element
, buffer
);
409 buffer
.append(" ]"); //$NON-NLS-1$
411 } else if (node
.getNodeType() == Node
.TEXT_NODE
) {
412 if (node
.getNodeValue().trim().length() != 0) {
413 buffer
.append(node
.getNodeValue().trim());
421 * Get an input element if it is a valid record input. If not, we will look
422 * into its children for valid inputs.
424 * @param inputElement
425 * The main element to check for.
426 * @return The record element
428 public InputElement
getRecordInputElement(final InputElement inputElement
) {
429 if (inputElement
.logEntry
) {
431 } else if (inputElement
.childElements
!= null) {
432 for (final InputElement childInputElement
: inputElement
.childElements
) {
433 final InputElement recordInputElement
= getRecordInputElement(childInputElement
);
434 if (recordInputElement
!= null) {
435 return recordInputElement
;
443 * Extract a trace event from an XML element.
447 * @param inputElement
449 * @return The extracted event
451 public CustomXmlEvent
extractEvent(final Element element
, final InputElement inputElement
) {
452 final CustomXmlEvent event
= new CustomXmlEvent(fDefinition
, this, TmfTimestamp
.ZERO
, "", fEventType
,""); //$NON-NLS-1$ //$NON-NLS-2$
453 event
.setContent(new CustomEventContent(event
, new StringBuffer()));
454 parseElement(element
, event
, inputElement
);
458 private void parseElement(final Element element
, final CustomXmlEvent event
, final InputElement inputElement
) {
459 if (inputElement
.inputName
!= null && !inputElement
.inputName
.equals(CustomXmlTraceDefinition
.TAG_IGNORE
)) {
460 event
.parseInput(parseElement(element
, new StringBuffer()).toString(), inputElement
.inputName
, inputElement
.inputAction
, inputElement
.inputFormat
);
462 if (inputElement
.attributes
!= null) {
463 for (final InputAttribute attribute
: inputElement
.attributes
) {
464 event
.parseInput(element
.getAttribute(attribute
.attributeName
), attribute
.inputName
, attribute
.inputAction
, attribute
.inputFormat
);
467 final NodeList childNodes
= element
.getChildNodes();
468 if (inputElement
.childElements
!= null) {
469 for (int i
= 0; i
< childNodes
.getLength(); i
++) {
470 final Node node
= childNodes
.item(i
);
471 if (node
instanceof Element
) {
472 for (final InputElement child
: inputElement
.childElements
) {
473 if (node
.getNodeName().equals(child
.elementName
)) {
474 parseElement((Element
) node
, event
, child
);
485 * Retrieve the trace definition.
487 * @return The trace definition
489 public CustomTraceDefinition
getDefinition() {
494 public IStatus
validate(IProject project
, String path
) {
495 if (fileExists(path
)) {
496 return Status
.OK_STATUS
;
498 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, Messages
.CustomTrace_FileNotFound
+ ": " + path
); //$NON-NLS-1$