V1_0.java [src/java/m/watershed/extract_DEM] 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.watershed.extract_DEM;

import csip.ModelDataService;
import javax.ws.rs.Path;
import csip.annotations.*;
import java.io.*;
import com.opencsv.CSVWriter;
import csip.api.server.Executable;
import csip.annotations.Resource;
import static csip.annotations.ResourceType.*;
import java.nio.channels.FileChannel;

/**
 * Extract DEM
 *
 * @author JK (using OD's template)
 */
@Name("extract_DEM")
@Description("Example of DEM extraction")
@Path("m/extract_DEM/1.0")
@Resource(file = "gdalwarp", type = REFERENCE, id = "gdalwarp")

public class V1_0 extends ModelDataService {

    // 2) watershed
    @Override
    protected void doProcess() throws Exception {

        String bound_4326 = parameter().getString("bound_wkt");
        String wd = workspace().getDir().toString();

        File sourceFile = new File("/mnt/csip-watershed/bound.vrt");
        File destFile = new File(wd + "/bound.vrt");

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }

        String outputFile = wd + "/bound.csv";

        try {
            try (CSVWriter csvOutput = new CSVWriter(new FileWriter(outputFile), ';')) {
                String[] entries = "Name#Polygon".split("#");
                csvOutput.writeNext(entries);
                String wkt_row = "Polygon#" + bound_4326;
                String[] entries_2 = wkt_row.split("#");
                csvOutput.writeNext(entries_2);
                csvOutput.close();
            }

        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        }

        Executable e = resources().getExe("gdalwarp");
        e.addArguments("/mnt/csip-watershed/DEM.vrt", wd + "/DEM_clip.tif", "-crop_to_cutline", "-cutline", wd + "/bound.vrt", "-multi");
        e.exec();
    }

    // 3) provide the temperature as a result.
    @Override
    protected void postProcess() throws Exception {
        String ip = request().getRemoteAddr();
        File ws = workspace().getDir();
        results().put(new File(ws, "bound.csv"), "gauged watershed");
        results().put(new File(ws, "bound.vrt"), "gauged watershed");
        results().put(new File(ws, "DEM_clip.tif"), "gauged watershed");

    }

}