Skip to content

Commit

Permalink
support geopackage urls in geo file reader
Browse files Browse the repository at this point in the history
  • Loading branch information
rakow committed Jan 6, 2025
1 parent 206f16d commit 533e5e8
Showing 1 changed file with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

package org.matsim.core.utils.gis;

import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.geotools.api.data.*;
Expand All @@ -38,7 +39,11 @@
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
Expand Down Expand Up @@ -98,12 +103,48 @@ public static Collection<SimpleFeature> getAllFeatures(final String filename, Na
public static Collection<SimpleFeature> getAllFeatures(final URL url) {
try {
log.info( "will try to read from " + url.getPath() ) ;
if (url.getFile().endsWith(".gpkg")) {
return getAllFeaturesGPKG(url);
}
return getSimpleFeatures(FileDataStoreFinder.getDataStore(url));
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}

/**
* Loads geo package like normal shape files using the first layer found in the file.
*/
private static Collection<SimpleFeature> getAllFeaturesGPKG(final URL url) throws URISyntaxException, IOException {

File file;
// Remote files have to be downloaded
if (url.getProtocol().startsWith("http")) {

String name = FilenameUtils.getBaseName(url.getFile());

Path tmp = Files.createTempFile(name, ".gpkg");
Files.copy(url.openStream(), tmp, StandardCopyOption.REPLACE_EXISTING);

file = tmp.toFile();
file.deleteOnExit();
} else
file = new File(url.toURI());

Map<String, Object> params = new HashMap<>();
params.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
params.put(GeoPkgDataStoreFactory.DATABASE.key, file.toString());
params.put(GeoPkgDataStoreFactory.READ_ONLY.key, true);
DataStore dataStore = DataStoreFinder.getDataStore(params);

String[] typeNames = dataStore.getTypeNames();

// Use first layer
return getSimpleFeatures(dataStore, typeNames[0]);
}

/**
* Read all simple features from a data store. This method makes sure the store is closed afterwards.
* @return list of contained features.
Expand Down Expand Up @@ -194,7 +235,7 @@ public static SimpleFeatureSource readDataFile(final String filename) {
* <p></p>
* Then, get the features by
* <p></p>
* <pre> Set<{@link Feature}> features = geoFileReader.getFeatureSet(); </pre>
* <pre> Set<{@link org.geotools.api.feature.Feature}> features = geoFileReader.getFeatureSet(); </pre>
* <p></p>
* If you need metadata you can use
* <p></p>
Expand Down

0 comments on commit 533e5e8

Please sign in to comment.