Search in sources :

Example 1 with Execute

use of oms3.annotations.Execute in project hortonmachine by TheHortonMachine.

the class OmsZonalStatsIM method process.

@Execute
public void process() throws Exception {
    checkNull(inVector);
    addSource(new File(inRaster));
    boolean hasUserTotalMean = false;
    if (pTotalMean != null) {
        hasUserTotalMean = true;
        tm_usertm_tactivecells[1] = pTotalMean;
    }
    ReferencedEnvelope bounds = inVector.getBounds();
    double[] xBins = NumericsUtilities.range2Bins(bounds.getMinX(), bounds.getMaxX(), pBinSize, false);
    double[] yBins = NumericsUtilities.range2Bins(bounds.getMinY(), bounds.getMaxY(), pBinSize, false);
    SimpleFeatureBuilder featureBuilder = OmsZonalStats.createFeatureBuilder(bounds.getCoordinateReferenceSystem(), hasUserTotalMean);
    outVector = new DefaultFeatureCollection();
    List<Geometry> geometriesList = FeatureUtilities.featureCollectionToGeometriesList(inVector, true, null);
    ConcurrentLinkedQueue<Geometry> allGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
    allGeometriesQueue.addAll(geometriesList);
    ConcurrentLinkedQueue<Geometry> keepGeometriesQueue;
    ConcurrentLinkedQueue<Geometry> removeGeometriesQueue;
    pm.beginTask("Processing polygons...", xBins.length - 1);
    for (int x = 0; x < xBins.length - 1; x++) {
        for (int y = 0; y < yBins.length - 1; y++) {
            Envelope envelope = new Envelope(xBins[x], xBins[x + 1], yBins[y], yBins[y + 1]);
            Envelope readEnvelope = null;
            keepGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
            removeGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
            for (Geometry geometry : allGeometriesQueue) {
                Envelope geometryenvelope = geometry.getEnvelopeInternal();
                if (geometryenvelope.intersects(envelope)) {
                    removeGeometriesQueue.add(geometry);
                    if (readEnvelope == null) {
                        readEnvelope = new Envelope(geometryenvelope);
                    } else {
                        readEnvelope.expandToInclude(geometryenvelope);
                    }
                } else {
                    keepGeometriesQueue.add(geometry);
                }
            }
            allGeometriesQueue = keepGeometriesQueue;
            if (removeGeometriesQueue.size() == 0) {
                continue;
            }
            // pm.message("" + readEnvelope);
            GridCoverage2D readGC = getGridCoverage(0, readEnvelope);
            double novalue = HMConstants.getNovalue(readGC);
            GridGeometry2D gridGeometry = readGC.getGridGeometry();
            Raster readRaster = readGC.getRenderedImage().getData();
            RandomIter readIter = RandomIterFactory.create(readRaster, null);
            for (Geometry geometry : removeGeometriesQueue) {
                double[] polygonStats = OmsZonalStats.polygonStats(geometry, gridGeometry, readIter, novalue, hasUserTotalMean, tm_usertm_tactivecells, pPercentageThres, pm);
                if (polygonStats == null) {
                    continue;
                }
                Object[] values;
                if (pTotalMean == null) {
                    values = new Object[] { // 
                    geometry, // 
                    polygonStats[0], // 
                    polygonStats[1], // 
                    polygonStats[2], // 
                    polygonStats[3], // 
                    polygonStats[4], // 
                    (int) polygonStats[5], // 
                    (int) polygonStats[6] };
                } else {
                    values = new Object[] { // 
                    geometry, // 
                    polygonStats[0], // 
                    polygonStats[1], // 
                    polygonStats[2], // 
                    polygonStats[3], // 
                    polygonStats[4], // 
                    polygonStats[5], // 
                    (int) polygonStats[6], // 
                    (int) polygonStats[7] };
                }
                featureBuilder.addAll(values);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                ((DefaultFeatureCollection) outVector).add(feature);
            }
        }
        pm.worked(1);
    }
    pm.done();
    if (!hasUserTotalMean) {
        tm_usertm_tactivecells[0] = tm_usertm_tactivecells[0] / tm_usertm_tactivecells[2];
        pm.message("Total mean: " + tm_usertm_tactivecells[0]);
    }
    dispose();
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) Raster(java.awt.image.Raster) RandomIter(javax.media.jai.iterator.RandomIter) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(org.locationtech.jts.geom.Geometry) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) File(java.io.File) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) Execute(oms3.annotations.Execute)

Example 2 with Execute

use of oms3.annotations.Execute in project hortonmachine by TheHortonMachine.

the class Mapurl2MbtilesConverter method process.

@Execute
public void process() throws Exception {
    checkNull(inFile);
    File mapurlFile = new File(inFile);
    HashMap<String, String> metadataMap = FileUtilities.readFileToHashMap(inFile, "=", false);
    String url = metadataMap.get("url");
    if (url == null) {
        throw new ModelsIllegalargumentException("The supplied file doesn't seem to be a valid HortonMachine mapurl file.", this, pm);
    }
    if (url.endsWith("jpg")) {
        format = "jpg";
    } else {
        format = "png";
    }
    File dbFile = FileUtilities.substituteExtention(mapurlFile, "mbtiles");
    String tilesetName = FileUtilities.getNameWithoutExtention(mapurlFile);
    File folderFile = new File(mapurlFile.getParentFile(), tilesetName);
    mbtilesHelper = new MBTilesHelper();
    mbtilesHelper.open(dbFile);
    mbtilesHelper.createTables(false);
    File[] zFolders = folderFile.listFiles();
    List<File> xFolder = new ArrayList<File>();
    for (File zFolder : zFolders) {
        File[] xFiles = zFolder.listFiles();
        for (File xFile : xFiles) {
            if (xFile.isDirectory()) {
                xFolder.add(xFile);
            }
        }
    }
    final GlobalMercator mercator = new GlobalMercator();
    int minZ = 1000;
    int maxZ = -1000;
    EggClock clock = new EggClock("Time check: ", " sec");
    clock.startAndPrint(System.out);
    for (File xFile : xFolder) {
        String zStr = xFile.getParentFile().getName();
        final int z = Integer.parseInt(zStr);
        minZ = min(minZ, z);
        maxZ = max(maxZ, z);
        String xStr = xFile.getName();
        final int x = Integer.parseInt(xStr);
        final File[] yFiles = xFile.listFiles(new FilenameFilter() {

            public boolean accept(File arg0, String name) {
                boolean endsWithPng = name.endsWith("png");
                boolean endsWithJpg = name.endsWith("jpg");
                if (endsWithPng || endsWithJpg) {
                    return true;
                }
                return false;
            }
        });
        for (File yFile : yFiles) {
            String yStr = FileUtilities.getNameWithoutExtention(yFile);
            int y = Integer.parseInt(yStr);
            Envelope wsen = mercator.TileLatLonBounds(x, y, z);
            n = max(n, wsen.getMaxY());
            e = max(e, wsen.getMaxX());
            s = max(s, wsen.getMinY());
            w = max(w, wsen.getMinX());
            try {
                BufferedImage image = ImageIO.read(yFile);
                mbtilesHelper.addTile(x, y, z, image, format);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (imageIndex % 1000 == 0) {
                pm.message("Images inserted in db: " + imageIndex);
                clock.printTimePassedInSeconds(System.out);
            }
            imageIndex++;
        }
    }
    mbtilesHelper.fillMetadata((float) n, (float) s, (float) w, (float) e, "tilesetName", format, minZ, maxZ);
    mbtilesHelper.createIndexes();
    mbtilesHelper.close();
}
Also used : ArrayList(java.util.ArrayList) Envelope(org.locationtech.jts.geom.Envelope) BufferedImage(java.awt.image.BufferedImage) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) EggClock(org.hortonmachine.gears.utils.time.EggClock) FilenameFilter(java.io.FilenameFilter) File(java.io.File) Execute(oms3.annotations.Execute)

Example 3 with Execute

use of oms3.annotations.Execute in project hortonmachine by TheHortonMachine.

the class OmsOnlineTilesDownloader method process.

@Execute
public void process() throws Exception {
    checkNull(inPath, inServiceUrl, pEpsg, pMinzoom, pMaxzoom, pWest, pEast, pSouth, pNorth);
    CoordinateReferenceSystem boundsCrs = CrsUtilities.getCrsFromEpsg(pEpsg, null);
    CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
    CoordinateReferenceSystem latLongCrs = CrsUtilities.getCrsFromEpsg(EPSG_LATLONG, null);
    ReferencedEnvelope inBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, boundsCrs);
    MathTransform in2MercatorTransform = CRS.findMathTransform(boundsCrs, mercatorCrs);
    Envelope mercatorEnvelope = JTS.transform(inBounds, in2MercatorTransform);
    ReferencedEnvelope mercatorBounds = new ReferencedEnvelope(mercatorEnvelope, mercatorCrs);
    MathTransform transform = CRS.findMathTransform(boundsCrs, latLongCrs);
    Envelope latLongBounds = JTS.transform(inBounds, transform);
    Coordinate latLongCentre = latLongBounds.centre();
    File inFolder = new File(inPath);
    File baseFolder = new File(inFolder, pName);
    double w = latLongBounds.getMinX();
    double s = latLongBounds.getMinY();
    double e = latLongBounds.getMaxX();
    double n = latLongBounds.getMaxY();
    GlobalMercator mercator = new GlobalMercator();
    for (int z = pMinzoom; z <= pMaxzoom; z++) {
        // get ul and lr tile number in GOOGLE tiles
        int[] llTileXY = mercator.GoogleTile(s, w, z);
        int[] urTileXY = mercator.GoogleTile(n, e, z);
        int startXTile = Math.min(llTileXY[0], urTileXY[0]);
        int endXTile = Math.max(llTileXY[0], urTileXY[0]);
        int startYTile = Math.min(llTileXY[1], urTileXY[1]);
        int endYTile = Math.max(llTileXY[1], urTileXY[1]);
        int tileNum = 0;
        ReferencedEnvelope levelBounds = new ReferencedEnvelope();
        pm.beginTask("Generating tiles at zoom level: " + z, (endXTile - startXTile + 1));
        for (int i = startXTile; i <= endXTile; i++) {
            for (int j = startYTile; j <= endYTile; j++) {
                tileNum++;
                Envelope bounds = mercator.TileLatLonBounds(i, j, z);
                ReferencedEnvelope tmpBounds = new ReferencedEnvelope(bounds, latLongCrs);
                levelBounds.expandToInclude(tmpBounds);
                if (!doDryrun) {
                    int[] onlineTileNumbers = { i, j };
                    int[] fileNameTileNumbers = { i, j };
                    // switch( pType ) {
                    // case 1:
                    // need to convert in TMS format
                    int[] tmsNUms = mercator.TMSTileFromGoogleTile(i, j, z);
                    fileNameTileNumbers = tmsNUms;
                    // break;
                    // case 0:
                    // default:
                    // break;
                    // }
                    File imageFolder = new File(baseFolder, z + "/" + fileNameTileNumbers[0]);
                    if (!imageFolder.exists()) {
                        if (!imageFolder.mkdirs()) {
                            throw new ModelsIOException("Unable to create folder:" + imageFolder, this);
                        }
                    }
                    File imageFile = new File(imageFolder, fileNameTileNumbers[1] + ".png");
                    if (imageFile.exists()) {
                        continue;
                    }
                    String tmp = inServiceUrl.replaceFirst("ZZZ", String.valueOf(z));
                    tmp = tmp.replaceFirst("XXX", String.valueOf(onlineTileNumbers[0]));
                    tmp = tmp.replaceFirst("YYY", String.valueOf(onlineTileNumbers[1]));
                    // System.out.println(tmp);
                    URL url = new URL(tmp);
                    InputStream imgStream = null;
                    OutputStream out = null;
                    try {
                        imgStream = url.openStream();
                        out = new FileOutputStream(imageFile);
                        int read = 0;
                        byte[] bytes = new byte[1024];
                        while ((read = imgStream.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                    } catch (Exception ex) {
                        pm.errorMessage("Unable to get image: " + tmp);
                    } finally {
                        if (imgStream != null)
                            imgStream.close();
                        if (out != null) {
                            out.flush();
                            out.close();
                        }
                    }
                }
            }
            pm.worked(1);
        }
        pm.done();
        pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
        pm.message("Boundary covered at Zoom level: " + z + ": " + levelBounds);
        pm.message("Total boundary wanted: " + mercatorBounds);
    }
    StringBuilder properties = new StringBuilder();
    properties.append("url=").append(pName).append("/ZZZ/XXX/YYY.png\n");
    properties.append("minzoom=").append(pMinzoom).append("\n");
    properties.append("maxzoom=").append(pMaxzoom).append("\n");
    properties.append("center=").append(latLongCentre.x).append(" ").append(latLongCentre.y).append("\n");
    properties.append("type=tms").append("\n");
    File propFile = new File(inFolder, pName + ".mapurl");
    FileUtilities.writeFile(properties.toString(), propFile);
}
Also used : MathTransform(org.opengis.referencing.operation.MathTransform) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) URL(java.net.URL) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Coordinate(org.locationtech.jts.geom.Coordinate) FileOutputStream(java.io.FileOutputStream) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) File(java.io.File) Execute(oms3.annotations.Execute)

Example 4 with Execute

use of oms3.annotations.Execute in project hortonmachine by TheHortonMachine.

the class OmsTmsGenerator method process.

@Execute
public void process() throws Exception {
    try {
        checkNull(inPath, pMinzoom, pMaxzoom, pWest, pEast, pSouth, pNorth);
        if (dataCrs == null) {
            if (pEpsg != null) {
                dataCrs = CrsUtilities.getCrsFromEpsg(pEpsg, null);
            } else {
                String wkt = FileUtilities.readFile(inPrj);
                dataCrs = CRS.parseWKT(wkt);
            }
        }
        String format = null;
        if (doMbtiles) {
            mbtilesHelper = new MBTilesHelper();
            File dbFolder = new File(inPath);
            File dbFile = new File(dbFolder, pName + ".mbtiles");
            ReferencedEnvelope dataBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, dataCrs);
            MathTransform data2LLTransform = CRS.findMathTransform(dataCrs, DefaultGeographicCRS.WGS84);
            Envelope llEnvelope = JTS.transform(dataBounds, data2LLTransform);
            float n = (float) llEnvelope.getMaxY();
            float s = (float) llEnvelope.getMinY();
            float w = (float) llEnvelope.getMinX();
            float e = (float) llEnvelope.getMaxX();
            format = pImagetype == 0 ? "png" : "jpg";
            mbtilesHelper.open(dbFile);
            mbtilesHelper.createTables(false);
            mbtilesHelper.fillMetadata(n, s, w, e, pName, format, pMinzoom, pMaxzoom);
        }
        int threads = getDefaultThreadsNum();
        String ext = "png";
        if (pImagetype == 1) {
            ext = "jpg";
        }
        checkCancel();
        List<String> inVectors = null;
        if (inVectorFile != null && new File(inVectorFile).exists())
            inVectors = FileUtilities.readFileToLinesList(new File(inVectorFile));
        checkCancel();
        List<String> inRasters = null;
        if (inRasterFile != null && new File(inRasterFile).exists())
            inRasters = FileUtilities.readFileToLinesList(new File(inRasterFile));
        if (inRasters == null && inVectors == null) {
            throw new ModelsIllegalargumentException("No raster and vector input maps available. check your inputs.", this, pm);
        }
        if (dataCrs == null && pEpsg == null && inPrj == null) {
            throw new ModelsIllegalargumentException("No projection info available. check your inputs.", this, pm);
        }
        final CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
        ReferencedEnvelope dataBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, dataCrs);
        MathTransform data2MercatorTransform = CRS.findMathTransform(dataCrs, mercatorCrs);
        Envelope mercatorEnvelope = JTS.transform(dataBounds, data2MercatorTransform);
        ReferencedEnvelope mercatorBounds = new ReferencedEnvelope(mercatorEnvelope, mercatorCrs);
        checkCancel();
        if (inZoomLimitVector != null) {
            SimpleFeatureCollection zoomLimitVector = OmsVectorReader.readVector(inZoomLimitVector);
            List<Geometry> geoms = FeatureUtilities.featureCollectionToGeometriesList(zoomLimitVector, true, null);
            MultiPolygon multiPolygon = gf.createMultiPolygon(geoms.toArray(GeometryUtilities.TYPE_POLYGON));
            // convert to mercator
            Geometry multiPolygonGeom = JTS.transform(multiPolygon, data2MercatorTransform);
            zoomLimitGeometry = PreparedGeometryFactory.prepare(multiPolygonGeom);
        }
        File inFolder = new File(inPath);
        final File baseFolder = new File(inFolder, pName);
        final ImageGenerator imgGen = new ImageGenerator(pm, mercatorCrs);
        if (inWMS != null) {
            imgGen.setWMS(inWMS);
        }
        String notLoading = "Not loading non-existing file: ";
        if (inRasters != null)
            for (String rasterPath : inRasters) {
                File file = new File(rasterPath);
                if (file.exists()) {
                    imgGen.addCoveragePath(rasterPath);
                } else {
                    pm.errorMessage(notLoading + rasterPath);
                }
            }
        if (inRasterBounds != null)
            for (GridGeometry2D rasterBounds : inRasterBounds) {
                imgGen.addCoverageRegion(rasterBounds);
            }
        if (inVectors != null)
            for (String vectorPath : inVectors) {
                File file = new File(vectorPath);
                if (file.exists()) {
                    imgGen.addFeaturePath(vectorPath, null);
                } else {
                    pm.errorMessage(notLoading + vectorPath);
                }
            }
        imgGen.setLayers();
        double w = mercatorBounds.getMinX();
        double s = mercatorBounds.getMinY();
        double e = mercatorBounds.getMaxX();
        double n = mercatorBounds.getMaxY();
        final GlobalMercator mercator = new GlobalMercator();
        for (int z = pMinzoom; z <= pMaxzoom; z++) {
            checkCancel();
            // get ul and lr tile number
            int[] llTileNumber = mercator.MetersToTile(w, s, z);
            int[] urTileNumber = mercator.MetersToTile(e, n, z);
            int startXTile = llTileNumber[0];
            int startYTile = llTileNumber[1];
            int endXTile = urTileNumber[0];
            int endYTile = urTileNumber[1];
            int tileNum = 0;
            final ReferencedEnvelope levelBounds = new ReferencedEnvelope(mercatorCrs);
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threads);
            pm.beginTask("Generating tiles at zoom level: " + z, (endXTile - startXTile + 1) * (endYTile - startYTile + 1));
            for (int i = startXTile; i <= endXTile; i++) {
                checkCancel();
                for (int j = startYTile; j <= endYTile; j++) {
                    checkCancel();
                    double[] bounds = mercator.TileBounds(i, j, z);
                    double west = bounds[0];
                    double south = bounds[1];
                    double east = bounds[2];
                    double north = bounds[3];
                    final ReferencedEnvelope tmpBounds = new ReferencedEnvelope(west, east, south, north, mercatorCrs);
                    levelBounds.expandToInclude(tmpBounds);
                    // if there is a zoom level geometry limitation, apply it
                    if (zoomLimitGeometry != null && z > pZoomLimit) {
                        double safeExtend = tmpBounds.getWidth() > tmpBounds.getHeight() ? tmpBounds.getWidth() : tmpBounds.getHeight();
                        final ReferencedEnvelope tmp = new ReferencedEnvelope(tmpBounds);
                        tmp.expandBy(safeExtend);
                        Polygon polygon = FeatureUtilities.envelopeToPolygon(tmp);
                        if (!zoomLimitGeometry.intersects(polygon)) {
                            pm.worked(1);
                            continue;
                        }
                    }
                    if (mbtilesHelper != null) {
                        final int x = i;
                        final int y = j;
                        final int zz = z;
                        final String fformat = format;
                        tileNum++;
                        Runnable runner = new Runnable() {

                            public void run() {
                                if (!cancelModule) {
                                    try {
                                        checkCancel();
                                        BufferedImage image = imgGen.getImageWithCheck(tmpBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        if (image != null) {
                                            mbtilesHelper.addTile(x, y, zz, image, fformat);
                                        }
                                    } catch (Exception e) {
                                        pm.errorMessage(e.getMessage());
                                        cancelModule = true;
                                    }
                                }
                                pm.worked(1);
                            }
                        };
                        fixedThreadPool.execute(runner);
                    } else {
                        File imageFolder = new File(baseFolder, z + "/" + i);
                        if (!imageFolder.exists()) {
                            if (!imageFolder.mkdirs()) {
                                throw new ModelsIOException("Unable to create folder:" + imageFolder, this);
                            }
                        }
                        File ignoreMediaFile = new File(imageFolder, ".nomedia");
                        ignoreMediaFile.createNewFile();
                        final File imageFile = new File(imageFolder, j + "." + ext);
                        if (imageFile.exists()) {
                            pm.worked(1);
                            continue;
                        }
                        tileNum++;
                        final String imagePath = imageFile.getAbsolutePath();
                        final ReferencedEnvelope finalBounds = tmpBounds;
                        Runnable runner = new Runnable() {

                            public void run() {
                                if (!cancelModule) {
                                    try {
                                        if (pImagetype == 1) {
                                            imgGen.dumpJpgImage(imagePath, finalBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        } else {
                                            imgGen.dumpPngImage(imagePath, finalBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        }
                                        pm.worked(1);
                                    } catch (Exception ex) {
                                        pm.errorMessage(ex.getMessage());
                                        cancelModule = true;
                                    }
                                }
                            }
                        };
                        fixedThreadPool.execute(runner);
                    }
                }
            }
            try {
                fixedThreadPool.shutdown();
                while (!fixedThreadPool.isTerminated()) {
                    Thread.sleep(100);
                }
            } catch (InterruptedException exx) {
                exx.printStackTrace();
            }
            pm.done();
            pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
        // pm.message("Boundary covered at Zoom level: " + z + ": " + levelBounds);
        // pm.message("Total boundary wanted: " + mercatorBounds);
        }
        if (mbtilesHelper != null) {
            mbtilesHelper.createIndexes();
            mbtilesHelper.close();
        } else {
            CoordinateReferenceSystem latLongCrs = CrsUtilities.getCrsFromEpsg(EPSG_LATLONG, null);
            MathTransform transform = CRS.findMathTransform(mercatorCrs, latLongCrs);
            Envelope latLongBounds = JTS.transform(mercatorBounds, transform);
            Coordinate latLongCentre = latLongBounds.centre();
            StringBuilder properties = new StringBuilder();
            properties.append("url=").append(pName).append("/ZZZ/XXX/YYY.").append(ext).append("\n");
            properties.append("minzoom=").append(pMinzoom).append("\n");
            properties.append("maxzoom=").append(pMaxzoom).append("\n");
            properties.append("center=").append(latLongCentre.y).append(" ").append(latLongCentre.x).append("\n");
            properties.append("type=tms").append("\n");
            File propFile = new File(inFolder, pName + ".mapurl");
            FileUtilities.writeFile(properties.toString(), propFile);
        }
    } catch (ModelsUserCancelException e) {
        pm.errorMessage(ModelsUserCancelException.DEFAULTMESSAGE);
    }
}
Also used : GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) MathTransform(org.opengis.referencing.operation.MathTransform) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) BufferedImage(java.awt.image.BufferedImage) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ModelsUserCancelException(org.hortonmachine.gears.libs.exceptions.ModelsUserCancelException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Polygon(org.locationtech.jts.geom.Polygon) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) ModelsUserCancelException(org.hortonmachine.gears.libs.exceptions.ModelsUserCancelException) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) Coordinate(org.locationtech.jts.geom.Coordinate) ExecutorService(java.util.concurrent.ExecutorService) ImageGenerator(org.hortonmachine.gears.utils.images.ImageGenerator) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) File(java.io.File) Execute(oms3.annotations.Execute)

Example 5 with Execute

use of oms3.annotations.Execute in project hortonmachine by TheHortonMachine.

the class TmsWms2Geotiff method process.

@Execute
public void process() throws Exception {
    checkNull(inServiceUrl, outRaster, inRoiPath);
    CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
    CoordinateReferenceSystem latLongCrs = DefaultGeographicCRS.WGS84;
    SimpleFeatureCollection inRoi = getVector(inRoiPath);
    ReferencedEnvelope inBounds = inRoi.getBounds();
    ReferencedEnvelope latLongBounds = inBounds.transform(latLongCrs, true);
    double w = latLongBounds.getMinX();
    double s = latLongBounds.getMinY();
    double e = latLongBounds.getMaxX();
    double n = latLongBounds.getMaxY();
    int z = 18;
    if (pZoomlevel != null) {
        z = pZoomlevel;
    }
    GlobalMercator gm = new GlobalMercator();
    int[] llTileXY = gm.GoogleTile(s, w, z);
    int[] urTileXY = gm.GoogleTile(n, e, z);
    int startXTile = Math.min(llTileXY[0], urTileXY[0]);
    int endXTile = Math.max(llTileXY[0], urTileXY[0]);
    int startYTile = Math.min(llTileXY[1], urTileXY[1]);
    int endYTile = Math.max(llTileXY[1], urTileXY[1]);
    if (pSchemaType.equals(OGC_TMS)) {
        llTileXY = gm.TMSTileFromGoogleTile(llTileXY[0], llTileXY[1], z);
        urTileXY = gm.TMSTileFromGoogleTile(urTileXY[0], urTileXY[1], z);
    }
    startXTile = Math.min(llTileXY[0], urTileXY[0]);
    endXTile = Math.max(llTileXY[0], urTileXY[0]);
    startYTile = Math.min(llTileXY[1], urTileXY[1]);
    endYTile = Math.max(llTileXY[1], urTileXY[1]);
    int tilesCountX = endXTile - startXTile + 1;
    int tilesCountY = endYTile - startYTile + 1;
    int width = tilesCountX * tileSize;
    int height = tilesCountY * tileSize;
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) img.getGraphics();
    int tileNum = 0;
    final ReferencedEnvelope finalMercatorBounds = new ReferencedEnvelope(mercatorCrs);
    pm.beginTask("Getting tiles at zoom level: " + z, (endXTile - startXTile + 1));
    int runningXPix = 0;
    int runningYPix = 0;
    for (int x = startXTile; x <= endXTile; x++) {
        for (int y = startYTile; y <= endYTile; y++) {
            tileNum++;
            int yy = y;
            if (pSchemaType.equalsIgnoreCase(GOOGLE))
                yy = (int) ((Math.pow(2, z) - 1) - y);
            double[] bounds = gm.TileBounds(x, yy, z);
            double west = bounds[0];
            double south = bounds[1];
            double east = bounds[2];
            double north = bounds[3];
            final ReferencedEnvelope tmpBounds = new ReferencedEnvelope(west, east, south, north, mercatorCrs);
            finalMercatorBounds.expandToInclude(tmpBounds);
            String tmp = "";
            if (pSourceType.equals(TMS)) {
                tmp = inServiceUrl.replaceFirst("ZZZ", String.valueOf(z));
                tmp = tmp.replaceFirst("XXX", String.valueOf(x));
                tmp = tmp.replaceFirst("YYY", String.valueOf(y));
            } else if (pSourceType.equals(WMS)) {
                ReferencedEnvelope llTB = tmpBounds.transform(latLongCrs, true);
                tmp = inServiceUrl.replaceFirst("SSS", String.valueOf(llTB.getMinY()));
                tmp = tmp.replaceFirst("NNN", String.valueOf(llTB.getMaxY()));
                tmp = tmp.replaceFirst("WWW", String.valueOf(llTB.getMinX()));
                tmp = tmp.replaceFirst("EEE", String.valueOf(llTB.getMaxX()));
            } else {
                throw new ModelsIllegalargumentException("Source Type can be only 0 or 1.", this);
            }
            // System.out.println(x + "/" + y + ": " + tmp);
            URL url = new URL(tmp);
            try (InputStream imgStream = url.openStream()) {
                BufferedImage tileImg = ImageIO.read(imgStream);
                g2d.drawImage(tileImg, runningXPix, runningYPix, null);
                if (doDebug) {
                    g2d.setColor(Color.RED);
                    g2d.drawRect(runningXPix, runningYPix, tileSize, tileSize);
                    String tileDescr = x + "/" + y + "/" + z;
                    g2d.drawString(tileDescr, runningXPix + 10, runningYPix + 20);
                }
            } catch (Exception ex) {
                pm.errorMessage("Unable to get image: " + tmp);
            }
            runningYPix += tileSize;
        }
        runningXPix += tileSize;
        runningYPix = 0;
        pm.worked(1);
    }
    pm.done();
    pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
    double ww = finalMercatorBounds.getMinX();
    double ss = finalMercatorBounds.getMinY();
    double ee = finalMercatorBounds.getMaxX();
    double nn = finalMercatorBounds.getMaxY();
    double xres = (ee - ww) / width;
    double yres = (nn - ss) / height;
    RegionMap envelopeParams = new RegionMap();
    envelopeParams.put(CoverageUtilities.NORTH, nn);
    envelopeParams.put(CoverageUtilities.SOUTH, ss);
    envelopeParams.put(CoverageUtilities.WEST, ww);
    envelopeParams.put(CoverageUtilities.EAST, ee);
    envelopeParams.put(CoverageUtilities.XRES, xres);
    envelopeParams.put(CoverageUtilities.YRES, yres);
    envelopeParams.put(CoverageUtilities.ROWS, (double) height);
    envelopeParams.put(CoverageUtilities.COLS, (double) width);
    GridCoverage2D coverage = CoverageUtilities.buildCoverage("tmsraster", img, envelopeParams, mercatorCrs);
    OmsRasterWriter.writeRaster(outRaster, coverage);
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) InputStream(java.io.InputStream) RegionMap(org.hortonmachine.gears.utils.RegionMap) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Graphics2D(java.awt.Graphics2D) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Execute(oms3.annotations.Execute)

Aggregations

Execute (oms3.annotations.Execute)389 File (java.io.File)85 WritableRaster (java.awt.image.WritableRaster)80 RegionMap (org.hortonmachine.gears.utils.RegionMap)79 ModelsIllegalargumentException (org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException)75 SimpleFeature (org.opengis.feature.simple.SimpleFeature)67 Coordinate (org.locationtech.jts.geom.Coordinate)64 DefaultFeatureCollection (org.geotools.feature.DefaultFeatureCollection)62 Geometry (org.locationtech.jts.geom.Geometry)59 ArrayList (java.util.ArrayList)58 RandomIter (javax.media.jai.iterator.RandomIter)57 WritableRandomIter (javax.media.jai.iterator.WritableRandomIter)55 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)51 RenderedImage (java.awt.image.RenderedImage)41 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)36 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)32 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)32 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)31 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)28 Polygon (org.locationtech.jts.geom.Polygon)28