-
Notifications
You must be signed in to change notification settings - Fork 62
/
GeoJsonReaderDriver.java
1671 lines (1596 loc) · 65.8 KB
/
GeoJsonReaderDriver.java
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
/**
* H2GIS is a library that brings spatial support to the H2 Database Engine
* <http://www.h2database.com>. H2GIS is developed by CNRS
* <http://www.cnrs.fr/>.
*
* This code is part of the H2GIS project. H2GIS is free software; you can
* redistribute it and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; version 3.0 of
* the License.
*
* H2GIS 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 <http://www.gnu.org/licenses/>.
*
*
* For more information, please consult: <http://www.h2gis.org/>
* or contact directly: info_at_h2gis.org
*/
package org.h2gis.functions.io.geojson;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.h2.value.ValueGeometry;
import org.h2gis.api.EmptyProgressVisitor;
import org.h2gis.api.ProgressVisitor;
import org.h2gis.utilities.JDBCUtilities;
import org.h2gis.utilities.TableLocation;
import org.h2gis.utilities.dbtypes.DBTypes;
import org.h2gis.utilities.dbtypes.DBUtils;
import org.locationtech.jts.geom.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.zip.GZIPInputStream;
/**
* Driver to import a GeoJSON file into a spatial table.
*
* Supported geometries are POINT, LINESTRING, POLYGON and GEOMETRYCOLLECTION.
*
* The driver requires all Feature objects in a collection to have the same
* schema of properties. To build the table schema the first feature of the
* FeatureCollection is parsed. If the GeoJSON format does not contain any
* properties, a default primary key is added.
*
* @author Erwan Bocher
* @author Hai Trung Pham
*/
public class GeoJsonReaderDriver {
private final File fileName;
private final Connection connection;
private static GeometryFactory GF;
private final String encoding;
private final boolean deleteTable;
private PreparedStatement preparedStatement = null;
private JsonFactory jsFactory;
private int nbFeature = 1;
private int featureCounter = 1;
private ProgressVisitor progress = new EmptyProgressVisitor();
// For progression information return
private static final int AVERAGE_NODE_SIZE = 500;
boolean hasGeometryField = false;
private static final Logger log = LoggerFactory.getLogger(GeoJsonReaderDriver.class);
private int parsedSRID = 0;
private DBTypes dbType =DBTypes.H2GIS;
private String tableLocation;
private LinkedHashMap<String, Integer> cachedColumnNames;
private LinkedHashMap<String, Integer> cachedColumnIndex;
private static final int BATCH_MAX_SIZE = 100;
private Set finalGeometryTypes;
private JsonEncoding jsonEncoding;
private boolean hasZ =false;
/**
* Driver to import a GeoJSON file into a spatial table.
*
* @param connection
* @param fileName
* @param encoding
* @param deleteTable
*/
public GeoJsonReaderDriver(Connection connection, File fileName, String encoding, boolean deleteTable) {
this.connection = connection;
this.fileName = fileName;
this.encoding = encoding;
this.deleteTable = deleteTable;
}
/**
* Read the GeoJSON file.
*
* @param progress
* @param tableReference
<<<<<<< HEAD
* @return
=======
* @return
>>>>>>> f17753e8b57767967bf0b70caf35a42b79d92059
* @throws java.sql.SQLException
* @throws java.io.IOException
*/
public String read(ProgressVisitor progress, String tableReference) throws SQLException, IOException {
if (fileName != null && fileName.getName().toLowerCase().endsWith(".geojson")) {
if (!fileName.exists()) {
throw new SQLException("The file " + tableLocation + " doesn't exist ");
}
this.dbType = DBUtils.getDBType(connection);
this.tableLocation = TableLocation.parse(tableReference, dbType).toString();
if (deleteTable) {
Statement stmt = connection.createStatement();
stmt.execute("DROP TABLE IF EXISTS " + tableLocation);
stmt.close();
}
if (fileName.length() > 0) {
parseGeoJson(progress);
return tableLocation;
} else {
JDBCUtilities.createEmptyTable(connection, tableLocation);
return tableLocation;
}
} else if (fileName != null && fileName.getName().toLowerCase().endsWith(".gz")) {
if (!fileName.exists()) {
throw new SQLException("The file " + tableLocation + " doesn't exist ");
}
this.dbType = DBUtils.getDBType(connection);
this.tableLocation = TableLocation.parse(tableReference, dbType).toString();
if (deleteTable) {
Statement stmt = connection.createStatement();
stmt.execute("DROP TABLE IF EXISTS " + tableLocation);
stmt.close();
}
if (fileName.length() > 0) {
this.progress = progress.subProcess(100);
init();
FileInputStream fis = new FileInputStream(fileName);
if (parseMetadata(new GZIPInputStream(fis))) {
connection.setAutoCommit(false);
GF = new GeometryFactory(new PrecisionModel(), parsedSRID);
fis = new FileInputStream(fileName);
parseData(new GZIPInputStream(fis));
connection.setAutoCommit(true);
return tableLocation;
} else {
throw new SQLException("Cannot create the table " + tableLocation + " to import the GeoJSON data");
}
} else {
JDBCUtilities.createEmptyTable(connection, tableLocation);
return tableLocation;
}
} else {
throw new SQLException("The geojson read driver supports only geojson or gz extensions");
}
}
/**
* Parses a GeoJSON 1.0 file and writes it to a table.
*
* A GeoJSON file is structured as follows:
*
* { "type": "FeatureCollection", "features": [ { "type": "Feature",
* "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties":
* {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type":
* "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0],
* [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } },
* {"type": "Feature", "geometry": { "type": "Polygon", "coordinates": [
* [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
* ]}, "properties": { "prop0": "value0", "prop1": {"this": "that"} } } ] }
*
* Note: To include information on the coordinate range for geometries, a
* GeoJSON object may have a member named "bbox".
*
* Syntax:
*
* { "type": "FeatureCollection", "bbox": [100.0, 0.0, 105.0, 1.0],
* "features": [ ... ] }
*
*
* @param progress
*/
private void parseGeoJson(ProgressVisitor progress) throws SQLException, IOException {
this.progress = progress.subProcess(100);
init();
if (parseMetadata(new FileInputStream(fileName))) {
connection.setAutoCommit(false);
GF = new GeometryFactory(new PrecisionModel(), parsedSRID);
parseData(new FileInputStream(fileName));
connection.setAutoCommit(true);
} else {
throw new SQLException("Cannot create the table " + tableLocation + " to import the GeoJSON data");
}
}
/**
* Parses the all GeoJSON feature to create the PreparedStatement.
*
* @throws SQLException
* @throws IOException
*/
private boolean parseMetadata(InputStream is) throws SQLException, IOException {
try {
cachedColumnNames = new LinkedHashMap<>();
finalGeometryTypes = new HashSet<String>();
try (JsonParser jp = jsFactory.createParser(new InputStreamReader(is, jsonEncoding.getJavaName()))) {
jp.nextToken();//START_OBJECT
jp.nextToken(); // field_name (type)
String dataType = jp.getText();
if (dataType.equalsIgnoreCase(GeoJsonField.TYPE)) {
jp.nextToken(); // value_string (FeatureCollection)
dataType = jp.getText();
if (dataType.equalsIgnoreCase(GeoJsonField.FEATURECOLLECTION)) {
jp.nextToken(); // FIELD_NAME features
parseFeaturesMetadata(jp);
}
else if(dataType.equalsIgnoreCase(GeoJsonField.FEATURE)){
parseFeatureMetadata(jp);
}
else if(dataType.equalsIgnoreCase(GeoJsonField.POINT)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.LINESTRING)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.POLYGON)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else if(dataType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)){
parseGeometryMetadata(jp, jp.getText());
hasGeometryField = true;
}
else {
throw new SQLException("Malformed GeoJSON file. Found '" + dataType + "'");
}
} else if (dataType.equalsIgnoreCase(GeoJsonField.FEATURES)) {
parseFeaturesMetadata(jp);
} else {
throw new SQLException("Malformed GeoJSON file. Found '" + dataType + "'");
}
} //START_OBJECT
} catch (FileNotFoundException ex) {
throw new SQLException(ex);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ex) {
throw new IOException(ex);
}
}
// Now we create the table if there is at least one geometry field.
if (hasGeometryField) {
StringBuilder createTable = new StringBuilder();
createTable.append("CREATE TABLE ");
createTable.append(tableLocation);
createTable.append(" (");
//Add the geometry column
String finalGeometryType = GeoJsonField.GEOMETRY;
if (finalGeometryTypes.size() == 1) {
finalGeometryType = (String) finalGeometryTypes.iterator().next();
createTable.append("THE_GEOM GEOMETRY(").append(hasZ?finalGeometryType+"Z":finalGeometryType).append(",").append(parsedSRID).append(")");
}
else{
createTable.append("THE_GEOM GEOMETRY(GEOMETRY,").append(parsedSRID).append(")");
}
cachedColumnIndex = new LinkedHashMap<>();
StringBuilder insertTable = new StringBuilder("INSERT INTO ");
insertTable.append(tableLocation).append(" VALUES(ST_GeomFromWKB(?, ").append(parsedSRID).append(")");
int i = 1;
for (Map.Entry<String, Integer> columns : cachedColumnNames.entrySet()) {
String columnName = columns.getKey();
Integer columnType = columns.getValue();
cachedColumnIndex.put(columnName, i++);
createTable.append(",").append(columns.getKey()).append(" ").append(getSQLTypeName(columnType));
if(columnType==Types.ARRAY){
if(dbType == DBTypes.H2 || dbType == DBTypes.H2GIS){
insertTable.append(",").append(" ? FORMAT json");
}else {
insertTable.append(",").append("cast(? as json)");
}
}else {
insertTable.append(",").append("?");
}
}
createTable.append(")");
insertTable.append(")");
try (Statement stmt = connection.createStatement()) {
stmt.execute(createTable.toString());
}
preparedStatement = connection.prepareStatement(insertTable.toString());
return true;
} else {
throw new SQLException("The geojson file does not contain any geometry.");
}
}
/**
* Parses the featureCollection to collect the field properties
*
* @param jp
* @throws IOException
* @throws SQLException
*/
private void parseFeaturesMetadata(JsonParser jp) throws IOException, SQLException {
// Passes all the properties until "Feature" object is found
while (!jp.getText().equalsIgnoreCase(GeoJsonField.FEATURES)
&& !jp.getText().equalsIgnoreCase(GeoJsonField.CRS)) {
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.START_ARRAY) || jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.skipChildren();
}
jp.nextToken();
}
if (jp.getText().equalsIgnoreCase(GeoJsonField.CRS)) {
parsedSRID = readCRS(jp);
}
if (jp.getText().equalsIgnoreCase(GeoJsonField.FEATURES)) {
jp.nextToken(); // START_ARRAY [
JsonToken token = jp.nextToken(); // START_OBJECT {
while (token != JsonToken.END_ARRAY) {
jp.nextToken(); // FIELD_NAME type
jp.nextToken(); // VALUE_STRING Feature
String geomType = jp.getText();
if (geomType.equalsIgnoreCase(GeoJsonField.FEATURE)) {
if (progress.isCanceled()) {
throw new SQLException("Canceled by user");
}
parseFeatureMetadata(jp);
token = jp.nextToken(); //START_OBJECT new feature
nbFeature++;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'");
}
}
//LOOP END_ARRAY ]
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'features', found '" + jp.getText() + "'");
}
}
/**
* Features in GeoJSON contain a geometry object and additional properties
* This method is used to collect metadata
*
* Syntax:
*
* { "type": "Feature", "geometry":{"type": "Point", "coordinates": [102.0,
* 0.5]}, "properties": {"prop0": "value0"} }
*
* @param jp
*/
private void parseFeatureMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken();
String field = jp.getText();
//Avoid all token which are not 'properties', 'geometry', 'type'
while (!field.equalsIgnoreCase(GeoJsonField.GEOMETRY)
&& !field.equalsIgnoreCase(GeoJsonField.PROPERTIES)
&& !jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.START_ARRAY) || jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.skipChildren();
}
jp.nextToken();
field = jp.getText();
}
// FIELD_NAME geometry
if (field.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
parseParentGeometryMetadata(jp);
hasGeometryField = true;
jp.nextToken();
} else if (field.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
parsePropertiesMetadata(jp);
jp.nextToken();
}
//If there is only one geometry field in the feature them the next
//token corresponds to the end object of the feature
//Avoid all token which are not 'properties', 'geometry', 'type'
field = jp.getText();
while (!field.equalsIgnoreCase(GeoJsonField.GEOMETRY)
&& !field.equalsIgnoreCase(GeoJsonField.PROPERTIES)
&& !jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.START_ARRAY) || jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.skipChildren();
}
jp.nextToken();
field = jp.getText();
}
if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
String secondParam = jp.getText();// field name
if (secondParam.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
parseParentGeometryMetadata(jp);
hasGeometryField = true;
} else if (secondParam.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
parsePropertiesMetadata(jp);
}
while (jp.nextToken() != JsonToken.END_OBJECT); //END_OBJECT } feature
}
}
/**
* Parses the geometries to return its properties
*
* @param jp
* @throws IOException
* @throws SQLException
*/
private void parseParentGeometryMetadata(JsonParser jp) throws IOException, SQLException {
if (jp.nextToken() != JsonToken.VALUE_NULL) {//START_OBJECT { in case of null geometry
jp.nextToken(); // FIELD_NAME type
jp.nextToken(); //VALUE_STRING Point
String geometryType = jp.getText();
parseGeometryMetadata(jp, geometryType);
}
}
/**
* Parses a all type of geometries and check if the geojson is wellformed.
*
* Syntax:
*
* "geometry":{"type": "Point", "coordinates": [102.0,0.5]}
*
* @param jp
* @throws IOException
*/
private void parseGeometryMetadata(JsonParser jp, String geometryType) throws IOException, SQLException {
if (geometryType.equalsIgnoreCase(GeoJsonField.POINT)) {
parsePointMetadata(jp);
finalGeometryTypes.add(GeoJsonField.POINT);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
parseMultiPointMetadata(jp);
finalGeometryTypes.add(GeoJsonField.MULTIPOINT);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
parseLinestringMetadata(jp);
finalGeometryTypes.add(GeoJsonField.LINESTRING);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
parseMultiLinestringMetadata(jp);
finalGeometryTypes.add(GeoJsonField.MULTILINESTRING);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
parsePolygonMetadata(jp);
finalGeometryTypes.add(GeoJsonField.POLYGON);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
parseMultiPolygonMetadata(jp);
finalGeometryTypes.add(GeoJsonField.MULTIPOLYGON);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
parseGeometryCollectionMetadata(jp);
finalGeometryTypes.add(GeoJsonField.GEOMETRYCOLLECTION);
} else {
throw new SQLException("Unsupported geometry : " + geometryType);
}
}
/**
* Parses a point and check if it's wellformated
*
* Syntax:
*
* { "type": "Point", "coordinates": [100.0, 0.0] }
*
* @param jp
* @throws IOException
*/
private void parsePointMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ to parse the coordinate
parseCoordinateMetadata(jp);
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
* Parses a MultiPoint and check if it's wellformated
*
* Syntax:
*
* { "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }
*
* @param jp
* @throws IOException
*/
private void parseMultiPointMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
parseCoordinatesMetadata(jp);
jp.nextToken();//END_OBJECT } geometry
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
*
* Parses a LineString and check if it's wellformated
*
* Syntax:
*
* { "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }
*
* @param jp
*/
private void parseLinestringMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
parseCoordinatesMetadata(jp);
jp.nextToken();//END_OBJECT } geometry
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
* Parses MultiLineString defined as:
*
* { "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0,
* 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
*
* @param jp
*/
private void parseMultiLinestringMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken();//START_ARRAY [ coordinates
jp.nextToken(); // START_ARRAY [ coordinates line
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
parseCoordinatesMetadata(jp);
jp.nextToken();
}
jp.nextToken();//END_OBJECT } geometry
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
* Parses a Polygon as an array of LinearRing coordinate arrays. The first
* element in the array represents the exterior ring. Any subsequent
* elements represent interior rings (or holes).
*
* Syntax:
*
* No holes:
*
* { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
* [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
*
* With holes:
*
* { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
* [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
* [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
*
*
*
* @param jp
*/
private void parsePolygonMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the RING
int linesIndex = 0;
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
if (linesIndex == 0) {
parseCoordinatesMetadata(jp);
} else {
parseCoordinatesMetadata(jp);
}
jp.nextToken();//END RING
linesIndex++;
}
if (linesIndex > 1) {
jp.nextToken();//END_OBJECT } geometry
} else {
jp.nextToken();//END_OBJECT } geometry
}
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
* Parses a MultiPolygon as an array of Polygon coordinate arrays:
*
* { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0],
* [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0],
* [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2],
* [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }
*
* @param jp
* @throws IOException
* @throws SQLException
*/
private void parseMultiPolygonMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the polygon
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
//Parses the polygon
jp.nextToken(); //Start the RING
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
parseCoordinatesMetadata(jp);
jp.nextToken();//END RING
}
jp.nextToken();//END_OBJECT
}
jp.nextToken();//END_OBJECT } geometry
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
}
/**
* Parses a GeometryCollection the geometry objects are described above:
*
* { "type": "GeometryCollection", "geometries": [ { "type": "Point",
* "coordinates": [100.0, 0.0] }, { "type": "LineString", "coordinates": [
* [101.0, 0.0], [102.0, 1.0] ] } ]
*
* @param jp
*
* @throws IOException
* @throws SQLException
* @return GeometryCollection
*/
private void parseGeometryCollectionMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME geometries
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.GEOMETRIES)) {
jp.nextToken();//START array
jp.nextToken();//START object
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
jp.nextToken(); // FIELD_NAME type
jp.nextToken(); //VALUE_STRING Point
String geometryType = jp.getText();
parseGeometryMetadata(jp, geometryType);
jp.nextToken();
}
jp.nextToken();//END_OBJECT } geometry
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'geometries', found '" + coordinatesField + "'");
}
}
/**
* Parses a GeoJSON coordinate array and check if it's wellformed. The first
* token corresponds to the first X value. The last token correponds to the
* end of the coordinate array "]".
*
* Parsed syntax:
*
* 100.0, 0.0]
*
* @param jp
* @throws IOException
* @return Coordinate
*/
private void parseCoordinateMetadata(JsonParser jp) throws IOException {
jp.nextToken();
jp.nextToken(); // second value
//We look for a z value
jp.nextToken();
if (jp.getCurrentToken() != JsonToken.END_ARRAY) {
jp.nextToken(); // exit array
hasZ=true;
}
jp.nextToken();
}
/**
* Parses a sequence of coordinates array expressed as
*
* [ [100.0, 0.0], [101.0, 1.0] ]
*
* and check if it's wellformated
*
* @param jp
* @throws IOException
* @throws SQLException
* @return Coordinate[]
*/
private void parseCoordinatesMetadata(JsonParser jp) throws IOException {
jp.nextToken(); // START_ARRAY [ to parse the each positions
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
parseCoordinateMetadata(jp);
}
}
/**
* Parses the properties of a feature
*
* Syntax:
*
* "properties": {"prop0": "value0"}
*
* @param jp
*/
private void parsePropertiesMetadata(JsonParser jp) throws IOException, SQLException {
jp.nextToken();//START_OBJECT {
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = TableLocation.capsIdentifier(jp.getText(), dbType); //FIELD_NAME columnName
fieldName = TableLocation.quoteIdentifier(fieldName, dbType);
JsonToken value = jp.nextToken();
if (null != value) {
Integer dataType = cachedColumnNames.get(fieldName);
boolean hasField = cachedColumnNames.containsKey(fieldName);
switch (value) {
case VALUE_STRING:
cachedColumnNames.put(fieldName, Types.VARCHAR);
break;
case VALUE_TRUE:
case VALUE_FALSE:
if (!hasField || dataType == Types.NULL) {
cachedColumnNames.put(fieldName, Types.BOOLEAN);
} else if (hasField && dataType != Types.BOOLEAN) {
cachedColumnNames.put(fieldName, Types.VARCHAR);
}
break;
case VALUE_NUMBER_FLOAT:
if (!hasField || dataType == Types.NULL) {
cachedColumnNames.put(fieldName, Types.DOUBLE);
} else if (hasField) {
if (dataType == Types.BIGINT) {
cachedColumnNames.put(fieldName, Types.DOUBLE);
} else if (dataType != Types.DOUBLE) {
cachedColumnNames.put(fieldName, Types.VARCHAR);
}
}
break;
case VALUE_NUMBER_INT:
if (!hasField || dataType == Types.NULL) {
cachedColumnNames.put(fieldName, Types.BIGINT);
} else if (hasField && dataType != Types.BIGINT && dataType!=Types.DOUBLE) {
cachedColumnNames.put(fieldName, Types.VARCHAR);
}
break;
case START_ARRAY:
if (!hasField || dataType == Types.NULL) {
cachedColumnNames.put(fieldName, Types.ARRAY);
} else if (hasField && dataType != Types.ARRAY) {
cachedColumnNames.put(fieldName, Types.VARCHAR);
}
parseArrayMetadata(jp);
break;
case START_OBJECT:
if (!hasField || dataType == Types.NULL) {
cachedColumnNames.put(fieldName, Types.ARRAY);
}
else if (hasField && dataType != Types.ARRAY) {
cachedColumnNames.put(fieldName, Types.VARCHAR);
}
parseObjectMetadata(jp);
break;
case VALUE_NULL:
if (!hasField) {
cachedColumnNames.put(fieldName, Types.NULL);
}
//ignore other value
default:
break;
}
}
}
}
/**
* Creates the JsonFactory.
*/
private void init() throws SQLException {
jsonEncoding = JsonEncoding.UTF8;
if (encoding != null && !encoding.isEmpty()) {
try {
jsonEncoding = JsonEncoding.valueOf(encoding);
} catch (IllegalArgumentException ex) {
throw new SQLException("Only UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE encoding is supported");
}
}
jsFactory = new JsonFactory();
jsFactory.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
jsFactory.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
jsFactory.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
}
/**
* Features in GeoJSON contain a geometry object and additional properties
* This method returns all values stored in a feature.
*
* Syntax:
*
* { "type": "Feature", "geometry":{"type": "Point", "coordinates": [102.0,
* 0.5]}, "properties": {"prop0": "value0"} }
*
* @param jp
*/
private Object[] parseFeature(JsonParser jp) throws IOException, SQLException {
jp.nextToken();
String field = jp.getText();
//Avoid all token which are not 'properties', 'geometry', 'type'
while (!field.equalsIgnoreCase(GeoJsonField.GEOMETRY)
&& !field.equalsIgnoreCase(GeoJsonField.PROPERTIES)
&& !jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.START_ARRAY) || jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.skipChildren();
}
jp.nextToken();
field = jp.getText();
}
Object[] values = new Object[cachedColumnIndex.size() + 1];
if (field.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
setGeometry(jp, values);
jp.nextToken();
} else if (field.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
parseProperties(jp, values);
jp.nextToken();
}
//If there is only one geometry field in the feature them the next
//token corresponds to the end object of the feature
//Avoid all token which are not 'properties', 'geometry', 'type'
field = jp.getText();
while (!field.equalsIgnoreCase(GeoJsonField.GEOMETRY)
&& !field.equalsIgnoreCase(GeoJsonField.PROPERTIES)
&& !jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.START_ARRAY) || jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.skipChildren();
}
jp.nextToken();
field = jp.getText();
}
if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
String secondParam = jp.getText();// field name
if (secondParam.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
setGeometry(jp, values);
} else if (secondParam.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
parseProperties(jp, values);
}
while (jp.nextToken() != JsonToken.END_OBJECT); //END_OBJECT } feature
}
return values;
}
/**
* Sets the parsed geometry to the table *
*
* @param jp
* @throws IOException
* @throws SQLException
*/
private void setGeometry(JsonParser jp, Object[] values) throws IOException, SQLException {
if (jp.nextToken() != JsonToken.VALUE_NULL) {//START_OBJECT { in case of null geometry
jp.nextToken(); // FIELD_NAME type
jp.nextToken(); //VALUE_STRING Point
String geometryType = jp.getText();
Geometry geom = parseGeometry(jp, geometryType);
values[0] = ValueGeometry.getFromGeometry(geom).getBytesNoCopy();
}
}
/**
* Parses a GeoJSON geometry and returns its JTS representation.
*
* Syntax:
*
* "geometry":{"type": "Point", "coordinates": [102.0,0.5]}
*
* @param jp
* @throws IOException
* @return Geometry
*/
private Geometry parseGeometry(JsonParser jp, String geometryType) throws IOException, SQLException {
if (geometryType.equalsIgnoreCase(GeoJsonField.POINT)) {
return parsePoint(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
return parseMultiPoint(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
return parseLinestring(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
return parseMultiLinestring(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
return parsePolygon(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
return parseMultiPolygon(jp);
} else if (geometryType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
return parseGeometryCollection(jp);
} else {
throw new SQLException("Unsupported geometry : " + geometryType);
}
}
/**
* Parses the properties of a feature
*
* Syntax:
*
* "properties": {"prop0": "value0"}
*
* @param jp
*/
private void parseProperties(JsonParser jp, Object[] values) throws IOException, SQLException {
jp.nextToken();//START_OBJECT {
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = TableLocation.capsIdentifier(jp.getText(), dbType); //FIELD_NAME columnName
fieldName = TableLocation.quoteIdentifier(fieldName, dbType);
JsonToken value = jp.nextToken();
if (null == value) {
//ignore other value
} else switch (value) {
case VALUE_STRING:
values[cachedColumnIndex.get(fieldName)] = jp.getText();
break;
case VALUE_TRUE:
values[cachedColumnIndex.get(fieldName)] = jp.getValueAsBoolean();
break;
case VALUE_FALSE:
values[cachedColumnIndex.get(fieldName)] = jp.getValueAsBoolean();
break;
case VALUE_NUMBER_FLOAT:
values[cachedColumnIndex.get(fieldName)] = jp.getValueAsDouble();
break;
case VALUE_NUMBER_INT:
if(jp.getNumberType() == JsonParser.NumberType.INT) {
values[cachedColumnIndex.get(fieldName)] = jp.getIntValue();
} else {
values[cachedColumnIndex.get(fieldName)] = jp.getLongValue();
} break;
case START_ARRAY:
{
StringBuilder sb = new StringBuilder();
parseArray(jp, sb);
values[cachedColumnIndex.get(fieldName)] = sb.toString();
break;
}
case START_OBJECT:
{
StringBuilder sb = new StringBuilder();
parseObject(jp, sb);
values[cachedColumnIndex.get(fieldName)] = sb.toString();
break;
}
case VALUE_NULL:
values[cachedColumnIndex.get(fieldName)] = null;
break;
default:
break;
}
}
}