V1_0.java [src/java/m/wqm/wqm12_rfactor] Revision:   Date:
package m.wqm.wqm12_rfactor;

import csip.ModelDataService;
import csip.api.server.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.Collections;
import java.util.Map;
import java.util.logging.Level;
import javax.ws.rs.Path;
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;
import wqm.utils.DBQueries;
import wqm.utils.DBResources;
import static wqm.utils.DBResources.WQM_ID;

/**
 *
 * @author Sandeep
 * @author Shaun Case
 */
@Deprecated
@Name("WQM-12: Climate R Factor for an Area of Analysis (AoARFactor)")
@Description("This service intersects an area of analysis (AoA) with the "
        + "Revised Universal Soil Loss Equation (RUSLE2) climate R Factor layer "
        + "and computes an R Factor representing the AoA.")
@Path("m/wqm/rfactor/1.0")
@Resource(from = DBResources.class)

public class V1_0 extends ModelDataService {

    private String error_msg;
    private ArrayList<m.wqm.wqm12_rfactor.V1_0.AoA> list;

    @Override
    public void preProcess() throws ServiceException {
        this.error_msg = "";
        String points;
        String finalpoints;
        JSONArray aoaArr;
        String aoaId;
        JSONArray polygon, coordinates;

        try {
            this.list = new ArrayList<>();

            aoaArr = parameter().getJSONArray("aoas");

            for (int i = 0; i < aoaArr.length(); i++) {
                //Map individual JSONObject & extract values
                Map<String, JSONObject> thisAoA = JSONUtils.preprocess(aoaArr.getJSONArray(i));
                aoaId = JSONUtils.getStringParam(thisAoA, "aoa_id", "unknown");
                polygon = JSONUtils.getJSONArrayParam(thisAoA, "aoa_geometry");
                coordinates = polygon.getJSONArray(0);
                points = coordinates.toString();
                points = points.replace("[", "");
                points = points.replace("]", "");
                points = points.replace(",", " ");
                String temp[] = points.split(" ");
                finalpoints = "";
                finalpoints += temp[0];
                for (int j = 1; j < temp.length; j++) {
                    if (j % 2 == 0) {
                        finalpoints += "," + temp[j];
                    } else {
                        finalpoints += " " + temp[j];
                    }
                }
                this.list.add(new AoA(aoaId, finalpoints));
            }
        } catch (ServiceException | JSONException ex) {
            LOG.log(Level.SEVERE, "Error in processing the request JSON for WQM-12!", ex);
            throw new ServiceException("Error in processing the request JSON.", ex);
        }
    }

    @Override
    public void doProcess() throws ServiceException {
        String rFactor;
        ArrayList<String> rfactorList = new ArrayList<>();

        if (this.error_msg.isEmpty()) {
            try (Connection conn = resources().getJDBC(WQM_ID);
                    Statement statement = conn.createStatement()) {

                for (m.wqm.wqm12_rfactor.V1_0.AoA list1 : this.list) {
                    String tPoints = list1.getCoordinates();

                    /*String gisQuery = "SELECT TOP 1 m.co_fips, r2_path, r2_name, r_factor, g.geometry "
                            + "FROM r2gis.map_climates AS m, r2gis.cli_geom AS g "
                            + "WITH (Index(cli_geom_idx)) "
                            + "WHERE "
                            + "g.geometry.STIntersects(geometry::STPolyFromText('POLYGON((" + tPoints + "))',0)) = 1 "
                            + "AND ((g.co_fips = m.co_fips and g.geometry.STIsValid()=1 and m.ei_rang is null) "
                            + "or (g.co_fips = m.co_fips and g.ei_rang = m.ei_rang and m.ei_rang is not null and g.geometry.STIsValid()=1)) "
                            + "and g.geometry.STIsValid()=1 and geometry::STPolyFromText('POLYGON((" + tPoints + "))',0).STIsValid()=1;";
                    */
                    //LOG.info("RFACTOR SQL=" + gisQuery);
                    ResultSet results = statement.executeQuery(DBQueries.WQM12Query(tPoints));
                    while (results.next()) {
                        rFactor = results.getString("r_factor");

                        if (null != rFactor) {
                            rfactorList.add(rFactor);
                        } else {
                            break;
                        }
                    }

                    if (!this.error_msg.isEmpty()) {
                        break;
                    }

                    if (rfactorList.size() > 0) {
                        list1.setRFactor(rfactorList);
                    }
                }
            } catch (ServiceException | SQLException ex) {
                LOG.log(Level.SEVERE, "SQL problem for WQM-12!", ex);
                throw new ServiceException("SQL problem", ex);
            }
        }
    }

    @Override
    public void postProcess() throws Exception {
        ArrayList<Double> temp;
        try {
            if (this.error_msg.isEmpty()) {
                JSONArray finalArr = new JSONArray();
                for (m.wqm.wqm12_rfactor.V1_0.AoA list1 : this.list) {
                    JSONArray resultArr = new JSONArray();
                    temp = new ArrayList<>();
                    for (int j = 0; j < list1.getRFactor().size(); j++) {
                        temp.add(Double.parseDouble(list1.getRFactor().get(j)));
                    }

                    resultArr.put(JSONUtils.dataDesc("AoAId", list1.getAoAId(), "Area of Analysis Identifier"));

                    if (temp.size() > 0) {
                        Collections.sort(temp);
                        resultArr.put(JSONUtils.dataDesc("RFactor", temp.get(temp.size() - 1), "R Factor"));
                    } else {
                        resultArr.put(JSONUtils.dataDesc("RFactor", "No polygon intersection found", "R Factor"));
                    }

                    finalArr.put(resultArr);
                }
                results().put("", finalArr);
            }
        } catch (NumberFormatException | JSONException ex) {
            LOG.log(Level.SEVERE, "Error in processing the response JSON for WQM-12!", ex);
            throw new ServiceException("Error in processing the response JSON.", ex);
        }
    }

// rFactor now coming from map_climates table
//    private String getAndProcessXml(String url) {
//        String ret_val = null;
//
//        try {
//            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//            DocumentBuilder db = dbf.newDocumentBuilder();
//
//            URL Url = new URL(url);
//            URLConnection urlConnection = Url.openConnection();
//            Document document = db.parse(urlConnection.getInputStream());
//            document.getDocumentElement().normalize();
//            Element root = document.getDocumentElement();
//            NodeList nList = document.getElementsByTagName("Flt");
//
//            for (int temp = 0; temp < nList.getLength(); temp++) {
//                Node node = nList.item(temp);
//
//                if (node.getNodeType() == Node.ELEMENT_NODE) {
//                    Element eElement = (Element) node;
//                    String Name = eElement.getElementsByTagName("Name").item(0).getTextContent();
//                    if (Name.equals("R_FACTOR")) {
//                        ret_val = eElement.getElementsByTagName("Data").item(0).getTextContent();
//                    }
//                }
//            }
//        } catch (ParserConfigurationException | IOException | SAXException | DOMException ex) {
//            this.error_msg = "Cannot parse the returned XML: " + ex.getMessage();
//            LOG.log(Level.SEVERE, this.error_msg);
//        }
//
//        return ret_val;
//    }
    static class AoA {

        private final String aoa_id;
        private final String polygonCoordinates;
        private ArrayList<String> rfactor;

        /**
         *
         * @param aoa_id
         * @param coordinates
         */
        public AoA(String aoa_id, String coordinates) {
            this.aoa_id = aoa_id;
            this.polygonCoordinates = coordinates;
            rfactor = new ArrayList<>();
        }

        /**
         *
         * @return
         */
        public String getAoAId() {
            return aoa_id;
        }

        /**
         *
         * @return
         */
        public ArrayList<String> getRFactor() {
            return rfactor;
        }

        /**
         *
         * @param rf
         */
        public void setRFactor(ArrayList<String> rf) {
            this.rfactor = rf;
        }

        /**
         *
         * @return
         */
        public String getCoordinates() {
            return polygonCoordinates;
        }

    }
}