Contribution for Bug353020
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.ui / src / org / eclipse / linuxtools / tmf / ui / parsers / custom / CustomXmlTrace.java
1 /*******************************************************************************
2 * Copyright (c) 2010 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 *******************************************************************************/
12
13 package org.eclipse.linuxtools.tmf.ui.parsers.custom;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.File;
17 import java.io.FileNotFoundException;
18 import java.io.IOException;
19 import java.io.RandomAccessFile;
20
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24
25 import org.eclipse.linuxtools.tmf.event.TmfEvent;
26 import org.eclipse.linuxtools.tmf.event.TmfEventReference;
27 import org.eclipse.linuxtools.tmf.event.TmfEventSource;
28 import org.eclipse.linuxtools.tmf.event.TmfTimestamp;
29 import org.eclipse.linuxtools.tmf.io.BufferedRandomAccessFile;
30 import org.eclipse.linuxtools.tmf.trace.ITmfContext;
31 import org.eclipse.linuxtools.tmf.trace.ITmfLocation;
32 import org.eclipse.linuxtools.tmf.trace.ITmfTrace;
33 import org.eclipse.linuxtools.tmf.trace.TmfContext;
34 import org.eclipse.linuxtools.tmf.trace.TmfLocation;
35 import org.eclipse.linuxtools.tmf.trace.TmfTrace;
36 import org.eclipse.linuxtools.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputAttribute;
37 import org.eclipse.linuxtools.tmf.ui.parsers.custom.CustomXmlTraceDefinition.InputElement;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
42 import org.xml.sax.EntityResolver;
43 import org.xml.sax.ErrorHandler;
44 import org.xml.sax.InputSource;
45 import org.xml.sax.SAXException;
46 import org.xml.sax.SAXParseException;
47
48 public class CustomXmlTrace extends TmfTrace<CustomXmlEvent> {
49
50 private static final TmfLocation<Long> NULL_LOCATION = new TmfLocation<Long>((Long) null);
51
52 private CustomXmlTraceDefinition fDefinition;
53 private CustomXmlEventType fEventType;
54 private InputElement fRecordInputElement;
55
56 public CustomXmlTrace(String name, CustomXmlTraceDefinition definition, String path, int cacheSize) throws FileNotFoundException {
57 super(name, CustomXmlEvent.class, path, cacheSize);
58 fDefinition = definition;
59 fEventType = new CustomXmlEventType(fDefinition);
60 fRecordInputElement = getRecordInputElement(fDefinition.rootInputElement);
61 }
62
63 @Override
64 public TmfContext seekLocation(ITmfLocation<?> location) {
65 //System.out.println(Thread.currentThread().getName() + "::" + getName() + " seekLocation(" + ((location == null || location.getLocation() == null) ? "null" : location) + ")");
66 //new Throwable().printStackTrace();
67 CustomXmlTraceContext context = new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.INITIAL_RANK);
68 if (NULL_LOCATION.equals(location) || !new File(getPath()).isFile()) {
69 return context;
70 }
71 try {
72 context.raFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
73 if (location != null && location.getLocation() instanceof Long) {
74 context.raFile.seek((Long)location.getLocation());
75 }
76
77 String line;
78 String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$
79 long rawPos = context.raFile.getFilePointer();
80
81 while ((line = context.raFile.getNextLine()) != null) {
82 int idx = line.indexOf(recordElementStart);
83 if (idx != -1) {
84 context.setLocation(new TmfLocation<Long>(rawPos + idx));
85 return context;
86 }
87 rawPos = context.raFile.getFilePointer();
88 }
89 return context;
90 } catch (FileNotFoundException e) {
91 e.printStackTrace();
92 return context;
93 } catch (IOException e) {
94 e.printStackTrace();
95 return context;
96 }
97
98 }
99
100 @Override
101 public TmfContext seekLocation(double ratio) {
102 try {
103 BufferedRandomAccessFile raFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
104 long pos = (long) (ratio * raFile.length());
105 while (pos > 0) {
106 raFile.seek(pos - 1);
107 if (raFile.read() == '\n') break;
108 pos--;
109 }
110 ITmfLocation<?> location = new TmfLocation<Long>(new Long(pos));
111 TmfContext context = seekLocation(location);
112 context.setRank(ITmfContext.UNKNOWN_RANK);
113 return context;
114 } catch (FileNotFoundException e) {
115 e.printStackTrace();
116 return new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.INITIAL_RANK);
117 } catch (IOException e) {
118 e.printStackTrace();
119 return new CustomXmlTraceContext(NULL_LOCATION, ITmfContext.INITIAL_RANK);
120 }
121 }
122
123 @Override
124 public double getLocationRatio(ITmfLocation<?> location) {
125 try {
126 if (location.getLocation() instanceof Long) {
127 RandomAccessFile raFile = new RandomAccessFile(getPath(), "r"); //$NON-NLS-1$
128 return (double) ((Long) location.getLocation()) / raFile.length();
129 }
130 } catch (FileNotFoundException e) {
131 e.printStackTrace();
132 } catch (IOException e) {
133 e.printStackTrace();
134 }
135 return 0;
136 }
137
138 @Override
139 public ITmfTrace createTraceCopy() {
140 // TODO Auto-generated method stub
141 return null;
142 }
143
144 @Override
145 public ITmfLocation<?> getCurrentLocation() {
146 // TODO Auto-generated method stub
147 return null;
148 }
149
150 @Override
151 public synchronized TmfEvent getNextEvent(TmfContext context) {
152 ITmfContext savedContext = context.clone();
153 TmfEvent event = parseEvent(context);
154 if (event != null) {
155 updateIndex(savedContext, savedContext.getRank(), event.getTimestamp());
156 context.updateRank(1);
157 }
158 return event;
159 }
160
161 @Override
162 public TmfEvent parseEvent(TmfContext tmfContext) {
163 //System.out.println(Thread.currentThread().getName() + ":: " + getName() + " parseEvent(" + tmfContext.getRank() + " @ " + (tmfContext.getLocation().getLocation() == null ? "null" : tmfContext.getLocation()));
164 if (!(tmfContext instanceof CustomXmlTraceContext)) {
165 return null;
166 }
167
168 CustomXmlTraceContext context = (CustomXmlTraceContext) tmfContext;
169 if (!(context.getLocation().getLocation() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) {
170 return null;
171 }
172
173 synchronized (context.raFile) {
174 CustomXmlEvent event = null;
175 try {
176 if (context.raFile.getFilePointer() != (Long)context.getLocation().getLocation() + 1) {
177 context.raFile.seek((Long)context.getLocation().getLocation() + 1); // +1 is for the <
178 }
179 StringBuffer elementBuffer = new StringBuffer("<"); //$NON-NLS-1$
180 readElement(elementBuffer, context.raFile);
181 Element element = parseElementBuffer(elementBuffer);
182
183 event = extractEvent(element, fRecordInputElement);
184 ((StringBuffer) event.getContent().getContent()).append(elementBuffer);
185
186 String line;
187 String recordElementStart = "<" + fRecordInputElement.elementName; //$NON-NLS-1$
188 long rawPos = context.raFile.getFilePointer();
189
190 while ((line = context.raFile.getNextLine()) != null) {
191 int idx = line.indexOf(recordElementStart);
192 if (idx != -1) {
193 context.setLocation(new TmfLocation<Long>(rawPos + idx));
194 return event;
195 }
196 rawPos = context.raFile.getFilePointer();
197 }
198 } catch (IOException e) {
199 e.printStackTrace();
200 }
201 context.setLocation(NULL_LOCATION);
202 return event;
203 }
204 }
205
206 private Element parseElementBuffer(StringBuffer elementBuffer) {
207 try {
208 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
209 DocumentBuilder db = dbf.newDocumentBuilder();
210
211 // The following allows xml parsing without access to the dtd
212 EntityResolver resolver = new EntityResolver () {
213 @Override
214 public InputSource resolveEntity (String publicId, String systemId) {
215 String empty = ""; //$NON-NLS-1$
216 ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
217 return new InputSource(bais);
218 }
219 };
220 db.setEntityResolver(resolver);
221
222 // The following catches xml parsing exceptions
223 db.setErrorHandler(new ErrorHandler(){
224 @Override
225 public void error(SAXParseException saxparseexception) throws SAXException {}
226 @Override
227 public void warning(SAXParseException saxparseexception) throws SAXException {}
228 @Override
229 public void fatalError(SAXParseException saxparseexception) throws SAXException {
230 throw saxparseexception;
231 }});
232
233 Document doc = db.parse(new ByteArrayInputStream(elementBuffer.toString().getBytes()));
234 return doc.getDocumentElement();
235 } catch (ParserConfigurationException e) {
236 e.printStackTrace();
237 } catch (SAXException e) {
238 e.printStackTrace();
239 } catch (IOException e) {
240 e.printStackTrace();
241 }
242 return null;
243 }
244
245 private void readElement(StringBuffer buffer, RandomAccessFile raFile) {
246 try {
247 int numRead = 0;
248 boolean startTagClosed = false;
249 int i;
250 while ((i = raFile.read()) != -1) {
251 numRead++;
252 char c = (char)i;
253 buffer.append(c);
254 if (c == '"') {
255 readQuote(buffer, raFile, '"');
256 } else if (c == '\'') {
257 readQuote(buffer, raFile, '\'');
258 } else if (c == '<') {
259 readElement(buffer, raFile);
260 } else if (c == '/' && numRead == 1) {
261 break; // found "</"
262 } else if (c == '-' && numRead == 3 && buffer.substring(buffer.length() - 3, buffer.length() - 1).equals("!-")) { //$NON-NLS-1$
263 readComment(buffer, raFile); // found "<!--"
264 } else if (i == '>') {
265 if (buffer.charAt(buffer.length() - 2) == '/') {
266 break; // found "/>"
267 } else if (startTagClosed) {
268 break; // found "<...>...</...>"
269 } else {
270 startTagClosed = true; // found "<...>"
271 }
272 }
273 }
274 return;
275 } catch (IOException e) {
276 return;
277 }
278 }
279
280 private void readQuote(StringBuffer buffer, RandomAccessFile raFile, char eq) {
281 try {
282 int i;
283 while ((i = raFile.read()) != -1) {
284 char c = (char)i;
285 buffer.append(c);
286 if (c == eq) {
287 break; // found matching end-quote
288 }
289 }
290 return;
291 } catch (IOException e) {
292 return;
293 }
294 }
295
296 private void readComment(StringBuffer buffer, RandomAccessFile raFile) {
297 try {
298 int numRead = 0;
299 int i;
300 while ((i = raFile.read()) != -1) {
301 numRead++;
302 char c = (char)i;
303 buffer.append(c);
304 if (c == '>' && numRead >= 2 && buffer.substring(buffer.length() - 3, buffer.length() - 1).equals("--")) { //$NON-NLS-1$
305 break; // found "-->"
306 }
307 }
308 return;
309 } catch (IOException e) {
310 return;
311 }
312 }
313
314 public static StringBuffer parseElement(Element parentElement, StringBuffer buffer) {
315 NodeList nodeList = parentElement.getChildNodes();
316 String separator = null;
317 for (int i = 0; i < nodeList.getLength(); i++) {
318 Node node = nodeList.item(i);
319 if (node.getNodeType() == Node.ELEMENT_NODE) {
320 if (separator == null) {
321 separator = " | "; //$NON-NLS-1$
322 } else {
323 buffer.append(separator);
324 }
325 Element element = (Element) node;
326 if (element.hasChildNodes() == false) {
327 buffer.append(element.getNodeName());
328 } else if (element.getChildNodes().getLength() == 1 && element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
329 buffer.append(element.getNodeName() + ":" + element.getFirstChild().getNodeValue().trim()); //$NON-NLS-1$
330 } else {
331 buffer.append(element.getNodeName());
332 buffer.append(" [ "); //$NON-NLS-1$
333 parseElement(element, buffer);
334 buffer.append(" ]"); //$NON-NLS-1$
335 }
336 } else if (node.getNodeType() == Node.TEXT_NODE) {
337 if (node.getNodeValue().trim().length() != 0) {
338 buffer.append(node.getNodeValue().trim());
339 }
340 }
341 }
342 return buffer;
343 }
344
345 public InputElement getRecordInputElement(InputElement inputElement) {
346 if (inputElement.logEntry) {
347 return inputElement;
348 } else if (inputElement.childElements != null) {
349 for (InputElement childInputElement : inputElement.childElements) {
350 InputElement recordInputElement = getRecordInputElement(childInputElement);
351 if (recordInputElement != null) {
352 return recordInputElement;
353 }
354 }
355 }
356 return null;
357 }
358
359 public CustomXmlEvent extractEvent(Element element, InputElement inputElement) {
360 CustomXmlEvent event = new CustomXmlEvent(fDefinition, TmfTimestamp.Zero, new TmfEventSource(""), fEventType, new TmfEventReference("")); //$NON-NLS-1$ //$NON-NLS-2$
361 event.setContent(new CustomEventContent(event, new StringBuffer()));
362 parseElement(element, event, inputElement);
363 return event;
364 }
365
366 private void parseElement(Element element, CustomXmlEvent event, InputElement inputElement) {
367 if (inputElement.inputName != null && !inputElement.inputName.equals(CustomXmlTraceDefinition.TAG_IGNORE)) {
368 event.parseInput(parseElement(element, new StringBuffer()).toString(), inputElement.inputName, inputElement.inputAction, inputElement.inputFormat);
369 }
370 if (inputElement.attributes != null) {
371 for (InputAttribute attribute : inputElement.attributes) {
372 event.parseInput(element.getAttribute(attribute.attributeName), attribute.inputName, attribute.inputAction, attribute.inputFormat);
373 }
374 }
375 NodeList childNodes = element.getChildNodes();
376 if (inputElement.childElements != null) {
377 for (int i = 0; i < childNodes.getLength(); i++) {
378 Node node = childNodes.item(i);
379 if (node instanceof Element) {
380 for (InputElement child : inputElement.childElements) {
381 if (node.getNodeName().equals(child.elementName)) {
382 parseElement((Element) node, event, child);
383 break;
384 }
385 }
386 }
387 }
388 }
389 return;
390 }
391
392 public CustomTraceDefinition getDefinition() {
393 return fDefinition;
394 }
395 }
This page took 0.03946 seconds and 5 git commands to generate.