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

import csip.ModelDataService;
import csip.api.server.Executable;
import csip.annotations.*;
import csip.api.server.ServiceException;
import static csip.annotations.ResourceType.*;
import java.io.File;
import javax.ws.rs.*;
import org.codehaus.jettison.json.JSONObject;
import org.json.XML;
import java.io.IOException;
import java.util.logging.Level;
import static m.weppws.ApplicationResources.*;

@Name("weppws-run_flowpath")
@Description("WEPPWS-run_flowpath - run a WEPP simulation for a single flowpath")
@Path("m/run_flowpath/1.0")
@Polling(first = 2000, next = 2000)

// Executables & File parameter
@Resource(file = "/bin/${arch}/wepphillslopeservws.exe", id = "weppserv", type = EXECUTABLE)
@Resource(file = "/bin/${arch}/weppws_2020.exe", id = "wepp", type = EXECUTABLE)
@Resource(file = "/bin/${arch}/weppws_2020_64.exe", id = "wepp64", type = EXECUTABLE)
public class V1_0 extends ModelDataService {

  float avgPrecip;
  float avgSoilLoss;
  float avgSedYield;
  float avgRunoff;
  float avgIrrigation;

  String weppVersion;
  String preVersion;


  /**
   * doProcess() Get input parameters from WEPP request.
   *
   * @throws Exception
   */
  @Override
  protected void doProcess() throws Exception {
    boolean use64BitWEPP = parameter().getBoolean(USE64BITWEPP, false);
    Executable weppserv = resources().getExe("weppserv");
  
    // Run an external program to create all the model inputs and run wepp
    // turn on calibration flag
    weppserv.setArguments(workspace().getDir(),
        workspace().getFile("wepp.prj"),
        workspace().getFile("output/weppout.txt"),
        resources().getFile(use64BitWEPP ? "wepp64" : "wepp"), "0", 0, 0, 1);
  
    int ret = weppserv.exec();
    if (ret != 0) {
      throw new ServiceException("WEPP run error: " + ret);
    }
    parseOutputs(workspace().readString("output/weppout.txt"));
  }


  /**
   * postProcess() Extract some WEPP outputs and include links to model input
   * and output files.
   *
   * @throws Exception
   */
  @Override
  protected void postProcess() throws Exception {
    metainfo().put("WEPPVersion", weppVersion);
    metainfo().put("PreprocessorVersion", preVersion);

    results().put("Precipitation", avgPrecip, "Average Annual Preciptation", "in");
    results().put("SoilLoss", avgSoilLoss, "Average Annual Soil Loss", "ton/ac/yr");
    results().put("Runoff", avgRunoff, "Average Annual Runoff", "in");
    results().put("SedimentYield", avgSedYield, "Average Annual Sediment Yield", "ton/ac/yr");
    results().put("Irrigation", avgIrrigation, "Average Annual Irrigation", "in");

    String lossFileStr = workspace().readString("output/plot_0.txt");

    results().put("SoilLossCells", lossFileStr, "WEPP Profile Soil Loss Output");
    
    File f = workspace().getFile("output/pass_0.txt");
    if (f.exists()) {
       results().put("PassFile", f.getName(), "WEPP pass file for use in watershed run");
    }
    
  }


  /**
   * After a WEPP run a brief put file lists the main 4 outputs which as read
   * and saved.
   *
   * @param resultsFile WEPP results
   * @throws IOException error reading file
   */
  private void parseOutputs(String content) throws IOException {
    try {
      String restring = XML.toJSONObject(content).toString();
      JSONObject results = new JSONObject(restring);
      if (!results.has("RESULTS")) {
        throw new IOException("XML Contents missing or 'RESULTS' xml tag not found.");
      }

      results = results.optJSONObject("RESULTS");
      avgPrecip = (float) results.optDouble("PRECIP");
      avgSoilLoss = (float) results.optDouble("LOSS");
      avgSedYield = (float) results.optDouble("SEDYIELD");
      avgRunoff = (float) results.optDouble("RUNOFF");
      weppVersion = results.getString("WEPP_VERSION");
      avgIrrigation = (float) results.optDouble("IRRIGATION");
      preVersion = results.getString("PREPROCESSOR_VERSION");
    } catch (org.json.JSONException | org.codehaus.jettison.json.JSONException E) {
      LOG.log(Level.WARNING, "Reset values to defaults because of: ", E);
      avgPrecip = avgSoilLoss = avgSedYield = avgRunoff = (float) -999;
    }
  }

}