V1_0.java [src/java/m/wqm/wqsr] Revision: 622683f6281d92a3770add4259c860b38cbadb3e  Date: Wed Apr 20 23:01:59 MDT 2016
/*
 * 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.wqm.wqsr;

import csip.ModelDataService;
import csip.ServiceException;
import csip.annotations.Resource;
import csip.utils.JSONUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Path;
import oms3.annotations.Description;
import oms3.annotations.Name;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import wqm.utils.DBResources;
import static wqm.utils.DBResources.SSURGO_ID;

/**
 * WQM-01: Water Quality Sensitivity Rating (WQSR)
 *
 * @author Sandeep, od
 */
@Name("WQM-01: Water Quality Sensitivity Rating (WQSR)")
@Description("This service intersects area of analysis (AoA) geometry with the NRCS Water Quality "
        + "Sensitivity Rating (WQSR) spatial layer and computes a sensitivity rating and treatment "
        + "level required for mitigating nutrient and pesticide loss potentials and hazards.")
@Path("m/wqm/wqsr/1.0")
@Resource(from = DBResources.class)
public class V1_0 extends ModelDataService {

    List<AoA> list = new ArrayList<>();

    @Override
    public void preProcess() throws ServiceException, JSONException {
        JSONArray aoaArr = getJSONArrayParam("aoas");
        for (int i = 0; i < aoaArr.length(); i++) {
            //Map individual JSONObject & extract values
            Map<String, JSONObject> thisAoA = JSONUtils.preprocess(aoaArr.getJSONArray(i));
            String aoaId = JSONUtils.getStringParam(thisAoA, "aoa_id", "unknown");
            JSONArray polygon = JSONUtils.getJSONArrayParam(thisAoA, "aoa_geometry");
            JSONArray coordinates = polygon.getJSONArray(0);
            String points = coordinates.toString();

            // Getting the array of coordinates and converting to a form that can be used in the query for intersection
            points = points.replace("[", "");
            points = points.replace("]", "");
            points = points.replace(",", " ");
            String temp[] = points.split(" ");
            String finalpoints = temp[0];
            for (int j = 1; j < temp.length; j++) {
                if (j % 2 == 0) {
                    finalpoints += "," + temp[j];
                } else {
                    finalpoints += " " + temp[j];
                }
            }
            list.add(new V1_0.AoA(aoaId, finalpoints));
        }
    }

    @Override
    public void doProcess() throws ServiceException, SQLException {
        try (Connection tempCon = getResourceJDBC(SSURGO_ID);
             Statement stmt = tempCon.createStatement()) {
          
                for (AoA aoa : list) {
                    double aoaBaseArea = 0.0;
                    double aoaSensitiveArea = 0.0;
                    double aoaCriticalArea = 0.0;
                    //Query to select the area,rating and treatment level 
                    // which given coordinates intersects wqsr_area geometry
                    try (ResultSet results = stmt.executeQuery("select shape_area,wqs_rating from wqm_huc12.wqsr_area WHERE ST_Intersects('POLYGON(("
                            + aoa.getCoordinates() + "))'::geography::geometry, geom)")) {
                        while (results.next()) {
                            String wqsRating = results.getString("wqs_rating");
                            double shape_area = results.getDouble("shape_area");
                            if (wqsRating.equalsIgnoreCase("base")) {
                                aoaBaseArea += shape_area;
                            } else if (wqsRating.equalsIgnoreCase("sensitive")) {
                                aoaSensitiveArea += shape_area;
                            } else if (wqsRating.equalsIgnoreCase("critical")) {
                                aoaCriticalArea += shape_area;
                            }
                        }
                    }

                    if ((aoaBaseArea >= aoaSensitiveArea) && (aoaBaseArea >= aoaCriticalArea)) {
                        aoa.setWQSRating("Base");
                        aoa.setTreatmentLevel("I");
                    } else if ((aoaSensitiveArea >= aoaBaseArea) && (aoaSensitiveArea >= aoaCriticalArea)) {
                        aoa.setWQSRating("Sensitive");
                        aoa.setTreatmentLevel("II");
                    } else {
                        aoa.setWQSRating("Critical");
                        aoa.setTreatmentLevel("III");
                    }
                }
            }
         catch (Exception e) {
            LOG.info(e.toString());
            throw new ServiceException(e);
        }
       
    }

    @Override
    public void postProcess() throws JSONException {
        JSONArray finalArr = new JSONArray();
        for (AoA aoa : list) {
            JSONArray resultArr = new JSONArray();
            resultArr.put(JSONUtils.dataDesc("AoAId", aoa.getAoAId(), "Area of Analysis Identifier"));
            resultArr.put(JSONUtils.dataDesc("wqs_Rating", aoa.getWQSRating(), "WQS Rating"));
            resultArr.put(JSONUtils.dataDesc("wqs_treatment_level", aoa.getTreatmentLevel(), "WQS Treatment Level"));
            finalArr.put(resultArr);
        }
        putResult("", finalArr);
    }

    public class AoA {

        String aoa_id;
        String polygonCoordinates;
        String wqsRating;
        String treatmentLevel;

        public AoA(String aoa_id, String coordinates) {
            this.aoa_id = aoa_id;
            this.polygonCoordinates = coordinates;
        }

        public String getAoAId() {
            return aoa_id;
        }

        public String getWQSRating() {
            return wqsRating;
        }

        public String getTreatmentLevel() {
            return treatmentLevel;
        }

        public String getCoordinates() {
            return polygonCoordinates;
        }

        public void setWQSRating(String wqs) {
            this.wqsRating = wqs;
        }

        public void setTreatmentLevel(String level) {
            this.treatmentLevel = level;
        }
    }

}