try {
Class geometryClass = JTSUtilities.findBestGeometryClass(shpReader.getHeader().getShapeType());
Integer geometryType = SpatialDatabaseService.convertJtsClassToGeometryType(geometryClass);
// TODO ask charset to user?
DbaseFileReader dbfReader = new DbaseFileReader(shpFiles, shpMemoryMapped, charset);
try {
DbaseFileHeader dbaseFileHeader = dbfReader.getHeader();
String[] fieldsName = new String[dbaseFileHeader.getNumFields()+1];
fieldsName[0] = "ID";
for (int i = 1; i < fieldsName.length; i++) {
fieldsName[i] = dbaseFileHeader.getFieldName(i-1);
}
Transaction tx = database.beginTx();
try {
if (crs != null) {
layer.setCoordinateReferenceSystem(crs);
}
if (geometryType != null) {
layer.setGeometryType(geometryType);
}
layer.mergeExtraPropertyNames(fieldsName);
tx.success();
} finally {
tx.close();
}
monitor.begin(dbaseFileHeader.getNumRecords());
try {
Record record;
Geometry geometry;
Object[] values;
ArrayList<Object> fields = new ArrayList<Object>();
int recordCounter = 0;
int filterCounter = 0;
while (shpReader.hasNext() && dbfReader.hasNext()) {
tx = database.beginTx();
try {
int committedSinceLastNotification = 0;
for (int i = 0; i < commitInterval; i++) {
if (shpReader.hasNext() && dbfReader.hasNext()) {
record = shpReader.nextRecord();
recordCounter++;
committedSinceLastNotification++;
try {
fields.clear();
geometry = (Geometry) record.shape();
if (filterEnvelope == null || filterEnvelope.intersects(geometry.getEnvelopeInternal())) {
values = dbfReader.readEntry();
fields.add(recordCounter);
Collections.addAll(fields, values);
if (geometry.isEmpty()) {
log("warn | found empty geometry in record " + recordCounter);
} else {
// TODO check geometry.isValid()
// ?
layer.add(geometry, fieldsName, fields.toArray(values));
}
} else {
filterCounter ++;
}
} catch (IllegalArgumentException e) {
// org.geotools.data.shapefile.shp.ShapefileReader.Record.shape() can throw this exception
log("warn | found invalid geometry: index=" + recordCounter, e);
}
}
}
monitor.worked(committedSinceLastNotification);
tx.success();
log("info | inserted geometries: " + (recordCounter-filterCounter));
if (filterCounter > 0) {
log("info | ignored " + filterCounter + "/" + recordCounter
+ " geometries outside filter envelope: " + filterEnvelope);
}
} finally {
tx.close();
}
}
} finally {
monitor.done();
}
} finally {
dbfReader.close();
}
} finally {
shpReader.close();
}