Search in sources :

Example 1 with GuiBridgeHandler

use of org.hortonmachine.gui.utils.GuiBridgeHandler in project hortonmachine by TheHortonMachine.

the class SqlTemplatesAndActions method doTiles.

private static void doTiles(GuiBridgeHandler guiBridge, DatabaseViewer databaseViewer, boolean isRaster) {
    try {
        String label = isRaster ? "raster" : "vector";
        FileFilter fileFilter = isRaster ? HMConstants.rasterFileFilter : HMConstants.vectorFileFilter;
        String title = "Open " + label + " file";
        File[] openFiles = GuiUtilities.showOpenFilesDialog(databaseViewer, title, true, PreferencesHandler.getLastFile(), fileFilter);
        if (openFiles != null && openFiles.length > 0) {
            try {
                PreferencesHandler.setLastPath(openFiles[0].getAbsolutePath());
            } catch (Exception e1) {
                logger.insertError("SqlTemplatesAndActions", "ERROR", e1);
            }
        } else {
            return;
        }
        try {
            String targetEpsg = "epsg:" + GeopackageCommonDb.MERCATOR_SRID;
            CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(targetEpsg, null);
            GeopackageCommonDb db = (GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase;
            List<FeatureEntry> features4326 = db.features();
            PreparedGeometry limitsGeom3857 = null;
            if (features4326.size() > 0) {
                List<String> names = features4326.stream().map(f -> f.getTableName()).collect(Collectors.toList());
                String selectedTable = GuiUtilities.showComboDialog(databaseViewer, "Area of interest", "It is possible to use one of the vector tables as area of interest. Tiles outside the area will be ignored.", names.toArray(new String[0]), "");
                if (selectedTable != null) {
                    SqlName tName = SqlName.m(selectedTable);
                    GeometryColumn gc = db.getGeometryColumnsForTable(tName);
                    List<Geometry> geometries = db.getGeometriesIn(tName, (Envelope) null, (String[]) null);
                    int dataSrid = db.feature(tName).getSrid();
                    List<Geometry> geometries3857;
                    if (dataSrid == GeopackageCommonDb.MERCATOR_SRID) {
                        geometries3857 = geometries;
                    } else {
                        String sourceEpsg = "epsg:" + dataSrid;
                        CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromEpsg(sourceEpsg, null);
                        ;
                        MathTransform transform = CRS.findMathTransform(sourceCRS, mercatorCrs);
                        geometries3857 = geometries.stream().map(g -> {
                            try {
                                return JTS.transform(g, transform);
                            } catch (Exception e) {
                                e.printStackTrace();
                                return null;
                            }
                        }).collect(Collectors.toList());
                    }
                    if (gc.geometryType.isPolygon()) {
                        // use polygons
                        Geometry union = CascadedPolygonUnion.union(geometries3857);
                        limitsGeom3857 = PreparedGeometryFactory.prepare(union);
                    } else {
                        // use envelopes
                        Envelope env = new Envelope();
                        for (Geometry geometry : geometries3857) {
                            env.expandToInclude(geometry.getEnvelopeInternal());
                        }
                        Polygon polyEnv = GeometryUtilities.createPolygonFromEnvelope(env);
                        limitsGeom3857 = PreparedGeometryFactory.prepare(polyEnv);
                    }
                }
            }
            String nameForTable = FileUtilities.getNameWithoutExtention(openFiles[0]);
            String[] zoomLevels = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" };
            HashMap<String, String[]> fields2ValuesMap = new HashMap<>();
            String newTableLabel = "name of the new table";
            String minZoomLevelLabel = "min zoom level";
            String maxZoomLevelLabel = "max zoom level";
            fields2ValuesMap.put(minZoomLevelLabel, zoomLevels);
            fields2ValuesMap.put(maxZoomLevelLabel, zoomLevels);
            String[] result = // 
            GuiUtilities.showMultiInputDialog(// 
            databaseViewer, // 
            "Select parameters", // 
            new String[] { newTableLabel, minZoomLevelLabel, maxZoomLevelLabel }, // 
            new String[] { nameForTable, "8", "16" }, null);
            if (result == null) {
                return;
            }
            PreparedGeometry _limitsGeom3857 = limitsGeom3857;
            final LogConsoleController logConsole = new LogConsoleController(null);
            IHMProgressMonitor pm = logConsole.getProgressMonitor();
            Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
            Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
            guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
            new Thread(() -> {
                try {
                    logConsole.beginProcess("Import " + label + " to tileset");
                    pm.message("Checking input parameters...");
                    String _nameForTable = result[0];
                    int minZoom = 8;
                    int maxZoom = 16;
                    try {
                        minZoom = Integer.parseInt(result[1]);
                        maxZoom = Integer.parseInt(result[2]);
                    } catch (Exception e1) {
                        pm.errorMessage("The min or max zoomlevel were not entered correctly, exiting.");
                        return;
                    }
                    for (File file : openFiles) {
                        String dataPath = file.getAbsolutePath();
                        Envelope envelopeInternal = null;
                        if (isRaster) {
                            AbstractGridFormat format = GridFormatFinder.findFormat(file);
                            AbstractGridCoverage2DReader reader = format.getReader(file, null);
                            GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
                            CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
                            double[] ll = originalEnvelope.getLowerCorner().getCoordinate();
                            double[] ur = originalEnvelope.getUpperCorner().getCoordinate();
                            ReferencedEnvelope renv = new ReferencedEnvelope(ll[0], ur[0], ll[1], ur[1], crs);
                            envelopeInternal = renv.transform(mercatorCrs, true);
                        } else {
                            ReferencedEnvelope renv = OmsVectorReader.readEnvelope(file.getAbsolutePath());
                            envelopeInternal = renv.transform(mercatorCrs, true);
                        }
                        ITilesProducer tileProducer = new GeopackageTilesProducer(pm, dataPath, isRaster, minZoom, maxZoom, 256, _limitsGeom3857);
                        String description = "HM import of " + openFiles[0].getName();
                        int addedTiles = ((GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase).addTilestable(SqlName.m(_nameForTable), description, envelopeInternal, tileProducer);
                        pm.message("Inserted " + addedTiles + " new tiles.");
                    }
                    databaseViewer.refreshDatabaseTree();
                } catch (Exception ex) {
                    pm.errorMessage(ex.getLocalizedMessage());
                } finally {
                    logConsole.finishProcess();
                    logConsole.stopLogging();
                    Logger.INSTANCE.resetStreams();
                }
            }, "DatabaseController->Import " + label + " to tileset").start();
        } catch (Exception e1) {
            GuiUtilities.handleError(databaseViewer, e1);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) Logger(org.hortonmachine.dbs.log.Logger) CRS(org.geotools.referencing.CRS) ObjectOutput(java.io.ObjectOutput) SpatialDbsImportUtils(org.hortonmachine.gears.spatialite.SpatialDbsImportUtils) MainController(org.hortonmachine.style.MainController) ObjectInputStream(java.io.ObjectInputStream) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) ByteArrayInputStream(java.io.ByteArrayInputStream) PreferencesHandler(org.hortonmachine.gears.utils.PreferencesHandler) IHmExtrasDb(org.hortonmachine.dbs.compat.IHmExtrasDb) HMConstants(org.hortonmachine.gears.libs.modules.HMConstants) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) QueryResult(org.hortonmachine.dbs.compat.objects.QueryResult) JTS(org.geotools.geometry.jts.JTS) ConnectionData(org.hortonmachine.dbs.compat.ConnectionData) JFrame(javax.swing.JFrame) TableLevel(org.hortonmachine.dbs.compat.objects.TableLevel) EDataType(org.hortonmachine.dbs.datatypes.EDataType) Collectors(java.util.stream.Collectors) GeopackageCommonDb(org.hortonmachine.dbs.geopackage.GeopackageCommonDb) List(java.util.List) AbstractAction(javax.swing.AbstractAction) DbsUtilities(org.hortonmachine.dbs.utils.DbsUtilities) ITilesProducer(org.hortonmachine.dbs.utils.ITilesProducer) CrsUtilities(org.hortonmachine.gears.utils.CrsUtilities) Polygon(org.locationtech.jts.geom.Polygon) Geometry(org.locationtech.jts.geom.Geometry) ObjectInput(java.io.ObjectInput) FeatureEntry(org.hortonmachine.dbs.geopackage.FeatureEntry) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) CascadedPolygonUnion(org.locationtech.jts.operation.union.CascadedPolygonUnion) DbFormHandler(org.hortonmachine.gforms.DbFormHandler) GuiUtilities(org.hortonmachine.gui.utils.GuiUtilities) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ASpatialDb(org.hortonmachine.dbs.compat.ASpatialDb) AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) HashMap(java.util.HashMap) Action(javax.swing.Action) ArrayList(java.util.ArrayList) SqlName(org.hortonmachine.dbs.utils.SqlName) ASqlTemplates(org.hortonmachine.dbs.compat.ASqlTemplates) ImageIcon(javax.swing.ImageIcon) GeometryUtilities(org.hortonmachine.gears.utils.geometry.GeometryUtilities) ObjectOutputStream(java.io.ObjectOutputStream) GuiBridgeHandler(org.hortonmachine.gui.utils.GuiBridgeHandler) Iterator(java.util.Iterator) INosqlCollection(org.hortonmachine.dbs.nosql.INosqlCollection) PGDb(org.hortonmachine.dbs.postgis.PGDb) FileUtilities(org.hortonmachine.gears.utils.files.FileUtilities) FormBuilderController(org.hortonmachine.gforms.FormBuilderController) INosqlDb(org.hortonmachine.dbs.nosql.INosqlDb) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) JOptionPane(javax.swing.JOptionPane) FileFilter(javax.swing.filechooser.FileFilter) OmsVectorReader(org.hortonmachine.gears.io.vectorreader.OmsVectorReader) ActionEvent(java.awt.event.ActionEvent) File(java.io.File) LogConsoleController(org.hortonmachine.gui.console.LogConsoleController) ColumnLevel(org.hortonmachine.dbs.compat.objects.ColumnLevel) EDb(org.hortonmachine.dbs.compat.EDb) GeometryColumn(org.hortonmachine.dbs.compat.GeometryColumn) MathTransform(org.opengis.referencing.operation.MathTransform) ADb(org.hortonmachine.dbs.compat.ADb) IFormHandler(org.hortonmachine.gforms.IFormHandler) DefaultGuiBridgeImpl(org.hortonmachine.gui.utils.DefaultGuiBridgeImpl) GridFormatFinder(org.geotools.coverage.grid.io.GridFormatFinder) Envelope(org.locationtech.jts.geom.Envelope) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) MathTransform(org.opengis.referencing.operation.MathTransform) HashMap(java.util.HashMap) LogConsoleController(org.hortonmachine.gui.console.LogConsoleController) AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) GeopackageCommonDb(org.hortonmachine.dbs.geopackage.GeopackageCommonDb) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) FeatureEntry(org.hortonmachine.dbs.geopackage.FeatureEntry) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) SqlName(org.hortonmachine.dbs.utils.SqlName) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) GeometryColumn(org.hortonmachine.dbs.compat.GeometryColumn) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) FileFilter(javax.swing.filechooser.FileFilter) Polygon(org.locationtech.jts.geom.Polygon) IOException(java.io.IOException) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) ITilesProducer(org.hortonmachine.dbs.utils.ITilesProducer) File(java.io.File)

Aggregations

ActionEvent (java.awt.event.ActionEvent)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 ObjectInput (java.io.ObjectInput)1 ObjectInputStream (java.io.ObjectInputStream)1 ObjectOutput (java.io.ObjectOutput)1 ObjectOutputStream (java.io.ObjectOutputStream)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 AbstractAction (javax.swing.AbstractAction)1 Action (javax.swing.Action)1 ImageIcon (javax.swing.ImageIcon)1 JFrame (javax.swing.JFrame)1 JOptionPane (javax.swing.JOptionPane)1 FileFilter (javax.swing.filechooser.FileFilter)1