FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
processing/core/src/processing/data/Table.java at master · h2oop/processing · GitHub
h2oop
processing
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
processing
/
core
/
src
/
processing
/
data
/
Table.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
4301 lines (3670 loc) · 123 KB
Breadcrumbs
processing
/
core
/
src
/
processing
/
data
/
Table.java
Copy path
File metadata and controls
4301 lines (3670 loc) · 123 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2011-13 Ben Fry and Casey Reas
Copyright (c) 2006-11 Ben Fry
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package
processing
.
data
;
import
java
.
io
.*;
import
java
.
lang
.
reflect
.*;
import
java
.
sql
.
ResultSet
;
import
java
.
sql
.
ResultSetMetaData
;
import
java
.
sql
.
SQLException
;
import
java
.
sql
.
Types
;
import
java
.
util
.*;
import
java
.
util
.
concurrent
.
ExecutorService
;
import
java
.
util
.
concurrent
.
Executors
;
import
java
.
util
.
zip
.
ZipEntry
;
import
java
.
util
.
zip
.
ZipInputStream
;
import
javax
.
xml
.
parsers
.
ParserConfigurationException
;
import
org
.
xml
.
sax
.
SAXException
;
import
processing
.
core
.
PApplet
;
import
processing
.
core
.
PConstants
;
/**
* <p>Generic class for handling tabular data, typically from a CSV, TSV, or
* other sort of spreadsheet file.</p>
* <p>CSV files are
* <a href="http://en.wikipedia.org/wiki/Comma-separated_values">comma separated values</a>,
* often with the data in quotes. TSV files use tabs as separators, and usually
* don't bother with the quotes.</p>
* <p>File names should end with .csv if they're comma separated.</p>
* <p>A rough "spec" for CSV can be found <a href="http://tools.ietf.org/html/rfc4180">here</a>.</p>
*
* @webref data:composite
* @see PApplet#loadTable(String)
* @see PApplet#saveTable(Table, String)
* @see TableRow
*/
public
class
Table
{
protected
int
rowCount
;
protected
int
allocCount
;
// protected boolean skipEmptyRows = true;
// protected boolean skipCommentLines = true;
// protected String extension = null;
// protected boolean commaSeparatedValues = false;
// protected boolean awfulCSV = false;
protected
String
missingString
=
null
;
protected
int
missingInt
=
0
;
protected
long
missingLong
=
0
;
protected
float
missingFloat
=
Float
.
NaN
;
protected
double
missingDouble
=
Double
.
NaN
;
protected
int
missingCategory
= -
1
;
String
[]
columnTitles
;
HashMapBlows
[]
columnCategories
;
HashMap
<
String
,
Integer
>
columnIndices
;
protected
Object
[]
columns
;
// [column]
// accessible for advanced users
static
public
final
int
STRING
=
0
;
static
public
final
int
INT
=
1
;
static
public
final
int
LONG
=
2
;
static
public
final
int
FLOAT
=
3
;
static
public
final
int
DOUBLE
=
4
;
static
public
final
int
CATEGORY
=
5
;
int
[]
columnTypes
;
protected
RowIterator
rowIterator
;
// 0 for doubling each time, otherwise the number of rows to increment on
// each expansion.
protected
int
expandIncrement
;
/**
* Creates a new, empty table. Use addRow() to add additional rows.
*/
public
Table
() {
init
();
}
/**
* @nowebref
*/
public
Table
(
File
file
)
throws
IOException
{
this
(
file
,
null
);
}
/**
* version that uses a File object; future releases (or data types)
* may include additional optimizations here
*
* @nowebref
*/
public
Table
(
File
file
,
String
options
)
throws
IOException
{
// uses createInput() to handle .gz (and eventually .bz2) files
init
();
parse
(
PApplet
.
createInput
(
file
),
extensionOptions
(
true
,
file
.
getName
(),
options
));
}
/**
* @nowebref
*/
public
Table
(
InputStream
input
)
throws
IOException
{
this
(
input
,
null
);
}
/**
* Read the table from a stream. Possible options include:
* <ul>
* <li>csv - parse the table as comma-separated values
* <li>tsv - parse the table as tab-separated values
* <li>newlines - this CSV file contains newlines inside individual cells
* <li>header - this table has a header (title) row
* </ul>
*
* @nowebref
* @param input
* @param options
* @throws IOException
*/
public
Table
(
InputStream
input
,
String
options
)
throws
IOException
{
init
();
parse
(
input
,
options
);
}
public
Table
(
Iterable
<
TableRow
>
rows
) {
init
();
int
row
=
0
;
int
alloc
=
10
;
for
(
TableRow
incoming
:
rows
) {
if
(
row
==
0
) {
setColumnTypes
(
incoming
.
getColumnTypes
());
setColumnTitles
(
incoming
.
getColumnTitles
());
// Do this after setting types, otherwise it'll attempt to parse the
// allocated but empty rows, and drive CATEGORY columns nutso.
setRowCount
(
alloc
);
}
else
if
(
row
==
alloc
) {
// Far more efficient than re-allocating all columns and doing a copy
alloc
*=
2
;
setRowCount
(
alloc
);
}
//addRow(row);
setRow
(
row
++,
incoming
);
}
// Shrink the table to only the rows that were used
if
(
row
!=
alloc
) {
setRowCount
(
row
);
}
}
/**
* @nowebref
*/
public
Table
(
ResultSet
rs
) {
init
();
try
{
ResultSetMetaData
rsmd
=
rs
.
getMetaData
();
int
columnCount
=
rsmd
.
getColumnCount
();
setColumnCount
(
columnCount
);
for
(
int
col
=
0
;
col
<
columnCount
;
col
++) {
setColumnTitle
(
col
,
rsmd
.
getColumnName
(
col
+
1
));
int
type
=
rsmd
.
getColumnType
(
col
+
1
);
switch
(
type
) {
// TODO these aren't tested. nor are they complete.
case
Types
.
INTEGER
:
case
Types
.
TINYINT
:
case
Types
.
SMALLINT
:
setColumnType
(
col
,
INT
);
break
;
case
Types
.
BIGINT
:
setColumnType
(
col
,
LONG
);
break
;
case
Types
.
FLOAT
:
setColumnType
(
col
,
FLOAT
);
break
;
case
Types
.
DECIMAL
:
case
Types
.
DOUBLE
:
case
Types
.
REAL
:
setColumnType
(
col
,
DOUBLE
);
break
;
}
}
int
row
=
0
;
while
(
rs
.
next
()) {
for
(
int
col
=
0
;
col
<
columnCount
;
col
++) {
switch
(
columnTypes
[
col
]) {
case
STRING
:
setString
(
row
,
col
,
rs
.
getString
(
col
+
1
));
break
;
case
INT
:
setInt
(
row
,
col
,
rs
.
getInt
(
col
+
1
));
break
;
case
LONG
:
setLong
(
row
,
col
,
rs
.
getLong
(
col
+
1
));
break
;
case
FLOAT
:
setFloat
(
row
,
col
,
rs
.
getFloat
(
col
+
1
));
break
;
case
DOUBLE
:
setDouble
(
row
,
col
,
rs
.
getDouble
(
col
+
1
));
break
;
default
:
throw
new
IllegalArgumentException
(
"column type "
+
columnTypes
[
col
] +
" not supported."
);
}
}
row
++;
// String[] row = new String[columnCount];
// for (int col = 0; col < columnCount; col++) {
// row[col] = rs.get(col + 1);
// }
// addRow(row);
}
}
catch
(
SQLException
s
) {
throw
new
RuntimeException
(
s
);
}
}
public
Table
typedParse
(
InputStream
input
,
String
options
)
throws
IOException
{
Table
table
=
new
Table
();
table
.
setColumnTypes
(
this
);
table
.
parse
(
input
,
options
);
return
table
;
}
protected
void
init
() {
columns
=
new
Object
[
0
];
columnTypes
=
new
int
[
0
];
columnCategories
=
new
HashMapBlows
[
0
];
}
/*
protected String checkOptions(File file, String options) throws IOException {
String extension = null;
String filename = file.getName();
int dotIndex = filename.lastIndexOf('.');
if (dotIndex != -1) {
extension = filename.substring(dotIndex + 1).toLowerCase();
if (!extension.equals("csv") &&
!extension.equals("tsv") &&
!extension.equals("html") &&
!extension.equals("bin")) {
// ignore extension
extension = null;
}
}
if (extension == null) {
if (options == null) {
throw new IOException("This table filename has no extension, and no options are set.");
}
} else { // extension is not null
if (options == null) {
options = extension;
} else {
// prepend the extension, it will be overridden if there's an option for it.
options = extension + "," + options;
}
}
return options;
}
*/
static
final
String
[]
loadExtensions
= {
"csv"
,
"tsv"
,
"ods"
,
"bin"
};
static
final
String
[]
saveExtensions
= {
"csv"
,
"tsv"
,
"html"
,
"bin"
};
static
public
String
extensionOptions
(
boolean
loading
,
String
filename
,
String
options
) {
String
extension
=
PApplet
.
checkExtension
(
filename
);
if
(
extension
!=
null
) {
for
(
String
possible
:
loading
?
loadExtensions
:
saveExtensions
) {
if
(
extension
.
equals
(
possible
)) {
if
(
options
==
null
) {
return
extension
;
}
else
{
// prepend the extension to the options (will be replaced by other
// options that override it later in the load loop)
return
extension
+
","
+
options
;
}
}
}
}
return
options
;
}
protected
void
parse
(
InputStream
input
,
String
options
)
throws
IOException
{
//init();
boolean
awfulCSV
=
false
;
boolean
header
=
false
;
String
extension
=
null
;
boolean
binary
=
false
;
String
worksheet
=
null
;
final
String
sheetParam
=
"worksheet="
;
String
[]
opts
=
null
;
if
(
options
!=
null
) {
opts
=
PApplet
.
trim
(
PApplet
.
split
(
options
,
','
));
for
(
String
opt
:
opts
) {
if
(
opt
.
equals
(
"tsv"
)) {
extension
=
"tsv"
;
}
else
if
(
opt
.
equals
(
"csv"
)) {
extension
=
"csv"
;
}
else
if
(
opt
.
equals
(
"ods"
)) {
extension
=
"ods"
;
}
else
if
(
opt
.
equals
(
"newlines"
)) {
awfulCSV
=
true
;
extension
=
"csv"
;
}
else
if
(
opt
.
equals
(
"bin"
)) {
binary
=
true
;
extension
=
"bin"
;
}
else
if
(
opt
.
equals
(
"header"
)) {
header
=
true
;
}
else
if
(
opt
.
startsWith
(
sheetParam
)) {
worksheet
=
opt
.
substring
(
sheetParam
.
length
());
}
else
if
(
opt
.
startsWith
(
"dictionary="
)) {
// ignore option, this is only handled by PApplet
}
else
{
throw
new
IllegalArgumentException
(
"'"
+
opt
+
"' is not a valid option for loading a Table"
);
}
}
}
if
(
extension
==
null
) {
throw
new
IllegalArgumentException
(
"No extension specified for this Table"
);
}
if
(
binary
) {
loadBinary
(
input
);
}
else
if
(
extension
.
equals
(
"ods"
)) {
odsParse
(
input
,
worksheet
);
}
else
{
BufferedReader
reader
=
PApplet
.
createReader
(
input
);
if
(
awfulCSV
) {
parseAwfulCSV
(
reader
,
header
);
}
else
if
(
"tsv"
.
equals
(
extension
)) {
parseBasic
(
reader
,
header
,
true
);
}
else
if
(
"csv"
.
equals
(
extension
)) {
parseBasic
(
reader
,
header
,
false
);
}
}
}
protected
void
parseBasic
(
BufferedReader
reader
,
boolean
header
,
boolean
tsv
)
throws
IOException
{
String
line
=
null
;
int
row
=
0
;
if
(
rowCount
==
0
) {
setRowCount
(
10
);
}
//int prev = 0; //-1;
try
{
while
((
line
=
reader
.
readLine
()) !=
null
) {
if
(
row
==
getRowCount
()) {
setRowCount
(
row
<<
1
);
}
if
(
row
==
0
&&
header
) {
setColumnTitles
(
tsv
?
PApplet
.
split
(
line
,
'\t'
) :
splitLineCSV
(
line
));
header
=
false
;
}
else
{
setRow
(
row
,
tsv
?
PApplet
.
split
(
line
,
'\t'
) :
splitLineCSV
(
line
));
row
++;
}
// this is problematic unless we're going to calculate rowCount first
if
(
row
%
10000
==
0
) {
/*
if (row < rowCount) {
int pct = (100 * row) / rowCount;
if (pct != prev) { // also prevents "0%" from showing up
System.out.println(pct + "%");
prev = pct;
}
}
*/
try
{
// Sleep this thread so that the GC can catch up
Thread
.
sleep
(
10
);
}
catch
(
InterruptedException
e
) {
e
.
printStackTrace
();
}
}
}
}
catch
(
Exception
e
) {
throw
new
RuntimeException
(
"Error reading table on line "
+
row
,
e
);
}
// shorten or lengthen based on what's left
if
(
row
!=
getRowCount
()) {
setRowCount
(
row
);
}
}
// public void convertTSV(BufferedReader reader, File outputFile) throws IOException {
// convertBasic(reader, true, outputFile);
// }
protected
void
parseAwfulCSV
(
BufferedReader
reader
,
boolean
header
)
throws
IOException
{
char
[]
c
=
new
char
[
100
];
int
count
=
0
;
boolean
insideQuote
=
false
;
int
alloc
=
100
;
setRowCount
(
100
);
int
row
=
0
;
int
col
=
0
;
int
ch
;
while
((
ch
=
reader
.
read
()) != -
1
) {
if
(
insideQuote
) {
if
(
ch
==
'\"'
) {
// this is either the end of a quoted entry, or a quote character
reader
.
mark
(
1
);
if
(
reader
.
read
() ==
'\"'
) {
// it's "", which means a quote character
if
(
count
==
c
.
length
) {
c
=
PApplet
.
expand
(
c
);
}
c
[
count
++] =
'\"'
;
}
else
{
// nope, just the end of a quoted csv entry
reader
.
reset
();
insideQuote
=
false
;
// TODO nothing here that prevents bad csv data from showing up
// after the quote and before the comma...
// set(row, col, new String(c, 0, count));
// count = 0;
// col++;
// insideQuote = false;
}
}
else
{
// inside a quote, but the character isn't a quote
if
(
count
==
c
.
length
) {
c
=
PApplet
.
expand
(
c
);
}
c
[
count
++] = (
char
)
ch
;
}
}
else
{
// not inside a quote
if
(
ch
==
'\"'
) {
insideQuote
=
true
;
}
else
if
(
ch
==
'\r'
||
ch
==
'\n'
) {
if
(
ch
==
'\r'
) {
// check to see if next is a '\n'
reader
.
mark
(
1
);
if
(
reader
.
read
() !=
'\n'
) {
reader
.
reset
();
}
}
setString
(
row
,
col
,
new
String
(
c
,
0
,
count
));
count
=
0
;
row
++;
if
(
row
==
1
&&
header
) {
// Use internal row removal (efficient because only one row).
removeTitleRow
();
// Un-set the header variable so that next time around, we don't
// just get stuck into a loop, removing the 0th row repeatedly.
header
=
false
;
// Reset the number of rows (removeTitleRow() won't reset our local 'row' counter)
row
=
0
;
}
// if (row % 1000 == 0) {
// PApplet.println(PApplet.nfc(row));
// }
if
(
row
==
alloc
) {
alloc
*=
2
;
setRowCount
(
alloc
);
}
col
=
0
;
}
else
if
(
ch
==
','
) {
setString
(
row
,
col
,
new
String
(
c
,
0
,
count
));
count
=
0
;
// starting a new column, make sure we have room
col
++;
ensureColumn
(
col
);
}
else
{
// just a regular character, add it
if
(
count
==
c
.
length
) {
c
=
PApplet
.
expand
(
c
);
}
c
[
count
++] = (
char
)
ch
;
}
}
}
// catch any leftovers
if
(
count
>
0
) {
setString
(
row
,
col
,
new
String
(
c
,
0
,
count
));
}
row
++;
// set row to row count (the current row index + 1)
if
(
alloc
!=
row
) {
setRowCount
(
row
);
// shrink to the actual size
}
}
/**
* Parse a line of text as comma-separated values, returning each value as
* one entry in an array of String objects. Remove quotes from entries that
* begin and end with them, and convert 'escaped' quotes to actual quotes.
* @param line line of text to be parsed
* @return an array of the individual values formerly separated by commas
*/
static
protected
String
[]
splitLineCSV
(
String
line
) {
char
[]
c
=
line
.
toCharArray
();
int
rough
=
1
;
// at least one
boolean
quote
=
false
;
for
(
int
i
=
0
;
i
<
c
.
length
;
i
++) {
if
(!
quote
&& (
c
[
i
] ==
','
)) {
rough
++;
}
else
if
(
c
[
i
] ==
'\"'
) {
quote
= !
quote
;
}
}
String
[]
pieces
=
new
String
[
rough
];
int
pieceCount
=
0
;
int
offset
=
0
;
while
(
offset
<
c
.
length
) {
int
start
=
offset
;
int
stop
=
nextComma
(
c
,
offset
);
offset
=
stop
+
1
;
// next time around, need to step over the comment
if
(
c
[
start
] ==
'\"'
&&
c
[
stop
-
1
] ==
'\"'
) {
start
++;
stop
--;
}
int
i
=
start
;
int
ii
=
start
;
while
(
i
<
stop
) {
if
(
c
[
i
] ==
'\"'
) {
i
++;
// skip over pairs of double quotes become one
}
if
(
i
!=
ii
) {
c
[
ii
] =
c
[
i
];
}
i
++;
ii
++;
}
String
s
=
new
String
(
c
,
start
,
ii
-
start
);
pieces
[
pieceCount
++] =
s
;
}
// make any remaining entries blanks instead of nulls
for
(
int
i
=
pieceCount
;
i
<
pieces
.
length
;
i
++) {
pieces
[
i
] =
""
;
}
return
pieces
;
}
static
protected
int
nextComma
(
char
[]
c
,
int
index
) {
boolean
quote
=
false
;
for
(
int
i
=
index
;
i
<
c
.
length
;
i
++) {
if
(!
quote
&& (
c
[
i
] ==
','
)) {
return
i
;
}
else
if
(
c
[
i
] ==
'\"'
) {
quote
= !
quote
;
}
}
return
c
.
length
;
}
/**
* Read a .ods (OpenDoc spreadsheet) zip file from an InputStream, and
* return the InputStream for content.xml contained inside.
*/
private
InputStream
odsFindContentXML
(
InputStream
input
) {
ZipInputStream
zis
=
new
ZipInputStream
(
input
);
ZipEntry
entry
=
null
;
try
{
while
((
entry
=
zis
.
getNextEntry
()) !=
null
) {
if
(
entry
.
getName
().
equals
(
"content.xml"
)) {
return
zis
;
}
}
}
catch
(
IOException
e
) {
e
.
printStackTrace
();
}
return
null
;
}
protected
void
odsParse
(
InputStream
input
,
String
worksheet
) {
try
{
InputStream
contentStream
=
odsFindContentXML
(
input
);
XML
xml
=
new
XML
(
contentStream
);
// table files will have multiple sheets..
// <table:table table:name="Sheet1" table:style-name="ta1" table:print="false">
// <table:table table:name="Sheet2" table:style-name="ta1" table:print="false">
// <table:table table:name="Sheet3" table:style-name="ta1" table:print="false">
XML
[]
sheets
=
xml
.
getChildren
(
"office:body/office:spreadsheet/table:table"
);
boolean
found
=
false
;
for
(
XML
sheet
:
sheets
) {
// System.out.println(sheet.getAttribute("table:name"));
if
(
worksheet
==
null
||
worksheet
.
equals
(
sheet
.
getString
(
"table:name"
))) {
odsParseSheet
(
sheet
);
found
=
true
;
if
(
worksheet
==
null
) {
break
;
// only read the first sheet
}
}
}
if
(!
found
) {
if
(
worksheet
==
null
) {
throw
new
RuntimeException
(
"No worksheets found in the ODS file."
);
}
else
{
throw
new
RuntimeException
(
"No worksheet named "
+
worksheet
+
" found in the ODS file."
);
}
}
}
catch
(
UnsupportedEncodingException
e
) {
e
.
printStackTrace
();
}
catch
(
IOException
e
) {
e
.
printStackTrace
();
}
catch
(
ParserConfigurationException
e
) {
e
.
printStackTrace
();
}
catch
(
SAXException
e
) {
e
.
printStackTrace
();
}
}
/**
* Parses a single sheet of XML from this file.
* @param The XML object for a single worksheet from the ODS file
*/
private
void
odsParseSheet
(
XML
sheet
) {
// Extra <p> or <a> tags inside the text tag for the cell will be stripped.
// Different from showing formulas, and not quite the same as 'save as
// displayed' option when saving from inside OpenOffice. Only time we
// wouldn't want this would be so that we could parse hyperlinks and
// styling information intact, but that's out of scope for the p5 version.
final
boolean
ignoreTags
=
true
;
XML
[]
rows
=
sheet
.
getChildren
(
"table:table-row"
);
//xml.getChildren("office:body/office:spreadsheet/table:table/table:table-row");
int
rowIndex
=
0
;
for
(
XML
row
:
rows
) {
int
rowRepeat
=
row
.
getInt
(
"table:number-rows-repeated"
,
1
);
// if (rowRepeat != 1) {
// System.out.println(rowRepeat + " " + rowCount + " " + (rowCount + rowRepeat));
// }
boolean
rowNotNull
=
false
;
XML
[]
cells
=
row
.
getChildren
();
int
columnIndex
=
0
;
for
(
XML
cell
:
cells
) {
int
cellRepeat
=
cell
.
getInt
(
"table:number-columns-repeated"
,
1
);
// <table:table-cell table:formula="of:=SUM([.E7:.E8])" office:value-type="float" office:value="4150">
// <text:p>4150.00</text:p>
// </table:table-cell>
String
cellData
=
ignoreTags
?
cell
.
getString
(
"office:value"
) :
null
;
// if there's an office:value in the cell, just roll with that
if
(
cellData
==
null
) {
int
cellKids
=
cell
.
getChildCount
();
if
(
cellKids
!=
0
) {
XML
[]
paragraphElements
=
cell
.
getChildren
(
"text:p"
);
if
(
paragraphElements
.
length
!=
1
) {
for
(
XML
el
:
paragraphElements
) {
System
.
err
.
println
(
el
.
toString
());
}
throw
new
RuntimeException
(
"found more than one text:p element"
);
}
XML
textp
=
paragraphElements
[
0
];
String
textpContent
=
textp
.
getContent
();
// if there are sub-elements, the content shows up as a child element
// (for which getName() returns null.. which seems wrong)
if
(
textpContent
!=
null
) {
cellData
=
textpContent
;
// nothing fancy, the text is in the text:p element
}
else
{
XML
[]
textpKids
=
textp
.
getChildren
();
StringBuffer
cellBuffer
=
new
StringBuffer
();
for
(
XML
kid
:
textpKids
) {
String
kidName
=
kid
.
getName
();
if
(
kidName
==
null
) {
odsAppendNotNull
(
kid
,
cellBuffer
);
}
else
if
(
kidName
.
equals
(
"text:s"
)) {
int
spaceCount
=
kid
.
getInt
(
"text:c"
,
1
);
for
(
int
space
=
0
;
space
<
spaceCount
;
space
++) {
cellBuffer
.
append
(
' '
);
}
}
else
if
(
kidName
.
equals
(
"text:span"
)) {
odsAppendNotNull
(
kid
,
cellBuffer
);
}
else
if
(
kidName
.
equals
(
"text:a"
)) {
// <text:a xlink:href="http://blah.com/">blah.com</text:a>
if
(
ignoreTags
) {
cellBuffer
.
append
(
kid
.
getString
(
"xlink:href"
));
}
else
{
odsAppendNotNull
(
kid
,
cellBuffer
);
}
}
else
{
odsAppendNotNull
(
kid
,
cellBuffer
);
System
.
err
.
println
(
getClass
().
getName
() +
": don't understand: "
+
kid
);
//throw new RuntimeException("I'm not used to this.");
}
}
cellData
=
cellBuffer
.
toString
();
}
//setString(rowIndex, columnIndex, c); //text[0].getContent());
//columnIndex++;
}
}
for
(
int
r
=
0
;
r
<
cellRepeat
;
r
++) {
if
(
cellData
!=
null
) {
//System.out.println("setting " + rowIndex + "," + columnIndex + " to " + cellData);
setString
(
rowIndex
,
columnIndex
,
cellData
);
}
columnIndex
++;
if
(
cellData
!=
null
) {
// if (columnIndex > columnMax) {
// columnMax = columnIndex;
// }
rowNotNull
=
true
;
}
}
}
if
(
rowNotNull
&&
rowRepeat
>
1
) {
String
[]
rowStrings
=
getStringRow
(
rowIndex
);
for
(
int
r
=
1
;
r
<
rowRepeat
;
r
++) {
addRow
(
rowStrings
);
}
}
rowIndex
+=
rowRepeat
;
}
}
private
void
odsAppendNotNull
(
XML
kid
,
StringBuffer
buffer
) {
String
content
=
kid
.
getContent
();
if
(
content
!=
null
) {
buffer
.
append
(
content
);
}
}
// A 'Class' object is used here, so the syntax for this function is:
// Table t = loadTable("cars3.tsv", "header");
// Record[] records = (Record[]) t.parse(Record.class);
// While t.parse("Record") might be nicer, the class is likely to be an
// inner class (another tab in a PDE sketch) or even inside a package,
// so additional information would be needed to locate it. The name of the
// inner class would be "SketchName$Record" which isn't acceptable syntax
// to make people use. Better to just introduce the '.class' syntax.
// Unlike the Table class itself, this accepts char and boolean fields in
// the target class, since they're much more prevalent, and don't require
// a zillion extra methods and special cases in the rest of the class here.
// since this is likely an inner class, needs a reference to its parent,
// because that's passed to the constructor parameter (inserted by the
// compiler) of an inner class by the runtime.
/** incomplete, do not use */
public
void
parseInto
(
Object
enclosingObject
,
String
fieldName
) {
Class
<?>
target
=
null
;
Object
outgoing
=
null
;
Field
targetField
=
null
;
try
{
// Object targetObject,
// Class target -> get this from the type of fieldName
// Class sketchClass = sketch.getClass();
Class
<?>
sketchClass
=
enclosingObject
.
getClass
();
targetField
=
sketchClass
.
getDeclaredField
(
fieldName
);
// PApplet.println("found " + targetField);
Class
<?>
targetArray
=
targetField
.
getType
();
if
(!
targetArray
.
isArray
()) {
// fieldName is not an array
}
else
{
target
=
targetArray
.
getComponentType
();
outgoing
=
Array
.
newInstance
(
target
,
getRowCount
());
}
}
catch
(
NoSuchFieldException
e
) {
e
.
printStackTrace
();
}
catch
(
SecurityException
e
) {
e
.
printStackTrace
();
}
// Object enclosingObject = sketch;
// PApplet.println("enclosing obj is " + enclosingObject);
Class
<?>
enclosingClass
=
target
.
getEnclosingClass
();
Constructor
<?>
con
=
null
;
try
{
if
(
enclosingClass
==
null
) {
con
=
target
.
getDeclaredConstructor
();
//new Class[] { });
// PApplet.println("no enclosing class");
}
else
{
con
=
target
.
getDeclaredConstructor
(
new
Class
[] {
enclosingClass
});
// PApplet.println("enclosed by " + enclosingClass.getName());
}
if
(!
con
.
isAccessible
()) {
// System.out.println("setting constructor to public");
con
.
setAccessible
(
true
);
}
}
catch
(
SecurityException
e
) {
e
.
printStackTrace
();
}
catch
(
NoSuchMethodException
e
) {
e
.
printStackTrace
();
}
Field
[]
fields
=
target
.
getDeclaredFields
();
ArrayList
<
Field
>
inuse
=
new
ArrayList
<
Field
>();
for
(
Field
field
:
fields
) {
String
name
=
field
.
getName
();
if
(
getColumnIndex
(
name
,
false
) != -
1
) {
// System.out.println("found field " + name);
if
(!
field
.
isAccessible
()) {
// PApplet.println(" changing field access");
field
.
setAccessible
(
true
);
}
inuse
.
add
(
field
);
}
else
{
// System.out.println("skipping field " + name);
}
}
int
index
=
0
;
try
{
for
(
TableRow
row
:
rows
()) {
Object
item
=
null
;
if
(
enclosingClass
==
null
) {
//item = target.newInstance();
item
=
con
.
newInstance
();
}
else
{
item
=
con
.
newInstance
(
new
Object
[] {
enclosingObject
});
}
//Object item = defaultCons.newInstance(new Object[] { });
for
(
Field
field
:
inuse
) {
String
name
=
field
.
getName
();
//PApplet.println("gonna set field " + name);
if
(
field
.
getType
() ==
String
.
class
) {
field
.
set
(
item
,
row
.
getString
(
name
));
}
else
if
(
field
.
getType
() ==
Integer
.
TYPE
) {
field
.
setInt
(
item
,
row
.
getInt
(
name
));
}
else
if
(
field
.
getType
() ==
Long
.
TYPE
) {
field
.
setLong
(
item
,
row
.
getLong
(
name
));
}
else
if
(
field
.
getType
() ==
Float
.
TYPE
) {
field
.
setFloat
(
item
,
row
.
getFloat
(
name
));
}
else
if
(
field
.
getType
() ==
Double
.
TYPE
) {
field
.
setDouble
(
item
,
row
.
getDouble
(
name
));
}
else
if
(
field
.
getType
() ==
Boolean
.
TYPE
) {
String
content
=
row
.
getString
(
name
);
if
(
content
!=
null
) {
// Only bother setting if it's true,
// otherwise false by default anyway.
if
(
content
.
toLowerCase
().
equals
(
"true"
) ||
content
.
equals
(
"1"
)) {
field
.
setBoolean
(
item
,
true
);
}
}
// if (content == null) {
// field.setBoolean(item, false); // necessary?
// } else if (content.toLowerCase().equals("true")) {
// field.setBoolean(item, true);
// } else if (content.equals("1")) {
// field.setBoolean(item, true);
// } else {
// field.setBoolean(item, false); // necessary?
// }
}
else
if
(
field
.
getType
() ==
Character
.
TYPE
) {
String
content
=
row
.
getString
(
name
);
if
(
content
!=
null
&&
content
.
length
() >
0
) {
// Otherwise set to \0 anyway
field
.
setChar
(
item
,
content
.
charAt
(
0
));
}
}
}
// list.add(item);
Array
.
set
(
outgoing
,
index
++,
item
);
}
if
(!
targetField
.
isAccessible
()) {
// PApplet.println("setting target field to public");
targetField
.
setAccessible
(
true
);
}
// Set the array in the sketch
// targetField.set(sketch, outgoing);
targetField
.
set
(
enclosingObject
,
outgoing
);
}
catch
(
InstantiationException
e
) {
e
.
printStackTrace
();
}
catch
(
IllegalAccessException
e
) {
e
.
printStackTrace
();
}
catch
(
IllegalArgumentException
e
) {
e
.
printStackTrace
();
}
catch
(
InvocationTargetException
e
) {
e
.
printStackTrace
();
}
}
public
boolean
save
(
File
file
,
String
options
)
throws
IOException
{
return
save
(
PApplet
.
createOutput
(
file
),
Table
.
extensionOptions
(
false
,
file
.
getName
(),
options
));
}
public
boolean
save
(
OutputStream
output
,
String
options
) {
PrintWriter
writer
=
PApplet
.
createWriter
(
output
);
String
extension
=
null
;
if
(
options
==
null
) {
throw
new
IllegalArgumentException
(
"No extension specified for saving this Table"
);
}
String
[]
opts
=
PApplet
.
trim
(
PApplet
.
split
(
options
,
','
));
// Only option for save is the extension, so we can safely grab the last
extension
=
opts
[
opts
.
length
-
1
];
boolean
found
=
false
;
for
(
String
ext
:
saveExtensions
) {
if
(
extension
.
equals
(
ext
)) {
found
=
true
;
break
;
}
}
// Not providing a fallback; let's make users specify an extension
if
(!
found
) {
throw
new
IllegalArgumentException
(
"'"
+
extension
+
"' not available for Table"
);
}
if
(
extension
.
equals
(
"csv"
)) {
writeCSV
(
writer
);
}
else
if
(
extension
.
equals
(
"tsv"
)) {
writeTSV
(
writer
);
}
else
if
(
extension
.
equals
(
"html"
)) {
writeHTML
(
writer
);
}
else
if
(
extension
.
equals
(
"bin"
)) {
try
{
saveBinary
(
output
);
}
catch
(
IOException
e
) {
e
.
printStackTrace
();
return
false
;
}
}
writer
.
flush
();
writer
.
close
();
return
true
;
}
protected
void
writeTSV
(
PrintWriter
writer
) {
if
(
columnTitles
!=
null
) {
for
(
int
col
=
0
;
col
<
columns
.
length
;
col
++) {
if
(
col
!=
0
) {
writer
.
print
(
'\t'
);
}
if
(
columnTitles
[
col
] !=
null
) {
writer
.
print
(
columnTitles
[
col
]);
}
}
writer
.
println
();
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL