RasterUtils.java [src/m/utils/raster] Revision: default  Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package m.utils.raster;

import csip.api.server.ServiceException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import m.utils.Layer;
import m.utils.LocalStringUtils;

/**
 *
 * @author ktraff
 */
public class RasterUtils {
    
    protected static final Logger LOG = Logger.getLogger(RasterUtils.class.getName());
    
    
    public static void runCommand(String [] args) throws ServiceException {
        try {
            LOG.log(Level.INFO, LocalStringUtils.join(args, " "));
            ProcessBuilder ps = new ProcessBuilder(args);

            //From the DOC:  Initially, this property is false, meaning that the 
            //standard output and error output of a subprocess are sent to two 
            //separate streams
            ps.redirectErrorStream(true);

            Process pr = ps.start();  

            BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                LOG.log(Level.INFO, line);
            }
            pr.waitFor();
            LOG.log(Level.INFO, "Process complete ("+pr.exitValue()+"): ");

            in.close();
        } catch (IOException|InterruptedException ex) {
            throw new ServiceException(ex);
        }
    }
    
    public static File clip(Layer lyr, File src, String dest) throws ServiceException {
        String [] cmd = {"/usr/bin/gdalwarp", "-cutline", lyr.db.getConnectionString(),
                "-csql", "SELECT * FROM "+lyr.getSchemaTable(),
                "-crop_to_cutline", "-of", "GTiff", "-srcnodata", "-9999",
                "-dstnodata", "-9999", src.toString(), dest};
        runCommand(cmd);

        return new File(dest);
    }
}