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

import csip.Config;
import csip.ModelDataService;
import csip.ServiceException;
import csip.annotations.Polling;
import csip.annotations.Resource;
import static csip.annotations.ResourceType.OUTPUT;
import csip.utils.JSONUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.ws.rs.Path;
import m.comet.utils.ServiceCall;
import m.comet.utils.COMETools;
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-04:  Get Climate Data for the COMET API
 * 
 * @author rumpal
 * @version 1.0
 */
@Name("COMET-04:  Get Climate Data for the COMET API")
@Description("This service generates a daily weather data file for the "
        + "COMET DayCent model from NRCS CDSI PRISM provisioned to the "
        + "agency data center.")
@Path("m/comet/cometcliinput/1.0")
@Polling(first = 10000, next = 2000)
@Resource(file = "*.txt", type = OUTPUT)
@Deprecated
public class V1_0 extends ModelDataService {

    private double latitude, longitude;

    @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, FileNotFoundException, ParseException {
        String prism = Config.getString("prism.uri");

        JSONObject request = createPrismRequest();
        JSONObject result = new ServiceCall().getResult(prism, request);
        parsePrismResponse(result);
    }

    public JSONObject createPrismRequest() 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)));
        parameter.put(JSONUtils.data("units", "metric"));
        parameter.put(JSONUtils.data("start_date", Config.getString("prism.start.date")));
        parameter.put(JSONUtils.data("end_date", Config.getString("prism.end.date")));
        JSONArray data = new JSONArray();
        data.put("tmin");
        data.put("tmax");
        data.put("ppt");
        parameter.put(JSONUtils.data("climate_data", data));
        parameter.put(JSONUtils.data(VALUE, VALUE));
        requestJSON.put("parameter", parameter);

        return requestJSON;
    }

    public void parsePrismResponse(JSONObject result) throws ServiceException, FileNotFoundException, ParseException, JSONException {

        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 data = JSONUtils.getJSONArrayParam(topLevel, "output").getJSONObject(0).getJSONArray("data");

            generateWeatherFile(data);
        }

    }

    public void generateWeatherFile(JSONArray data) throws JSONException, FileNotFoundException, ParseException {
        int dateIndex, tminIndex, tmaxIndex, precipIndex;
        dateIndex = tminIndex = tmaxIndex = precipIndex = -1;

        JSONArray line = data.getJSONArray(0);
        for (int j = 0; j < line.length(); j++) {
            String column = line.getString(j);
            if (column.toLowerCase().contains("date")) {
                dateIndex = j;
            } else if (column.toLowerCase().contains("tmin")) {
                tminIndex = j;
            } else if (column.toLowerCase().contains("tmax")) {
                tmaxIndex = j;
            } else if (column.toLowerCase().contains("ppt")) {
                precipIndex = j;
            }
        }

        DateFormat df = new SimpleDateFormat(Config.getString("prism.date.format"));
        Calendar cal = Calendar.getInstance();

        try (PrintWriter writer = new PrintWriter(new File(getWorkspaceDir(), "DAILY_WEATHER.txt"));) {
            if (dateIndex != -1 && tminIndex != -1 && tmaxIndex != -1 && precipIndex != -1) {
                for (int i = 1; i < data.length(); i++) {
                    line = data.getJSONArray(i);

                    Date today = df.parse(line.getString(dateIndex));
                    cal.setTime(today);

                    writer.print(String.format("%-4s", cal.get(Calendar.DAY_OF_MONTH)));
                    writer.print(String.format("%-4s", cal.get(Calendar.MONTH) + 1));
                    writer.print(String.format("%-6s", cal.get(Calendar.YEAR)));
                    writer.print(String.format("%-6s", cal.get(Calendar.DAY_OF_YEAR)));
                    writer.print(String.format("%-8s", line.getDouble(tmaxIndex)));
                    writer.print(String.format("%-8s", line.getDouble(tminIndex)));
                    writer.print(String.format("%-8s", line.getDouble(precipIndex)));
                    writer.println();
                }
            }
        }
    }

}