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

import csip.Config;
import csip.ModelDataService;
import csip.annotations.Description;
import csip.annotations.Name;
import csip.annotations.Resource;
import csip.api.server.PayloadParameter;
import csip.api.server.ServiceException;
import csip.utils.Validation;
import d.dataNodes.SWATplusData;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.ws.rs.Path;
import soils.Component;
import soils.MapUnit;
import static soils.db.DBResources.SDM;
import soils.db.SOILS_DATA;
import soils.db.SOILS_DB_Factory;
import soils.exceptions.WEPPException;

/**
 *
 * @author sidereus
 */
@Name("SWAT+ soil input")
@Description("Gets data from the NRCS Soil Data Mart and generates sol input file for SWAT+")
@Path("d/swatplus/1.0")
@Resource(from = soils.db.DBResources.class)
public class V1_0 extends ModelDataService {

  static String KEY_COKEY = "cokey";
  static String KEY_FILENAME = "soils.sol";

  @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("fpp.version", "swatplus 1.0");
      }
    };
  }


    @Override
    protected void doProcess()  throws ServiceException {

    PayloadParameter payload = parameter();
    String cokey = payload.getString(KEY_COKEY);
    Validation.checkCokey(cokey);

    Component comp = null;
    MapUnit mapUnit = null;

    try (SOILS_DATA soilsDb = SOILS_DB_Factory.createEngine(getClass(), LOG, Config.getString("soils.gis.database.source"))) {
      comp = new Component();
      comp.cokey(cokey);
      if (soilsDb.validateComponent(Integer.parseInt(comp.cokey()))) {
        if (null == (mapUnit = soilsDb.findWEPPDataByCokey(comp))) {
          throw new ServiceException("Could not retrieve the proper SDM soils data for this cokey");
        }
      } else {
        throw new ServiceException("The cokey value provided does not exist in the SDM database.  Cannot continue.");
      }
    } catch (ServiceException | SQLException | WEPPException ex) {
      throw new RuntimeException(ex);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    SWATplusData spd = new SWATplusData();
    try {
      spd.computeAndWrite(workspace().getDir().getPath(), KEY_FILENAME, comp);
    } catch (IOException ex) {
      throw new RuntimeException(ex.getMessage());
    }

    results().put(workspace().getFile(KEY_FILENAME));
  }
}