V1_0.java [src/java/d/soils/rc03_rcsoilparams] 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 d.soils.rc03_rcsoilparams;

import adb.DBResources;
import static adb.DBResources.EROSION_SQLSVR;
import static adb.DBResources.R2GIS_SQLSVR;
import csip.Config;
import csip.ModelDataService;
import csip.SessionLogger;
import csip.annotations.Description;
import csip.annotations.Name;
import csip.annotations.Resource;
import static csip.annotations.ResourceType.FILE;
import csip.api.server.ServiceException;
import csip.api.server.ServiceResources;
import d.util.WindWaterErosion;
import static d.util.WindWaterErosion.WWE_TIFF_FILE;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.ws.rs.Path;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import soils.MapUnit;
import static soils.db.DBResources.SDM;
import soils.db.SOILS_DATA;
import soils.db.SOILS_DB_Factory;
import soils.db.tables.TableComponent;
import soils.db.tables.TableComponentCalculations;
import soils.db.tables.TableHorizon;
import soils.db.tables.TableMapUnit;
import soils.db.tables.TableMapUnitCalculations;
import utils.MDS_Result;

/**
 *
 * @author <a href="mailto:shaun.case@colostate.edu">Shaun Case</a>
 */
@Name("RCSoilParams")
@Description("This service fetches soil mapnunits, components, and horizons for "
    + "the soil mapunits intersected by farm field geometry (area of assessment) "
    + "necessary for algorithms used to prescreen, screen, and/or assess NRCS resource concerns.")
@Path("d/rcsoilparams/1.0")

@Resource(file = "/data/us_cvalues_topo2ras_masked.tif", type = FILE, id = WWE_TIFF_FILE)
@Resource(file = "/data/us_cvalues_topo2ras_masked.tfw", type = FILE, id = "tfw_file")
@Resource(file = "/data/us_cvalues_topo2ras_masked.tif.aux.xml", type = FILE, id = "tifxml_file")

@Resource(from = soils.db.DBResources.class)
@Resource(from = DBResources.class)

public class V1_0 extends ModelDataService {

  protected final ServiceResources resources = resources();

  @Override
  protected Map<String, Object> getConfigInfo() {
    return new LinkedHashMap<String, Object>() {
      {
        put("soils.gis.database.source", resources().getResolved("soils.gis.database.source"));
        put(SDM, resources().getResolved(SDM));
        put(R2GIS_SQLSVR, resources().getResolved(R2GIS_SQLSVR));
        put("cfactor_gis_raster_file", resources().getResolved(WWE_TIFF_FILE));
        put("fpp.version", "rcs 1.0");
      }
    };
  }

  @Override
  protected void doProcess() throws Exception {
    try (SOILS_DATA soilsDb = SOILS_DB_Factory.createEngine(getClass(), LOG, Config.getString("soils.gis.database.source")); Connection gisDb = resources.getJDBC(EROSION_SQLSVR);) {
      soils.AoA.setMapUnitsRequired(false);
      WindWaterErosion.loadGisRaster(() -> resources.getFile(WWE_TIFF_FILE));

      V1_0.AoA aoaErosion = new V1_0.AoA(soilsDb, gisDb, getParamMap(), LOG);

      aoaErosion.getErosion(() -> resources.getJDBC(R2GIS_SQLSVR), false); //Will throw exception on failure

      aoaErosion.toJSON((String name, Object val, String descr, String unit) -> results().put(name, val, descr, unit));
      aoaErosion.soilsToJSON((String name, Object val, String descr, String unit) -> results().put(name, val, descr, unit));
    }
  }

  protected class AoA extends WindWaterErosion {

    public AoA(SOILS_DATA soilsDb, Connection gisDb, Map<String, JSONObject> params, SessionLogger Log) throws Exception {
      super(soilsDb, gisDb, params, Log);
    }

    @Override
    public void getErosion(Callable<Connection> r2gis, boolean adjustForIrrig) throws Exception {
      getCFactor(r2gis);
      getSoilsData(adjustForIrrig);
      getMaxFloodingPondingData(); //Also fills in the Comonth table data for each Component of each Mapunit.
      getSalinitySodicity(); // Evaluates salinity and sodicity values.  Requires Horizon table to be filled in already and contain sar_r and ec_r values.
    }

    public JSONArray soilsToJSON(MDS_Result output) throws JSONException, IOException, ServiceException {
      JSONArray soilsArray = new JSONArray();
      for (MapUnit mapUnit : map_units.values()) {

        mapUnit.setOutputColumnOrdering(new ArrayList(Arrays.asList(
            TableMapUnit.MUKEY, TableMapUnit.MUNAME,
            TableMapUnit.AREASYMBOL_NAME, TableMapUnit.MUACRES, TableMapUnitCalculations.AREA_NAME, TableMapUnitCalculations.AREA_PCT
        )));
        mapUnit.setComponentOutputColumnOrdering(new ArrayList(Arrays.asList(
            TableComponent.COKEY, TableComponent.COMPNAME, TableComponent.COMPPCT_R_NAME, TableComponentCalculations.AREA_PCT_NAME,
            TableComponent.TAXORDER_NAME, TableComponent.TFACT_NAME, TableComponent.HYDRICRATING,
            TableComponentCalculations.SALINITY, TableComponentCalculations.SODICITY,
            TableComponentCalculations.POND_FREQ_CL, TableComponentCalculations.FLOD_FREQ_CL
        )));
        mapUnit.setHorizonOutputColumnOrdering(new ArrayList(Arrays.asList(
            TableHorizon.CHKEY_NAME, TableHorizon.HZDEPT_R_NAME,
            TableHorizon.HZDEPB_R_NAME, TableHorizon.EC_R, TableHorizon.SAR_R
        )));

        soilsArray.put(mapUnit.toJSON(false, false));
        output.putResult("soils_list", soilsArray, null, null);
      }

      return soilsArray;
    }
  }
}