V1_0.java [src/java/m/comet/comet03_cliparams] Revision: default  Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API, and application suite.
 *
 * 2012-2017, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package m.comet.comet03_cliparams;

import csip.Config;
import csip.ModelDataService;
import csip.ServiceException;
import csip.annotations.Polling;
import csip.utils.JSONUtils;
import java.util.Map;
import javax.ws.rs.Path;
import m.comet.utils.COMETools;
import m.comet.utils.ServiceCall;
import csip.annotations.Description;
import csip.annotations.Name;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 * COMET-03: Get Climate Data for Display in CDSI Application
 *
 * @author rumpal
 * @version 1.0
 */
@Name("COMET-03:  Get Climate Data for Display in CDSI Application")
@Description("This service fetches climate data from NRCS PRISM deployed "
        + "to the agency data center for display in a CDSI application, "
        + "such as the Conservation Desktop.")
@Path("m/comet/cometcliparams/1.0")
@Polling(first = 10000, next = 2000)
@Deprecated
public class V1_0 extends ModelDataService {

    private static final String[] MONTH_NAME_LIST = {"January", "February", "March", "April", "May",
        "June", "July", "August", "September", "October", "November", "December"};

    private double latitude, longitude;

    private Result[] monthlyResult;
    private Result annualResult;

    @Override
    public void preProcess() throws ServiceException, JSONException {
        latitude = parameter().getParamJSON("aoa_centroid").getDouble("latitude");
        longitude = parameter().getParamJSON("aoa_centroid").getDouble("longitude");
    }

    @Override
    public void doProcess() throws ServiceException, JSONException {
        String prismNormals = Config.getString("prism.normals.uri");

        JSONObject request = generatePrismRequest();
        JSONObject result = new ServiceCall().getResult(prismNormals, request);
        parsePrismResponse(result);
    }

    @Override
    public void postProcess() throws ServiceException, JSONException {
        results().put("30yr_normal_annual_precip", annualResult.precipitation);
        results().put("30yr_normal_annual_min_temp", annualResult.minTemperature);
        results().put("30yr_normal_annual_max_temp", annualResult.maxTemprature);

        JSONArray monthlyArray = new JSONArray();
        for (int i = 0; i < monthlyResult.length; i++) {
            JSONArray monthlyArr = new JSONArray();
            monthlyArr.put(JSONUtils.data("Month", MONTH_NAME_LIST[i]));
            monthlyArr.put(JSONUtils.data("30yr_normal_monthly_precip", monthlyResult[i].precipitation));
            monthlyArr.put(JSONUtils.data("30yr_normal_monthly_tmin", monthlyResult[i].minTemperature));
            monthlyArr.put(JSONUtils.data("30yr_normal_monthly_tmax", monthlyResult[i].maxTemprature));
            monthlyArray.put(monthlyArr);
        }
        results().put("30yr Normal Monthly Data", monthlyArray);
    }

    public void parsePrismResponse(JSONObject result) throws ServiceException, JSONException {
        monthlyResult = new Result[12];

        JSONObject metaInfoObject = result.getJSONObject("metainfo");
        String metaError = metaInfoObject.optString("error");

        if ((null == metaError) || (metaError.isEmpty())) {
            JSONArray resultArray = result.getJSONArray("result");
            Map<String, JSONObject> topLevel = JSONUtils.preprocess(resultArray);

            JSONArray periodsArray = JSONUtils.getJSONArrayParam(topLevel, "features").getJSONObject(0).getJSONArray("periods");
            for (int i = 0; i < periodsArray.length(); i++) {
                JSONObject thisperiod = periodsArray.getJSONObject(i);
                int period = thisperiod.getInt("period");
                double precip = thisperiod.getDouble("ppt");
                double minTemp = thisperiod.getDouble("tmin");
                double maxTemp = thisperiod.getDouble("tmax");

                if (period >= 1 && period <= 12) {
                    monthlyResult[period - 1] = new Result(precip, minTemp, maxTemp);
                } else if (period == 13) {
                    annualResult = new Result(precip, minTemp, maxTemp);
                }
            }
        }

    }

    public JSONObject generatePrismRequest() throws JSONException {
        //Request
        JSONObject requestJSON = new JSONObject();

        //Metainfo
        JSONObject metainfo = new JSONObject();
        requestJSON.put("metainfo", metainfo);

        //Parameter
        //Adding FeatureCollection to the request array
        JSONArray parameter = new JSONArray();
        parameter.put(JSONUtils.data("input_zone_features", COMETools.createFeatureCollection(latitude, longitude)));
        requestJSON.put("parameter", parameter);

        return requestJSON;
    }

    public class Result {

        protected double precipitation;
        protected double minTemperature;
        protected double maxTemprature;

        public Result(double precip, double minTemperature, double maxTemprature) {
            this.precipitation = precip;
            this.minTemperature = minTemperature;
            this.maxTemprature = maxTemprature;
        }
    }

}