V1_0.java [src/java/d/states/extent] Revision: default  Date:
package d.states.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("States extent")
@Description("Retrieve 2010 U.S. Census polygon information for states that intersect a given extent")
@Path("d/states/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);
            
            // Fix null properties
            if (boundary.size() > 0) {
                Table tbl = db.getLocations("census", "tl_2010_us_state10", boundary.get(0));
                JSONObject table = db.toJSON(tbl);
                result.put(table.getJSONArray("rows"));
            }
        } catch (SQLException | ServiceException ex) {
            LOG.log(Level.SEVERE, null, ex);
            throw new ServiceException(ex);
        }
    }


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

}