forked from processing/processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTable.java
More file actions
3089 lines (2587 loc) · 88.1 KB
/
Copy pathTable.java
File metadata and controls
3089 lines (2587 loc) · 88.1 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
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-12 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 processing.core.PApplet;
import processing.core.PConstants;
// function that will convert awful CSV to TSV.. or something else?
// maybe to write binary instead? then read the binary file once it's ok?
// if loading from a File object (or PApplet is passed in and we can check online)
// then check the (probable) size of the file before loading
// implement binary tables
// no column max/min functions since it needs to be per-datatype
// better to use float mx = max(float(getColumn(3)));
// *** but what to do with null entries?
// todo: need a method to reset the row/column indices after add/remove
// or just make sure that it's covered for all cases
// no longer the case, ja?
// <p>By default, empty rows are skipped and so are lines that start with the
// # character. Using # at the beginning of a line indicates a comment.</p>
// attempt at a CSV spec: http://tools.ietf.org/html/rfc4180
/**
* <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>
*
* @webref data:composite
*/
public class Table {
protected int rowCount;
// 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]
static final int STRING = 0;
static final int INT = 1;
static final int LONG = 2;
static final int FLOAT = 3;
static final int DOUBLE = 4;
static final int CATEGORICAL = 5;
int[] columnTypes;
protected RowIterator rowIterator;
/**
* Creates a new, empty table. Use addRow() to add additional rows.
*/
public Table() {
init();
}
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
public Table(File file, String options) throws IOException {
parse(new FileInputStream(file), checkOptions(file, options));
}
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>
* @param input
* @param options
* @throws IOException
*/
public Table(InputStream input, String options) throws IOException {
parse(input, options);
}
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);
}
}
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")) {
// 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;
}
protected void parse(InputStream input, String options) throws IOException {
init();
boolean awfulCSV = false;
boolean header = false;
String extension = null;
if (options != null) {
String[] opts = PApplet.splitTokens(options, " ,");
for (String opt : opts) {
if (opt.equals("tsv")) {
extension = "tsv";
} else if (opt.equals("csv")) {
extension = "csv";
} else if (opt.equals("newlines")) {
awfulCSV = true;
} else if (opt.equals("header")) {
header = true;
} else {
throw new IllegalArgumentException("'" + opt + "' is not a valid option for loading a Table");
}
}
}
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;
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 {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
*/
}
// 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 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;
if (row == 0 && 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;
}
row++;
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++;
checkColumn(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));
}
}
/**
* 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;
}
// 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 void save(File file, String options) throws IOException {
save(new FileOutputStream(file), checkOptions(file, options));
}
public void save(OutputStream output, String options) {
PrintWriter writer = PApplet.createWriter(output);
if (options != null) {
String[] opts = PApplet.splitTokens(options, ", ");
for (String opt : opts) {
if (opt.equals("csv")) {
writeCSV(writer);
} else if (opt.equals("tsv")) {
writeTSV(writer);
} else if (opt.equals("html")) {
writeHTML(writer);
} else {
throw new IllegalArgumentException("'" + opt + "' not understood. " +
"Only csv, tsv, and html are " +
"accepted as save parameters");
}
}
}
writer.close();
}
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();
}
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < getColumnCount(); col++) {
if (col != 0) {
writer.print('\t');
}
String entry = getString(row, col);
// just write null entries as blanks, rather than spewing 'null'
// all over the spreadsheet file.
if (entry != null) {
writer.print(entry);
}
}
writer.println();
}
writer.flush();
}
protected void writeCSV(PrintWriter writer) {
if (columnTitles != null) {
for (int col = 0; col < columns.length; col++) {
if (col != 0) {
writer.print(',');
}
if (columnTitles[col] != null) {
writeEntryCSV(writer, columnTitles[col]);
}
}
writer.println();
}
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < getColumnCount(); col++) {
if (col != 0) {
writer.print(',');
}
String entry = getString(row, col);
// just write null entries as blanks, rather than spewing 'null'
// all over the spreadsheet file.
if (entry != null) {
writeEntryCSV(writer, entry);
}
}
// Prints the newline for the row, even if it's missing
writer.println();
}
writer.flush();
}
protected void writeEntryCSV(PrintWriter writer, String entry) {
if (entry != null) {
if (entry.indexOf('\"') != -1) { // convert quotes to double quotes
char[] c = entry.toCharArray();
writer.print('\"');
for (int i = 0; i < c.length; i++) {
if (c[i] == '\"') {
writer.print("\"\"");
} else {
writer.print(c[i]);
}
}
writer.print('\"');
// add quotes if commas or CR/LF are in the entry
} else if (entry.indexOf(',') != -1 ||
entry.indexOf('\n') != -1 ||
entry.indexOf('\r') != -1) {
writer.print('\"');
writer.print(entry);
writer.print('\"');
// add quotes if leading or trailing space
} else if ((entry.length() > 0) &&
(entry.charAt(0) == ' ' ||
entry.charAt(entry.length() - 1) == ' ')) {
writer.print('\"');
writer.print(entry);
writer.print('\"');
} else {
writer.print(entry);
}
}
}
protected void writeHTML(PrintWriter writer) {
writer.println("<html>");
writer.println("<head>");
writer.println(" <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />");
writer.println("</head>");
writer.println("<body>");
writer.println(" <table>");
for (int row = 0; row < getRowCount(); row++) {
writer.println(" <tr>");
for (int col = 0; col < getColumnCount(); col++) {
String entry = getString(row, col);
writer.print(" <td>");
writeEntryHTML(writer, entry);
writer.println(" </td>");
}
writer.println(" </tr>");
}
writer.println(" </table>");
writer.println("</body>");
writer.println("</hmtl>");
writer.flush();
}
protected void writeEntryHTML(PrintWriter writer, String entry) {
//char[] chars = entry.toCharArray();
for (char c : entry.toCharArray()) { //chars) {
if (c == '<') {
writer.print("<");
} else if (c == '>') {
writer.print(">");
} else if (c == '&') {
writer.print("&");
} else if (c == '\'') {
writer.print("'");
} else if (c == '"') {
writer.print(""");
// not necessary with UTF-8?
// } else if (c < 32 || c > 127) {
// writer.print("&#");
// writer.print((int) c);
// writer.print(';');
} else {
writer.print(c);
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public void addColumn() {
addColumn(null, STRING);
}
public void addColumn(String title) {
addColumn(title, STRING);
}
public void addColumn(String title, int type) {
insertColumn(columns.length, title, type);
}
public void insertColumn(int index) {
insertColumn(index, null, STRING);
}
public void insertColumn(int index, String title) {
insertColumn(index, title, STRING);
}
public void insertColumn(int index, String title, int type) {
if (title != null && columnTitles == null) {
columnTitles = new String[columns.length];
}
if (columnTitles != null) {
columnTitles = PApplet.splice(columnTitles, title, index);
columnIndices = null;
}
columnTypes = PApplet.splice(columnTypes, type, index);
// columnCategories = (HashMapBlows[])
// PApplet.splice(columnCategories, new HashMapBlows(), index);
HashMapBlows[] catTemp = new HashMapBlows[columns.length + 1];
// Faster than arrayCopy for a dozen or so entries
for (int i = 0; i < index; i++) {
catTemp[i] = columnCategories[i];
}
catTemp[index] = new HashMapBlows();
for (int i = index; i < columns.length; i++) {
catTemp[i+1] = columnCategories[i];
}
columnCategories = catTemp;
Object[] temp = new Object[columns.length + 1];
System.arraycopy(columns, 0, temp, 0, index);
System.arraycopy(columns, index, temp, index+1, columns.length - index);
columns = temp;
switch (type) {
case INT: columns[index] = new int[rowCount]; break;
case LONG: columns[index] = new long[rowCount]; break;
case FLOAT: columns[index] = new float[rowCount]; break;
case DOUBLE: columns[index] = new double[rowCount]; break;
case STRING: columns[index] = new String[rowCount]; break;
case CATEGORICAL: columns[index] = new int[rowCount]; break;
}
}
public void removeColumn(String columnName) {
removeColumn(getColumnIndex(columnName));
}
public void removeColumn(int column) {
Object[] temp = new Object[columns.length + 1];
System.arraycopy(columns, 0, temp, 0, column);
System.arraycopy(columns, column+1, temp, column, (columns.length - column) + 1);
columns = temp;
}
public int getColumnCount() {
return columns.length;
}
/**
* Change the number of columns in this table. Resizes all rows to ensure
* the same number of columns in each row. Entries in the additional (empty)
* columns will be set to null.
* @param newCount
*/
public void setColumnCount(int newCount) {
int oldCount = columns.length;
if (oldCount != newCount) {
columns = (Object[]) PApplet.expand(columns, newCount);
// create new columns, default to String as the data type
for (int c = oldCount; c < newCount; c++) {
columns[c] = new String[rowCount];
}
if (columnTitles != null) {
columnTitles = PApplet.expand(columnTitles, newCount);
}
columnTypes = PApplet.expand(columnTypes, newCount);
columnCategories = (HashMapBlows[])
PApplet.expand(columnCategories, newCount);
}
}
public void setColumnType(String columnName, String columnType) {
setColumnType(checkColumnIndex(columnName), columnType);
}
/**
* Set the data type for a column so that using it is more efficient.
* @param column the column to change
* @param columnType One of int, long, float, double, or String.
*/
public void setColumnType(int column, String columnType) {
int type = -1;
if (columnType.equals("String")) {
type = STRING;
} else if (columnType.equals("int")) {
type = INT;
} else if (columnType.equals("long")) {
type = LONG;
} else if (columnType.equals("float")) {
type = FLOAT;
} else if (columnType.equals("double")) {
type = DOUBLE;
} else if (columnType.equals("categorical")) {
type = CATEGORICAL;
} else {
throw new IllegalArgumentException("'" + columnType + "' is not a valid column type.");
}
setColumnType(column, type);
}
protected void setColumnType(String columnName, int newType) {
setColumnType(checkColumnIndex(columnName), newType);
}
/**
* Sets the column type. If data already exists, then it'll be converted to
* the new type.
* @param column the column whose type should be changed
* @param newType something fresh, maybe try an int or a float for size?
*/
protected void setColumnType(int column, int newType) {
switch (newType) {
case INT: {
int[] intData = new int[rowCount];
for (int row = 0; row < rowCount; row++) {
String s = getString(row, column);
intData[row] = PApplet.parseInt(s, missingInt);
}
columns[column] = intData;
break;
}
case LONG: {
long[] longData = new long[rowCount];
for (int row = 0; row < rowCount; row++) {
String s = getString(row, column);
try {
longData[row] = Long.parseLong(s);
} catch (NumberFormatException nfe) {
longData[row] = missingLong;
}
}
columns[column] = longData;
break;
}
case FLOAT: {
float[] floatData = new float[rowCount];
for (int row = 0; row < rowCount; row++) {
String s = getString(row, column);
floatData[row] = PApplet.parseFloat(s, missingFloat);
}
columns[column] = floatData;
break;
}
case DOUBLE: {
double[] doubleData = new double[rowCount];
for (int row = 0; row < rowCount; row++) {
String s = getString(row, column);
try {
doubleData[row] = Double.parseDouble(s);