use of org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb in project hortonmachine by TheHortonMachine.
the class GeopaparazziSpatialiteCreator method process.
// VARS DOCS END
@Execute
public void process() throws Exception {
checkNull(inGeopaparazzi, inShapefilesFolder);
if (pEncoding == null || pEncoding.trim().length() == 0) {
pEncoding = "UTF-8";
}
if (pSizeFactor < 1) {
pSizeFactor = 3;
}
if (pLinesWidthFactor < 1) {
pLinesWidthFactor = 6;
}
File shpFolder = new File(inShapefilesFolder);
File[] shpfiles = shpFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".shp");
}
});
if (shpfiles.length == 0) {
throw new ModelsIOException("The supplied folder doesn't contain any shapefile.", this);
}
try (ASpatialDb db = new GTSpatialiteThreadsafeDb()) {
if (!db.open(inGeopaparazzi)) {
db.initSpatialMetadata(null);
}
if (!db.hasTable(SqlName.m(GeopaparazziDatabaseProperties.PROPERTIESTABLE))) {
GeopaparazziDatabaseProperties.createPropertiesTable(db);
} else {
QueryResult qres1 = db.getTableRecordsMapFromRawSql("select * from dataproperties", 10);
pm.message("Dataproperties already existing: ");
for (Object[] objs : qres1.data) {
pm.message(Arrays.toString(objs));
}
pm.message("----------------------------------");
}
pm.beginTask("Importing shapefiles...", shpfiles.length);
for (File shpFile : shpfiles) {
SqlName name = SqlName.m(FileUtilities.getNameWithoutExtention(shpFile));
if (db.hasTable(name)) {
pm.errorMessage("Table already existing: " + name);
continue;
}
SimpleFeatureCollection fc = OmsVectorReader.readVector(shpFile.getAbsolutePath());
SimpleFeatureType schema = fc.getSchema();
CoordinateReferenceSystem crs = schema.getCoordinateReferenceSystem();
String epsgStr = CrsUtilities.getCodeFromCrs(crs);
String sirdStr = epsgStr.substring(5);
int srid = Integer.parseInt(sirdStr);
EGeometryType geomType = EGeometryType.forGeometryDescriptor(schema.getGeometryDescriptor());
ESpatialiteGeometryType spatialiteGeometryType = geomType.toSpatialiteGeometryType();
HMImportExportUtils.importShapefileThroughVirtualTable(db, name, shpFile.getAbsolutePath(), pEncoding, srid, spatialiteGeometryType);
Style style = SldUtilities.getStyleFromFile(shpFile);
if (style != null) {
String uniqueName = "/#" + name + "#geometry";
StyleWrapper styleWrapper = new StyleWrapper(style);
List<FeatureTypeStyleWrapper> featureTypeStylesWrapperList = styleWrapper.getFeatureTypeStylesWrapperList();
if (featureTypeStylesWrapperList.size() > 0) {
List<RuleWrapper> rulesWrapperList = new ArrayList<>();
for (FeatureTypeStyleWrapper ftsWrapper : featureTypeStylesWrapperList) {
List<RuleWrapper> rulesWrappers = ftsWrapper.getRulesWrapperList();
rulesWrapperList.addAll(rulesWrappers);
}
if (rulesWrapperList.size() == 1) {
RuleWrapper ruleWrapper = rulesWrapperList.get(0);
SymbolizerWrapper geometrySymbolizersWrapper = ruleWrapper.getGeometrySymbolizersWrapper();
if (geometrySymbolizersWrapper != null) {
org.hortonmachine.dbs.utils.BasicStyle gpStyle = createBaseStyle(db, uniqueName, rulesWrapperList);
populateStyleObject(gpStyle, geometrySymbolizersWrapper);
GeopaparazziDatabaseProperties.updateStyle(db, gpStyle);
}
} else if (rulesWrapperList.size() > 1) {
org.hortonmachine.dbs.utils.BasicStyle gpStyle = createBaseStyle(db, uniqueName, rulesWrapperList);
gpStyle.themeMap = new HashMap<>();
for (RuleWrapper ruleWrapper : rulesWrapperList) {
SymbolizerWrapper geometrySymbolizersWrapper = ruleWrapper.getGeometrySymbolizersWrapper();
org.hortonmachine.dbs.utils.BasicStyle themeStyle = createBaseStyle(null, uniqueName, rulesWrapperList);
populateStyleObject(themeStyle, geometrySymbolizersWrapper);
Filter filter = ruleWrapper.getRule().getFilter();
if (filter instanceof IsEqualsToImpl) {
IsEqualsToImpl equalsFilter = (IsEqualsToImpl) filter;
Expression expression1 = equalsFilter.getExpression1();
Expression expression2 = equalsFilter.getExpression2();
setFilter(gpStyle, themeStyle, expression1);
setFilter(gpStyle, themeStyle, expression2);
}
}
GeopaparazziDatabaseProperties.updateStyle(db, gpStyle);
} else {
pm.errorMessage("Unable to export SLD for: " + shpFile);
continue;
}
}
}
pm.worked(1);
}
pm.done();
QueryResult qres = db.getTableRecordsMapFromRawSql("select * from dataproperties", 100);
pm.message("Dataproperties inserted: ");
int theme = qres.names.indexOf(org.hortonmachine.dbs.utils.BasicStyle.THEME);
for (Object[] objs : qres.data) {
String themeString = objs[theme].toString().replaceAll("\\s+", " ");
if (themeString.length() > 20) {
objs[theme] = themeString.substring(0, 15) + "...";
}
pm.message(Arrays.toString(objs));
}
}
}
use of org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb in project hortonmachine by TheHortonMachine.
the class DatabaseController method openDatabase.
protected void openDatabase(EDb dbType, String dbfilePath, String user, String pwd) {
if (dbfilePath == null && dbType == null) {
return;
}
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error closing the database...", e1);
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
logConsole.beginProcess("Open database");
boolean hadError = false;
try {
DbLevel dbLevel = null;
String dbPath;
if (!dbType.isNosql()) {
if (dbType == EDb.SPATIALITE) {
if (SpatialiteCommonMethods.isSqliteFile(new File(dbfilePath))) {
currentConnectedSqlDatabase = new GTSpatialiteThreadsafeDb();
} else {
guiBridge.messageDialog("The selected file is not a Spatialite database.", "WARNING", JOptionPane.WARNING_MESSAGE);
return;
}
} else {
currentConnectedSqlDatabase = dbType.getSpatialDb();
}
currentConnectedSqlDatabase.setCredentials(user, pwd);
try {
currentConnectedSqlDatabase.open(dbfilePath);
} catch (JdbcSQLException e) {
String message = e.getMessage();
if (message.contains("Wrong user name or password")) {
guiBridge.messageDialog("Wrong user name or password.", "ERROR", JOptionPane.ERROR_MESSAGE);
currentConnectedSqlDatabase = null;
return;
}
if (message.contains("Database may be already in use")) {
guiBridge.messageDialog("Database may be already in use. Close all connections or use server mode.", "ERROR", JOptionPane.ERROR_MESSAGE);
currentConnectedSqlDatabase = null;
return;
}
} catch (Exception e) {
Logger.INSTANCE.insertError("", "ERROR", e);
hadError = true;
}
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedSqlDatabase.getType());
dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
dbPath = currentConnectedSqlDatabase.getDatabasePath();
} else {
currentConnectedNosqlDatabase = dbType.getNosqlDb();
currentConnectedNosqlDatabase.setCredentials(user, pwd);
currentConnectedNosqlDatabase.open(dbfilePath);
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedNosqlDatabase.getType());
dbPath = currentConnectedNosqlDatabase.getDbEngineUrl();
dbLevel = gatherDatabaseLevels(currentConnectedNosqlDatabase);
}
setRightTreeRenderer();
layoutTree(dbLevel, true);
setDbTreeTitle(dbPath);
} catch (Exception e) {
currentConnectedSqlDatabase = null;
currentConnectedNosqlDatabase = null;
Logger.INSTANCE.insertError("", "Error connecting to the database...", e);
hadError = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadError) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->open database").start();
}
use of org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb in project hortonmachine by TheHortonMachine.
the class DatabaseController method createNewDatabase.
protected void createNewDatabase(EDb dbType, String dbfilePath, String user, String pwd) {
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error closing the database...", e1);
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
logConsole.beginProcess("Create new database");
boolean hadError = false;
try {
if (dbType == EDb.SPATIALITE) {
currentConnectedSqlDatabase = new GTSpatialiteThreadsafeDb();
} else {
currentConnectedSqlDatabase = dbType.getSpatialDb();
}
currentConnectedSqlDatabase.setCredentials(user, pwd);
currentConnectedSqlDatabase.open(dbfilePath);
if (currentConnectedSqlDatabase instanceof ASpatialDb) {
((ASpatialDb) currentConnectedSqlDatabase).initSpatialMetadata(null);
}
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedSqlDatabase.getType());
setRightTreeRenderer();
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
layoutTree(dbLevel, false);
} catch (Exception e) {
currentConnectedSqlDatabase = null;
Logger.INSTANCE.insertError("", "Error connecting to the database...", e);
hadError = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadError) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->create new database").start();
}
use of org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb in project hortonmachine by TheHortonMachine.
the class ToolsPanelController method loadFile.
private void loadFile(File selectedFile) {
String name = FileUtilities.getNameWithoutExtention(selectedFile);
try {
if (selectedFile.getName().endsWith(".asc") || selectedFile.getName().endsWith(".tiff")) {
GridCoverageNwwLayer coverageNwwLayer = new GridCoverageNwwLayer(selectedFile, null, Color.WHITE);
wwjPanel.getWwd().getModel().getLayers().add(coverageNwwLayer);
layerEventsListener.onLayerAdded(coverageNwwLayer);
} else if (selectedFile.getName().endsWith(".shp")) {
// shp or image mosaic?
File parentFolder = selectedFile.getParentFile();
String fileName = FileUtilities.getNameWithoutExtention(selectedFile);
File imageMosaicPropertiesFile = new File(parentFolder, fileName + ".properties");
try {
if (imageMosaicPropertiesFile.exists()) {
final ParameterValue<Color> inTransp = AbstractGridFormat.INPUT_TRANSPARENT_COLOR.createValue();
inTransp.setValue(Color.white);
final ParameterValue<Boolean> fading = ImageMosaicFormat.FADING.createValue();
fading.setValue(true);
final ParameterValue<Boolean> multiThread = ImageMosaicFormat.ALLOW_MULTITHREADING.createValue();
multiThread.setValue(true);
final ParameterValue<Boolean> usejai = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue();
usejai.setValue(true);
GeneralParameterValue[] gp = new GeneralParameterValue[] { inTransp, usejai, multiThread };
ImageMosaicNwwLayer imageMosaicNwwLayer = new ImageMosaicNwwLayer(selectedFile, null, gp, true);
wwjPanel.getWwd().getModel().getLayers().add(imageMosaicNwwLayer);
layerEventsListener.onLayerAdded(imageMosaicNwwLayer);
return;
}
} catch (Exception e) {
e.printStackTrace();
// ignore and handle as shapefile
}
HashMap<String, String[]> field2ValuesMap = null;
File codesFile = new File(selectedFile.getParentFile(), fileName + ".codes");
if (codesFile.exists()) {
List<String> linesList = FileUtilities.readFileToLinesList(codesFile);
field2ValuesMap = new HashMap<>();
for (String line : linesList) {
String[] split = line.split("=");
String key = split[0];
String[] values = split[1].split(";");
field2ValuesMap.put(key, values);
}
}
SimpleFeatureSource featureSource = NwwUtilities.readFeatureSource(selectedFile.getAbsolutePath());
SimpleFeatureStore featureStore = null;
if (featureSource instanceof SimpleFeatureStore) {
featureStore = (SimpleFeatureStore) featureSource;
}
SimpleFeatureCollection readFC = NwwUtilities.readAndReproject(featureSource);
loadFeatureCollection(selectedFile, name, featureStore, readFC, field2ValuesMap);
} else if (selectedFile.getName().endsWith(".mbtiles")) {
MBTilesNwwLayer mbTileLayer = new MBTilesNwwLayer(selectedFile);
wwjPanel.getWwd().getModel().getLayers().add(mbTileLayer);
layerEventsListener.onLayerAdded(mbTileLayer);
} else if (selectedFile.getName().endsWith(".gpkg")) {
List<String> tilesTables = new ArrayList<>();
List<String> featureTables = new ArrayList<>();
try (GeopackageCommonDb db = new GeopackageDb()) {
db.open(selectedFile.getAbsolutePath());
List<TileEntry> tiles = db.tiles();
for (TileEntry tileEntry : tiles) {
tilesTables.add(tileEntry.getTableName());
}
List<FeatureEntry> features = db.features();
for (FeatureEntry featureEntry : features) {
featureTables.add(featureEntry.getTableName());
}
}
for (String tableName : tilesTables) {
GeopackageTilesNwwLayer gpkgTilesLayer = new GeopackageTilesNwwLayer(selectedFile, tableName);
wwjPanel.getWwd().getModel().getLayers().add(gpkgTilesLayer);
layerEventsListener.onLayerAdded(gpkgTilesLayer);
}
if (_useRasterizedCheckbox.isSelected()) {
for (String tableName : featureTables) {
SimpleFeatureCollection readFC = OmsVectorReader.readVector(selectedFile.getAbsolutePath() + HMConstants.DB_TABLE_PATH_SEPARATOR + tableName);
String sldString = null;
try (GeopackageCommonDb db = new GeopackageDb()) {
db.open(selectedFile.getAbsolutePath());
sldString = db.getSldString(SqlName.m(tableName));
}
Style style;
if (sldString != null) {
style = SldUtilities.getStyleFromSldString(sldString);
} else {
style = SLD.createSimpleStyle(readFC.getSchema(), Color.BLUE);
}
String n = selectedFile.getName() + HMConstants.DB_TABLE_PATH_SEPARATOR + tableName;
RasterizedFeatureCollectionLayer collectionLayer = new RasterizedFeatureCollectionLayer(n, readFC, style, null, true);
wwjPanel.getWwd().getModel().getLayers().add(collectionLayer);
layerEventsListener.onLayerAdded(collectionLayer);
}
} else {
for (String tableName : featureTables) {
GeopackageVectorLayer gpkgVectorLayer = new GeopackageVectorLayer(selectedFile.getAbsolutePath(), tableName);
wwjPanel.getWwd().getModel().getLayers().add(gpkgVectorLayer);
layerEventsListener.onLayerAdded(gpkgVectorLayer);
}
}
} else if (selectedFile.getName().endsWith(".map")) {
String layerName = FileUtilities.getNameWithoutExtention(selectedFile);
MapsforgeNwwLayer mbTileLayer = new MapsforgeNwwLayer(layerName, new File[] { selectedFile }, null, null);
wwjPanel.getWwd().getModel().getLayers().add(mbTileLayer);
layerEventsListener.onLayerAdded(mbTileLayer);
} else if (selectedFile.getName().endsWith(".rl2")) {
GTSpatialiteThreadsafeDb db = new GTSpatialiteThreadsafeDb();
db.open(selectedFile.getAbsolutePath());
Rasterlite2Db rldb = new Rasterlite2Db(db);
List<Rasterlite2Coverage> rasterCoverages = rldb.getRasterCoverages(false);
if (rasterCoverages.size() > 0) {
Rasterlite2Coverage rasterCoverage = rasterCoverages.get(0);
RL2NwwLayer rl2Layer = new RL2NwwLayer(rasterCoverage, null);
wwjPanel.getWwd().getModel().getLayers().add(rl2Layer);
layerEventsListener.onLayerAdded(rl2Layer);
}
} else if (selectedFile.getName().endsWith(".sqlite")) {
ASpatialDb db = new GTSpatialiteThreadsafeDb();
db.open(selectedFile.getAbsolutePath());
if (RasterizedSpatialiteLasLayer.isLasDb(db)) {
String[] options = { "elevation", "intensity" };
String option = (String) JOptionPane.showInputDialog(this, "Select data to view", "Data selection", JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
boolean doIntensity = false;
if (option.equals(options[1])) {
doIntensity = true;
}
RasterizedSpatialiteLasLayer rasterizedSpatialiteLayer = new RasterizedSpatialiteLasLayer(name, db, null, true, doIntensity);
wwjPanel.getWwd().getModel().getLayers().add(rasterizedSpatialiteLayer);
layerEventsListener.onLayerAdded(rasterizedSpatialiteLayer);
} else {
List<String> tableMaps = db.getTables(false);
String[] tables = tableMaps.toArray(new String[0]);
String tableName = (String) JOptionPane.showInputDialog(this, "Select the table to load", "Table selection", JOptionPane.QUESTION_MESSAGE, null, tables, tables[0]);
if (_useRasterizedCheckbox.isSelected()) {
RasterizedSpatialiteLayer rasterizedSpatialiteLayer = new RasterizedSpatialiteLayer(name, db, tableName, -1, null, null, true);
wwjPanel.getWwd().getModel().getLayers().add(rasterizedSpatialiteLayer);
layerEventsListener.onLayerAdded(rasterizedSpatialiteLayer);
} else {
GeometryColumn geometryColumn = db.getGeometryColumnsForTable(SqlName.m(tableName));
if (geometryColumn != null) {
org.hortonmachine.dbs.datatypes.EGeometryType geomType = geometryColumn.geometryType;
if (geomType.isPolygon()) {
SpatialitePolygonLayer layer = new SpatialitePolygonLayer(db, tableName, 10000);
wwjPanel.getWwd().getModel().getLayers().add(layer);
layerEventsListener.onLayerAdded(layer);
} else if (geomType.isLine()) {
SpatialiteLinesLayer layer = new SpatialiteLinesLayer(db, tableName, 10000);
wwjPanel.getWwd().getModel().getLayers().add(layer);
layerEventsListener.onLayerAdded(layer);
} else if (geomType.isPoint()) {
SpatialitePointsLayer layer = new SpatialitePointsLayer(db, tableName, 10000);
wwjPanel.getWwd().getModel().getLayers().add(layer);
layerEventsListener.onLayerAdded(layer);
}
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
Aggregations