V2_0.java [src/java/d/crlmod/operation] Revision: default  Date:
/*
 * $Id: 1.0+69 V2_0.java 68122e0cd0dd 2023-02-02 casesp $
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API, and application suite.
 *
 * 2012-2024, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package d.crlmod.operation;

import crlmod.LMODData;
import crlmod.ServiceResources;
import static crlmod.ServiceResources.*;
import crlmod.nodes.Operation;
import crlmod.utils.Utils;
import csip.ModelDataService;
import csip.api.server.ServiceException;
import csip.annotations.*;
import static csip.annotations.State.RELEASED;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Path;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author User
 */
@Name("operations")
@Description("Operation service for the CRLMOD_2018 Database.  Results from this service are returned in the rotation v1 format.")
@VersionInfo("2.0")
@State(RELEASED)
@Path("d/operation/2.0")
@Resource(from = ServiceResources.class)
public class V2_0 extends ModelDataService {

  LMODData lmodData = new LMODData();

  private final String OBJECT_PREFIX = "op";
  private final String OBJECT_NAME = "Operation";
  private boolean nativeFormats = false;
  private boolean namesOnly = false;

  @Override
  protected void doProcess() throws Exception {
    //does the user want just names?
    namesOnly = parameter().getBoolean(KEY_NAMESONLY, false);
    //does the user want param_sets, or just base data?
    nativeFormats = parameter().getBoolean(KEY_NATIVEFORMATS, false);
    getOperations();
  }

  @Override
  protected void postProcess() throws Exception {
    if (namesOnly) {
      for (Operation op : lmodData.operations) {
        op.id = null;
        op.stir = null;
        op.add_residue = null;
        op.begin_growth = null;
        op.kill_crop = null;
      }
    }
    results().put("crlmod", lmodData.getJson());
  }

  private void getOperations() throws Exception {
    List<String> params = new ArrayList<>();
    String query = "SELECT op_id, op_name, op_group1, op_group2, op_group3, op_group4, op_group5, \n"
        + "op_begin_growth, op_kill_crop, op_add_residue, op_stir, op_res_added, op_notes, \n"
        + "weps_op_param_set, wepp_op_param_set\n"
        + "FROM operations \n"
        + "     LEFT JOIN weps_ops on (fk_weps_op_id = weps_op_id)\n"
        + "     LEFT JOIN wepp_ops on (fk_wepp_op_id = wepp_op_id)\n";

    query += Utils.createWhere(params, OBJECT_PREFIX, OBJECT_NAME, parameter(), LOG);

    String countQuery = "SELECT Count(*) AS 'Count' \n"
        + "FROM operations \n";
    countQuery += Utils.createWhere(new ArrayList<String>(), OBJECT_PREFIX, OBJECT_NAME, parameter(), LOG);
    System.out.println(query);

    try (Connection connection = resources().getJDBC(getJDBCId())) {
      try (Statement statement = connection.createStatement()) {
        try (ResultSet resultSet = statement.executeQuery(countQuery)) {
          resultSet.next();
          lmodData.operationCount = resultSet.getInt("Count");
        }

        query += Utils.createOffsetAndLimits(params, parameter(), LOG, OBJECT_NAME, OBJECT_PREFIX);

        try (ResultSet resultSet = statement.executeQuery(query)) {
          if (!resultSet.next()) {
            String errors = "";
            errors = "No operations found with ";
            for (int i = 0; i < params.size(); i++) {
              errors += params.get(i);
              if (i < params.size() - 1) {
                errors += "and ";
              }
            }
            throw new ServiceException(errors);
          }
          do {
            BigDecimal op_id = resultSet.getBigDecimal("op_id");
            String op_name = resultSet.getString("op_name");
            String op_group1 = StringUtils.isEmpty(resultSet.getString("op_group1")) ? null : resultSet.getString("op_group1");
            String op_group2 = StringUtils.isEmpty(resultSet.getString("op_group2")) ? null : resultSet.getString("op_group2");
            String op_group3 = StringUtils.isEmpty(resultSet.getString("op_group3")) ? null : resultSet.getString("op_group3");
            String op_group4 = StringUtils.isEmpty(resultSet.getString("op_group4")) ? null : resultSet.getString("op_group4");
            String op_group5 = StringUtils.isEmpty(resultSet.getString("op_group5")) ? null : resultSet.getString("op_group5");
            String op_notes = StringUtils.isEmpty(resultSet.getString("op_notes")) ? null : resultSet.getString("op_notes");

            boolean begin_growth = resultSet.getBoolean("op_begin_growth");
            boolean add_residue = resultSet.getBoolean("op_add_residue");
            boolean kill_crop = resultSet.getBoolean("op_kill_crop");
            double stir = resultSet.getDouble("op_stir");
            double res_added = resultSet.getDouble("op_res_added");

            String weps_param_set = resultSet.getString("weps_op_param_set");
            String wepp_param_set = resultSet.getString("wepp_op_param_set");

            if (weps_param_set == null) {
              weps_param_set = "No matching WEPS data is available at this time";
            }
            if (wepp_param_set == null) {
              wepp_param_set = "No matching WEPP data is available at this time";
            }

            weps_param_set = filterXML(weps_param_set);
            wepp_param_set = filterXML(wepp_param_set);

//            weps_param_set = weps_param_set.replaceAll("\n", "").replaceAll("\t", "");
//            wepp_param_set = wepp_param_set.replaceAll("\n", "").replaceAll("\t", "");
            Operation op = new Operation(op_id.toBigInteger(), op_name);
            //Strings
            op.opGroup1 = op_group1;
            op.opGroup2 = op_group2;
            op.opGroup3 = op_group3;
            op.opGroup4 = op_group4;
            op.opGroup5 = op_group5;
            op.opNotes = op_notes;

            //Booleans
            op.begin_growth = begin_growth;
            op.add_residue = add_residue;
            op.kill_crop = kill_crop;

            //Doubles
            op.stir = stir;
            op.resAdded = res_added;

            if (nativeFormats) {
              op.wepsOpParamSet = weps_param_set;
              op.weppOpParamSet = wepp_param_set;
            }
            lmodData.addOperation(op);
          } while (resultSet.next());
        }
        statement.clearBatch();
      }
    }
  }

  /**
   * This filter was required in order to attempt to fix non UTF-8 encoded XML
   * data provided by ARS.
   *
   * @param value
   * @return
   */
  protected String filterXML(String value) {
    return value.replaceAll("\n", "").replaceAll("\t", "");
  }

  protected String getJDBCId() {
    return CR_LMOD_2018_ID;
  }

  @Override
  protected Map<String, Object> getConfigInfo() {
    return new LinkedHashMap<String, Object>() {
      {
        put(getJDBCId(), resources().getResolved(getJDBCId()));
      }
    };
  }

}