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

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.Layer;
import org.codehaus.jettison.json.JSONObject;

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

    protected PostgresqlLocationsDatabase db;
    protected int id;
    protected String city;
    protected JSONObject result;
    
    @Override
    protected void preProcess() throws Exception {
        PayloadParameter inputPayload = parameter();
        id = inputPayload.getInt("oid", -1);
        if (id > 0) { 
            // we should be able to look it up by id
        } else {
            // Try name
            city = inputPayload.getString("name");
        }
    }

    @Override
    protected void doProcess() throws Exception {
        result = new JSONObject();
        try (Connection c = resources().getJDBC(DBResources.cities_ID)) {
            db = new PostgresqlLocationsDatabase(c);
            
            Layer lyr;
            if (id > 0) { 
                lyr = db.getLocation("public", "city_extents", id);
            } else {
                // Try name
                lyr = db.getLocationString("public", "city_extents", "name", city);
            }
            result = db.toJSON(lyr);
        } 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);
    }
}