cd48427d6c5b60d36c115f9798565a7540927dbf
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.core / src / org / eclipse / linuxtools / tmf / core / trace / text / TextTrace.java
1 /*******************************************************************************
2 * Copyright (c) 2012, 2014 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 * Marc-Andre Laperle - Add persistent index support
12 *******************************************************************************/
13
14 package org.eclipse.linuxtools.tmf.core.trace.text;
15
16 import java.io.File;
17 import java.io.IOException;
18 import java.nio.ByteBuffer;
19 import java.util.Collections;
20 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23
24 import org.eclipse.core.resources.IProject;
25 import org.eclipse.core.resources.IResource;
26 import org.eclipse.core.runtime.IStatus;
27 import org.eclipse.core.runtime.Status;
28 import org.eclipse.linuxtools.internal.tmf.core.Activator;
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.TmfTrace;
36 import org.eclipse.linuxtools.tmf.core.trace.TraceValidationStatus;
37 import org.eclipse.linuxtools.tmf.core.trace.indexer.ITmfPersistentlyIndexable;
38 import org.eclipse.linuxtools.tmf.core.trace.indexer.ITmfTraceIndexer;
39 import org.eclipse.linuxtools.tmf.core.trace.indexer.TmfBTreeTraceIndexer;
40 import org.eclipse.linuxtools.tmf.core.trace.indexer.checkpoint.ITmfCheckpoint;
41 import org.eclipse.linuxtools.tmf.core.trace.indexer.checkpoint.TmfCheckpoint;
42 import org.eclipse.linuxtools.tmf.core.trace.location.ITmfLocation;
43 import org.eclipse.linuxtools.tmf.core.trace.location.TmfLongLocation;
44
45 /**
46 * Extension of TmfTrace for handling of line-based text traces parsed using
47 * regular expressions. Each line that matches the first line pattern indicates
48 * the start of a new event. The subsequent lines can contain additional
49 * information that is added to the current event.
50 *
51 * @param <T>
52 * TmfEvent class returned by this trace
53 *
54 * @since 3.0
55 */
56 public abstract class TextTrace<T extends TextTraceEvent> extends TmfTrace implements ITmfEventParser, ITmfPersistentlyIndexable {
57
58 private static final TmfLongLocation NULL_LOCATION = new TmfLongLocation(-1L);
59 private static final int MAX_LINES = 100;
60 private static final int MAX_CONFIDENCE = 100;
61
62 /** The default separator used for multi-line fields */
63 protected static final String SEPARATOR = " | "; //$NON-NLS-1$
64
65 /** The text file */
66 protected BufferedRandomAccessFile fFile;
67
68 /**
69 * Constructor
70 */
71 public TextTrace() {
72 }
73
74 /**
75 * {@inheritDoc}
76 * <p>
77 * The default implementation computes the confidence as the sum of weighted
78 * values of the first 100 lines of the file which match any of the provided
79 * validation patterns. For each matching line a weighted value between 1.5
80 * and 2.0 is assigned based on the group count of the matching patterns.
81 * The higher the group count, the closer the weighted value will be to 2.0.
82 */
83 @Override
84 public IStatus validate(IProject project, String path) {
85 File file = new File(path);
86 if (!file.exists()) {
87 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); //$NON-NLS-1$
88 }
89 if (!file.isFile()) {
90 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); //$NON-NLS-1$
91 }
92 int confidence = 0;
93 try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { //$NON-NLS-1$
94 int lineCount = 0;
95 double matches = 0.0;
96 String line = rafile.getNextLine();
97 List<Pattern> validationPatterns = getValidationPatterns();
98 while ((line != null) && (lineCount++ < MAX_LINES)) {
99 for(Pattern pattern : validationPatterns) {
100 Matcher matcher = pattern.matcher(line);
101 if (matcher.matches()) {
102 int groupCount = matcher.groupCount();
103 matches += (1.0 + groupCount / ((double) groupCount + 1));
104 }
105 }
106 confidence = (int) (MAX_CONFIDENCE * matches / lineCount);
107 line = rafile.getNextLine();
108 }
109 } catch (IOException e) {
110 Activator.logError("Error validating file: " + path, e); //$NON-NLS-1$
111 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); //$NON-NLS-1$
112 }
113
114 return new TraceValidationStatus(confidence, Activator.PLUGIN_ID);
115
116 }
117 @Override
118 public void initTrace(IResource resource, String path, Class<? extends ITmfEvent> type) throws TmfTraceException {
119 super.initTrace(resource, path, type);
120 try {
121 fFile = new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
122 } catch (IOException e) {
123 throw new TmfTraceException(e.getMessage(), e);
124 }
125 }
126
127 @Override
128 public synchronized void dispose() {
129 super.dispose();
130 if (fFile != null) {
131 try {
132 fFile.close();
133 } catch (IOException e) {
134 } finally {
135 fFile = null;
136 }
137 }
138 }
139
140 @Override
141 public synchronized TextTraceContext seekEvent(ITmfLocation location) {
142 TextTraceContext context = new TextTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK);
143 if (NULL_LOCATION.equals(location) || fFile == null) {
144 return context;
145 }
146 try {
147 if (location == null) {
148 fFile.seek(0);
149 } else if (location.getLocationInfo() instanceof Long) {
150 fFile.seek((Long) location.getLocationInfo());
151 }
152 long rawPos = fFile.getFilePointer();
153 String line = fFile.getNextLine();
154 while (line != null) {
155 Matcher matcher = getFirstLinePattern().matcher(line);
156 if (matcher.matches()) {
157 setupContext(context, rawPos, line, matcher);
158 return context;
159 }
160 rawPos = fFile.getFilePointer();
161 line = fFile.getNextLine();
162 }
163 return context;
164 } catch (IOException e) {
165 Activator.logError("Error seeking file: " + getPath(), e); //$NON-NLS-1$
166 return context;
167 }
168 }
169
170 private void setupContext(TextTraceContext context, long rawPos, String line, Matcher matcher) throws IOException {
171 context.setLocation(new TmfLongLocation(rawPos));
172 context.firstLineMatcher = matcher;
173 context.firstLine = line;
174 context.nextLineLocation = fFile.getFilePointer();
175 }
176
177 @Override
178 public synchronized TextTraceContext seekEvent(double ratio) {
179 if (fFile == null) {
180 return new TextTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK);
181 }
182 try {
183 long pos = (long) (ratio * fFile.length());
184 while (pos > 0) {
185 fFile.seek(pos - 1);
186 if (fFile.read() == '\n') {
187 break;
188 }
189 pos--;
190 }
191 ITmfLocation location = new TmfLongLocation(Long.valueOf(pos));
192 TextTraceContext context = seekEvent(location);
193 context.setRank(ITmfContext.UNKNOWN_RANK);
194 return context;
195 } catch (IOException e) {
196 Activator.logError("Error seeking file: " + getPath(), e); //$NON-NLS-1$
197 return new TextTraceContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK);
198 }
199 }
200
201 @Override
202 public double getLocationRatio(ITmfLocation location) {
203 if (fFile == null) {
204 return 0;
205 }
206 try {
207 long length = fFile.length();
208 if (length == 0) {
209 return 0;
210 }
211 if (location.getLocationInfo() instanceof Long) {
212 return (double) ((Long) location.getLocationInfo()) / length;
213 }
214 } catch (IOException e) {
215 Activator.logError("Error reading file: " + getPath(), e); //$NON-NLS-1$
216 }
217 return 0;
218 }
219
220 @Override
221 public ITmfLocation getCurrentLocation() {
222 return null;
223 }
224
225 @Override
226 public TextTraceEvent parseEvent(ITmfContext tmfContext) {
227 TextTraceContext context = seekEvent(tmfContext.getLocation());
228 return parse(context);
229 }
230
231 @Override
232 public synchronized T getNext(ITmfContext context) {
233 if (!(context instanceof TextTraceContext)) {
234 throw new IllegalArgumentException();
235 }
236 TextTraceContext savedContext = new TextTraceContext(context.getLocation(), context.getRank());
237 T event = parse((TextTraceContext) context);
238 if (event != null) {
239 updateAttributes(savedContext, event.getTimestamp());
240 context.increaseRank();
241 }
242 return event;
243 }
244
245 /**
246 * Parse the next event. The context is advanced.
247 *
248 * @param tmfContext
249 * the context
250 * @return the next event or null
251 */
252 protected synchronized T parse(TextTraceContext tmfContext) {
253 if (fFile == null) {
254 return null;
255 }
256 TextTraceContext context = tmfContext;
257 if (context.getLocation() == null || !(context.getLocation().getLocationInfo() instanceof Long) || NULL_LOCATION.equals(context.getLocation())) {
258 return null;
259 }
260
261 T event = parseFirstLine(context.firstLineMatcher, context.firstLine);
262
263 try {
264 if (fFile.getFilePointer() != context.nextLineLocation) {
265 fFile.seek(context.nextLineLocation);
266 }
267 long rawPos = fFile.getFilePointer();
268 String line = fFile.getNextLine();
269 while (line != null) {
270 Matcher matcher = getFirstLinePattern().matcher(line);
271 if (matcher.matches()) {
272 setupContext(context, rawPos, line, matcher);
273 return event;
274 }
275 parseNextLine(event, line);
276 rawPos = fFile.getFilePointer();
277 line = fFile.getNextLine();
278 }
279 } catch (IOException e) {
280 Activator.logError("Error reading file: " + getPath(), e); //$NON-NLS-1$
281 }
282
283 context.setLocation(NULL_LOCATION);
284 return event;
285 }
286
287 /**
288 * Gets the first line pattern.
289 *
290 * @return The first line pattern
291 */
292 protected abstract Pattern getFirstLinePattern();
293
294 /**
295 * Parses the first line data and returns a new event. When constructing the
296 * event, the concrete trace should use the trace's timestamp transform to
297 * create the timestamp, by either transforming the parsed time value
298 * directly or by using the method {@link #createTimestamp(long)}.
299 *
300 * @param matcher
301 * The matcher
302 * @param line
303 * The line to parse
304 * @return The parsed event
305 */
306 protected abstract T parseFirstLine(Matcher matcher, String line);
307
308 /**
309 * Parses the next line data for the current event.
310 *
311 * @param event
312 * The current event being parsed
313 * @param line
314 * The line to parse
315 */
316 protected abstract void parseNextLine(T event, String line);
317
318 /**
319 * Returns a ordered list of validation patterns that will be used in
320 * the default {@link #validate(IProject, String)} method to match
321 * the first 100 to compute the confidence level
322 *
323 * @return collection of patterns to validate against
324 * @since 3.2
325 */
326 protected List<Pattern> getValidationPatterns() {
327 return Collections.singletonList(getFirstLinePattern());
328 }
329
330 // ------------------------------------------------------------------------
331 // Helper methods
332 // ------------------------------------------------------------------------
333
334 /**
335 * Strip quotes surrounding a string
336 *
337 * @param input
338 * The input string
339 * @return The string without quotes
340 */
341 protected static String replaceQuotes(String input) {
342 String out = input.replaceAll("^\"|(\"\\s*)$", ""); //$NON-NLS-1$//$NON-NLS-2$
343 return out;
344 }
345
346 /**
347 * Strip brackets surrounding a string
348 *
349 * @param input
350 * The input string
351 * @return The string without brackets
352 */
353 protected static String replaceBrackets(String input) {
354 String out = input.replaceAll("^\\{|(\\}\\s*)$", ""); //$NON-NLS-1$//$NON-NLS-2$
355 return out;
356 }
357
358 private static int fCheckpointSize = -1;
359
360 @Override
361 public synchronized int getCheckpointSize() {
362 if (fCheckpointSize == -1) {
363 TmfCheckpoint c = new TmfCheckpoint(TmfTimestamp.ZERO, new TmfLongLocation(0L), 0);
364 ByteBuffer b = ByteBuffer.allocate(ITmfCheckpoint.MAX_SERIALIZE_SIZE);
365 b.clear();
366 c.serialize(b);
367 fCheckpointSize = b.position();
368 }
369
370 return fCheckpointSize;
371 }
372
373 @Override
374 protected ITmfTraceIndexer createIndexer(int interval) {
375 return new TmfBTreeTraceIndexer(this, interval);
376 }
377
378 @Override
379 public ITmfLocation restoreLocation(ByteBuffer bufferIn) {
380 return new TmfLongLocation(bufferIn);
381 }
382 }
This page took 0.047885 seconds and 4 git commands to generate.