V1_0.java [src/java/d/huc/geometry] Revision: default  Date:
package d.huc.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 huc.utils.DBResources;
import huc.utils.PostgresqlHUCDatabase;
import m.utils.Layer;
import org.codehaus.jettison.json.JSONObject;

/**
 * Last Updated: 21-June-2019
 * @author ktraff
 */
@Name("HUC geometry")
@Description("Retrieve HUC polygon geometries for HUCs that match a given ID")
@Path("d/huc/geometry/1.0")
@Resource(from = DBResources.class)
public class V1_0 extends ModelDataService {

    protected PostgresqlHUCDatabase db;
    protected int hucLevel;
    protected String id;
    protected JSONObject result;
    
    @Override
    protected void preProcess() throws Exception {
        PayloadParameter inputPayload = parameter();
        int hucParam = inputPayload.getInt("huc", 12);
        hucLevel = 12;
        for (int i : new int[]{2,4,6,8,10,12,14}) {
            if (hucParam == i) hucLevel = hucParam;
        }
        id = inputPayload.getString("id", "0");
    }

    @Override
    protected void doProcess() throws Exception {
        result = new JSONObject();
        try (Connection c = resources().getJDBC(DBResources.HUC_ID)) {
            db = new PostgresqlHUCDatabase(c);
            Layer lyr = db.getHUC(id, hucLevel);
            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);
    }
}