WeppSoil.java [src/java/m/weppws] Revision: default  Date:
package m.weppws;

import csip.api.server.ServiceException;
import csip.SessionLogger;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.codehaus.jettison.json.JSONArray;

import util.WEPPSoilParamsServiceCall;

/**
 * A function library for communicating with the public Soil Data Mart and
 * retrieving SSURGO soils information.
 * <p>
 * The primary function of this class is the method
 * {@link #getSoilCSIP(int, String, String)} which constructs a Soil object
 * containing information derived from data in the SSURGO database.
 *
 * @author Eric.Theller
 *
 */
public class WeppSoil {

  String serviceURL;
  SessionLogger LOG;
  String csipSoilFilename;


  WeppSoil(SessionLogger log, String serviceURL) {
    this.LOG = log;
    this.serviceURL = serviceURL;
    csipSoilFilename = null;
  }


  public boolean getSoilCSIP(String metaData, int cokey, File workDir, String soilFileName) throws ServiceException {

    String soilFileData;
    boolean rc = true;
    WEPPSoilParamsServiceCall wwe04 = new WEPPSoilParamsServiceCall(serviceURL, metaData, cokey, true);
    try {
      wwe04.call();
    } catch (ServiceException ex) {
      String metaError = wwe04.getMetaError();
      Logger.getLogger(WeppSoil.class.getName()).log(Level.SEVERE, null, ex);
      if (!metaError.isEmpty()) {
        if (metaError.contains("excluded")) {
          throw new ServiceException("The soil cokey provided does not meet the WEPP component filtering requirements provided by NRCS.");
        }

        if (metaError.contains("not found")) {
          //maybe this soil is an old SSURGO soil, caller decides what to do
          rc = false;
        }
      }
    }

    if (rc) {
      JSONArray soilComponents = wwe04.getResultSection();
      try {
        soilFileData = soilComponents.getJSONObject(0).getString("value");
      } catch (Exception ex) {
        // throw new ServiceException("Data returned from the WEPPSoilInput service did not contain the expected results: " + ex.getMessage(), ex);
        // maybe this soil is an old SSURGO soil, caller decides what to do
        //
        return false;
      }

      File solFile = new File(soilFileName);
      try {
        FileUtils.writeStringToFile(solFile, soilFileData, "UTF-8");
      } catch (IOException ex) {
        throw new ServiceException("Cannot create the sol files locally with the returned data from WEPPSoilInput: " + ex.getMessage(), ex);
      }
    }
    return rc;
  }
}