Child: [9eb143] (diff)

Download this file

CommaSeparatedValuesReader.java    558 lines (498 with data), 18.9 kB

  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
/*
* Copyright 2013 TecO - Karlsruhe Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package squirrel.model.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.rmi.UnexpectedException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import squirrel.model.Annotation;
import squirrel.model.SensorDatum;
import squirrel.model.io.DataColumn.Unit;
import squirrel.util.Range;
/**
* Reader to Read from CSV file
* @author marc
*
*/
public class CommaSeparatedValuesReader extends AbstractReader<CSVDataColumn> implements
FileDictionary {
private String valueSeparator;
private String lineSeparator;
private RandomAccessFile raf = null;
private double average = -1.0;
private double averageLineLength = 0;
private double min = Double.MAX_VALUE;
private double minLineLength = Double.MAX_VALUE;
private long startTimestamp = -1;
private long endTimestamp = -1;
// (int) (0.01 * (raf.length() / (line.length() + lineSeparator.length())));
static int percentForCalculation = 100;
protected String replace;
private boolean getAdressInit = false;
private long size = -1;
protected TimeConverter timeConverter;
private int offset = 0;
// this is set when parseTimestamp() is invoked.
private long lastFilePosition = -1L;
int count = 0;
/**
* Constructs csvReader with TimeConverter
* @param dataSource contains descriptions for each column and the path of
* the source file
*/
public CommaSeparatedValuesReader(CSVDataSource dataSource) {
super(dataSource);
if (count == 1)
System.exit(1);
count++;
this.valueSeparator = dataSource.getElemSeparator();
this.lineSeparator = dataSource.getLineSeparator();
// For now we hardcode the timestamp to be in the first column
this.replace = dataSource.getDataColumn(0).getCustomDateSeparator();
if (dataSource.isHeader()) {
initialiseReader();
this.offset = dataSource.getHeaderLength() + 1;
try {
raf.seek(this.offset);
int c = raf.read();
if ('\n' == c) {
c = raf.read();
if ('\r' == c) {
offset += 2;
} else {
offset += 1;
}
} else {
offset += 2;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int counterUnits = 0;
int posUnit = 0;
for (int j = 0; j < dataSource.getNumberOfColumns(); j++) {
if (dataSource.getDataColumn(j).getType().isTimeStamp()
&& !dataSource.getDataColumn(j).isDate()) {
counterUnits += dataSource.getDataColumn(j).getCustomDateUnits().length;
}
}
Unit[] u = new Unit[counterUnits];
for (int j = 0; j < dataSource.getNumberOfColumns(); j++) {
if (dataSource.getDataColumn(j).getType().isTimeStamp()
&& !dataSource.getDataColumn(j).isDate()) {
for (int i = 0; i < dataSource.getDataColumn(j).getCustomDateUnits().length; i++) {
u[posUnit] = (dataSource.getDataColumn(j).getCustomDateUnits()[i]);
posUnit++;
}
}
}
this.timeConverter = new TimeConverter(u);
}
private void initialiseReader() {
try {
if (raf == null)
raf = new RandomAccessFile(new File(dataSource.getLocation().toURI()), "r");
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
}
@Override
public Iterable<SensorAnnotationTuple> readData(Range range) {
List<SensorAnnotationTuple> annotationTuple =
new ArrayList<SensorAnnotationTuple>((int) (range.getDistance() / min));
if (range.getStart() > endTimeStamp() ||
range.getEnd() < startTimeStamp()) {
return annotationTuple;
}
if (range.getStart() < startTimeStamp()) {
range = new Range(startTimeStamp(), range.getEnd());
}
if (range.getEnd() > endTimeStamp()) {
range = new Range(range.getStart(), endTimeStamp());
}
long fileStart = getAddressInFile(range.getStart());
String[] values;
int counterDataColumns = 0;
int countAnnotationColumns = 0;
// Calculates the length of the arrays
for (int i = 0; i < dataSource.getNumberOfColumns(); i++) {
if (dataSource.getDataColumn(i).getType().isSensor()) {
counterDataColumns++;
} else if (dataSource.getDataColumn(i).getType().isOldAnnotation()) {
countAnnotationColumns++;
}
}
initialiseReader();
try {
StringBuilder sb = new StringBuilder();
raf.seek(fileStart);
boolean read = true;
while (read) {
FileChannel channel = raf.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
int N = channel.read(buffer);
if (N <= 0)
read = false;
buffer.flip();
while (read && buffer.hasRemaining()) {
char c = (char) buffer.get();
if (c == '\"')
continue;
if (c == '\n') {
values = sb.toString().replaceAll("\\r", "").split(valueSeparator);
SensorAnnotationTuple sat =
parseRow(values, counterDataColumns, countAnnotationColumns);
if (sat.getSensorDatum().getTimestamp() >= range.getEnd()) {
read = false;
}
else
annotationTuple.add(sat);
sb = new StringBuilder();
}
else {
sb.append(c);
}
}
}
} catch (IOException e) {
// IO exeption vor reading next line or for cannot read file
e.printStackTrace();
}
bufferTuple = annotationTuple;
bufferRange = range;
finalizeReader();
return annotationTuple;
}
private void finalizeReader() {
// try {
// raf.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
private void initFileDictionary() throws IOException {
long last = 0;
long before = 0;
String line = "";
String[] row;
int count = 1;
int percent = percentForCalculation;
for (int i = 0; i < percent && (line = raf.readLine()) != null; i++) {
line = line.replaceAll("\"", "");
row = line.split(valueSeparator);
// if block for the minimum
if (last == -1) {
last = getTimestamp(row);
before = last;
} else if (min > getTimestamp(row) - last) {
min = getTimestamp(row) - last;
last = getTimestamp(row);
count++;
} else {
last = getTimestamp(row);
}
if (minLineLength > line.length()) {
minLineLength = line.length();
}
averageLineLength += line.length();
}
averageDistance();
averageLineLength = averageLineLength / count;
}
/**
* Given a {@code timestamp} lookup its address in this file and return it.
* The address of a {@code timestamp} is the number of the byte on the start
* of the line the given {@code timestamp} is located on.
* <p>
* If {@code timestamp} is bigger than the biggest timestamp in this file,
* return a negative value. If the timestamp does not exist but is smaller
* than the largest timestamp, take the next bigger timestamp to compute the
* returned address.
*
* @param timestamp the positive timestamp whos address is to be computed.
* @return the address of {@code timestamp} in bytes in this file.
*/
@Override
public long getAddressInFile(long timestamp) {
if (timestamp < 0) {
throw new IllegalArgumentException("Timestamp may not be smaller than 0");
}
// if (timestamp == startTimeStamp())
// return offset;
// This is a binary search
initialiseReader();
long begByte = 0+offset;
long endByte = getFileLength();
while (true) {
// the byte we are currently looking at
long cursorByte = (endByte + begByte) / 2;
long parsedTS = parseTimestamp(cursorByte, raf);
if (parsedTS < timestamp) {
begByte = cursorByte + 1;
} else if (parsedTS > timestamp) {
endByte = cursorByte;
} else {
return this.lastFilePosition;
}
if (begByte == endByte) {
return this.lastFilePosition;
}
}
}
/**
* Parse and return the timestamp that is found on the line denoted by
* {@code start}. {@code raf.getFilePointer()} will return the position of
* the start of that line, after this method has been called. This method
* also sets {@code lastFilePosition} to said position or to a negative
* value, if an {@code IOException} occured.
*
* @param start the position in the file from where to start reading.
* @param raf the random access file to read from.
* @return the timestamp on the line denoted by {@code start} or a negative
* value if an {@code IOException} occured.
*/
private long parseTimestamp(long start, RandomAccessFile raf) {
long cursor = -1;
String line = null;
try {
long startOfLine = goToBeginningOfLine(start, raf);
raf.seek(startOfLine);
line = raf.readLine();
cursor = startOfLine;
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (line == null)
return -1;
line = line.replaceAll("\"", "");
// parsing
String[] splitted = line.split(valueSeparator, dataSource.idxOfLastTimestamp() + 2);
this.lastFilePosition = cursor;
return getTimestamp(splitted);
}
/**
* Search backwards for the first newline before {@code position} and return
* the position in bytes after said newline.
* <p>
* After calling this method, {@code raf.getFilePointer()} will return the
* same value as this method.
* <p>
* If {@code position} is {@code 0}, {@code 0} is returned and {@code raf}
* will be at position {@code 0}.
* <p>
* If an {@code IOException} occurs, a negative value is returned.
*
* @param position the position from which to start searching.
* @param raf the random access file to search in.
*/
private long goToBeginningOfLine(long position, RandomAccessFile raf) throws IOException {
int c = 1;
position -= 2;
while (position >= 0) {
raf.seek(position);
switch (c = raf.read()) {
case -1:
case '\n':
return position + 1;
case '\r':
long cur = raf.getFilePointer();
if ((raf.read()) != '\n') {
raf.seek(cur);
} else {
return position + 2;
}
break;
}
position -= 1;
}
return 0;
}
private long getFileLength() {
long length = -1;
try {
length = raf.getChannel().size();
} catch (IOException ioe) {
System.err.println("This Exception was caught and ignored: " + ioe);
}
return length;
}
@Override
public double averageDistance() {
try {
if (average == -1) {
initialiseReader();
raf.seek(0 + offset);
String line;
String[] row;
long last = -1;
long before = 0;
int count = 0;
int percent = 10;
percent = percentForCalculation;
initialiseReader();
for (int i = 0; i < percent && (line = raf.readLine()) != null; i++) {
line = line.replaceAll("\"", "");
row = line.split(valueSeparator);
if (last == -1) {
last = getTimestamp(row);
before = last;
average = 0;
} else {
last = getTimestamp(row);
average = average + last - before;
before = last;
count++;
}
}
average = average / count;
finalizeReader();
}
} catch (IOException e) {
e.printStackTrace();
}
return average;
}
@Override
public long startTimeStamp() {
if (startTimestamp != -1) {
return startTimestamp;
}
initialiseReader();
String line;
try {
raf.seek(0 + offset);
line = raf.readLine();
line = line.replaceAll("\"", "");
long timestamp = getTimestamp(line.split(valueSeparator));
finalizeReader();
startTimestamp = timestamp;
return timestamp;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
private long getFileSize() {
if (size == -1) {
try {
size = raf.getChannel().size();
return size;
} catch (IOException e) {
e.printStackTrace();
}
}
return size;
}
@Override
public long endTimeStamp() {
initialiseReader();
return parseTimestamp(getFileSize() - 1, raf);
}
/**
* Parse the values in the SensorAnnotationTuple
* @param values the values of one line of the File
* @param counterDataColumns how much DataColumns are there
* @param countAnnotationColumns how much Annotations are there
* @return the SensorAnnotationTuple for the Line
*/
protected SensorAnnotationTuple parseRow(String[] values, int counterDataColumns,
int countAnnotationColumns) {
SensorAnnotationTuple aT = new SensorAnnotationTuple();
SensorDatum sD = new SensorDatum();
Annotation[] anno = new Annotation[countAnnotationColumns];
double[] sensorValues = new double[counterDataColumns];
int countS = 0;
int countA = 0;
sD.setTimestamp(getTimestamp(values));
for (int i = 0; i < values.length && i < dataSource.getNumberOfColumns(); i++) {
if (dataSource.getDataColumn(i).getType().isSensor()) {
sensorValues[countS] = Double.parseDouble(values[i]);
countS++;
} else if (dataSource.getDataColumn(i).getType().isOldAnnotation()) {
Range range = new Range(sD.getTimestamp(), sD.getTimestamp() + 1);
String wyh = "asdf";
anno[countA] = getAnnotation(range, values[i], dataSource.getDataColumn(i), countA);
countA++;
}
}
sD.setValues(sensorValues);
aT.setAnnotation(anno);
aT.setSensorDatum(sD);
return aT;
}
/**
* Returns the milliseconds of value
* @param the row
* @return milliseconds of value
*/
protected long getTimestamp(String[] values) {
long milliseconds = 0;
boolean timeConvert = false;
ArrayList<String[]> timeValues = new ArrayList<>();
int countLength = 0;
int countPos = 0;
for (int i = 0; i < dataSource.getNumberOfColumns(); i++) {
if (dataSource.getDataColumn(i).isDate()) {
Date date;
try {
date = dataSource.getDataColumn(i).getDateFormat().parse(values[i]);
milliseconds += date.getTime();
System.out.println(date.toString());
System.out.println(date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
} else if (dataSource.getDataColumn(i).getType().isTimeStamp()) {
timeConvert = true;
String[] parts =
values[i].split(
dataSource.getDataColumn(i).getCustomDateSeparator());
String s = dataSource.getDataColumn(i).getCustomDateSeparator();
if (parts.length == 0) {
parts = new String[] { values[i] };
}
countLength += parts.length;
timeValues.add(parts);
}
}
String[] units = new String[countLength];
if (timeConvert) {
for (String[] string : timeValues) {
for (int j = 0; j < string.length; j++) {
units[countPos] = string[j];
countPos++;
}
}
milliseconds += timeConverter.getMilliseconds(units, 0);
}
return milliseconds;
}
}