V1_0.java [src/java/d/cities/extent] Revision: default  Date:
package d.cities.extent;

import csip.ModelDataService;
import csip.api.server.PayloadParameter;
import csip.api.server.PayloadResults;
import csip.api.server.ServiceException;
import csip.annotations.Description;
import csip.annotations.Name;
import csip.annotations.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import javax.ws.rs.Path;
import cities.utils.DBResources;
import cities.utils.PostgresqlLocationsDatabase;
import m.utils.GeoJSON;
import m.utils.Table;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

/**
* Last Updated: 21-June-2019
* @author Tyler Wible
* @since 30-August-2016
*/
@Name("Cities extent")
@Description("Retrieve 2010 U.S. Census 'Incorporated Places' polygon information for Cities that intersect a given extent")
@Path("d/cities/extent/1.0")
@Resource(from = DBResources.class)
public class V1_0 extends ModelDataService {

    protected PostgresqlLocationsDatabase db;
    protected JSONObject geojson;
    protected JSONArray result;
    
    @Override
    protected void preProcess() throws Exception {
        PayloadParameter inputPayload = parameter();
        geojson = inputPayload.getJSON("boundary");
    }

    @Override
    protected void doProcess() throws Exception {
        result = new JSONArray();
        try (Connection c = resources().getJDBC(DBResources.cities_ID)) {
            db = new PostgresqlLocationsDatabase(c);
            GeoJSON boundary = new GeoJSON(geojson, db);
            
            if (boundary.size() > 0) {
                Table tbl = db.getLocations("public", "city_extents", boundary.get(0));
                JSONObject table = db.toJSON(tbl);
                result.put(table.getJSONArray("rows"));
            }
        } catch (SQLException | ServiceException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }


    @Override
    protected void postProcess() throws Exception {
        PayloadResults resultPayload = results();
        resultPayload.put("result", result);
    }

}