V2_0.java [src/java/d/crlmod/operationImport] Revision: default  Date:
/*
 *
 * 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.operationImport;

import crlmod.ServiceResources;
import static crlmod.ServiceResources.*;
import csip.ModelDataService;
import csip.annotations.*;
import csip.api.server.ServiceException;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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.io.FileUtils;

@Name("operations Import")
@Description("Operation import service for the CRLMOD_2018 database")
@VersionInfo("2.0")
@Path("d/operationImport/2.0")
@Resource(from = ServiceResources.class)
public class V2_0 extends ModelDataService {

  private int rowsAffected = -1;

  @Override
  protected void doProcess() throws Exception {
    String sourceModel = parameter().getString("source_model");
    if (sourceModel.equalsIgnoreCase("weps")) {
      importWeps();
    } else if (sourceModel.equalsIgnoreCase("wepp")) {
      importWepp();
    } else {
      throw new ServiceException("required input missing 'source_model' must be included in your json.");
    }
  }

  @Override
  protected void postProcess() throws Exception {
    results().put("rowsAffected", rowsAffected);
  }

  private void importWeps() throws Exception {
    File[] unZippedFiles = null;
    File unzipDir = new File(workspace().getDir() + File.separator + "WEPSOperations");
    if (unzipDir.canRead()) {
      unZippedFiles = unzipDir.listFiles();
    }
    //Read into weps_op object
    List<Op> wepsOps = getOpsFromFiles(unZippedFiles);

//    String query = "INSERT INTO weps_ops (weps_op_path, weps_op_name, weps_op_param_set) "
//        + "VALUES (?,?,?)";
    String query = "UPDATE weps_ops SET weps_op_param_set=? WHERE weps_op_path=? AND weps_op_name=?;";

    try (Connection connection = resources().getJDBC(getJDBCId())) {
      try (PreparedStatement statement = connection.prepareStatement(query)) {
        for (int i = 0; i < wepsOps.size(); i++) {
          statement.setString(1, wepsOps.get(i).op_param_set);
          statement.setString(2, wepsOps.get(i).op_path);
          statement.setString(3, wepsOps.get(i).op_name);

          statement.addBatch();
        }
        connection.setAutoCommit(false);
        try {
          int[] rowResults = statement.executeBatch();
          for (int i = 0; i < rowResults.length; i++) {
            if (rowResults[i] < 0) {
              connection.rollback();
              throw new SQLException("Not all WEPS operation insert operations succeeded.");
            }
          }
          connection.commit();
          rowsAffected = rowResults.length;
        } catch (SQLException ex) {
          connection.rollback();
          throw ex;
        }
      }
    }
  }

  private void importWepp() throws Exception {
    File[] unZippedFiles = null;
    File unzipDir = new File(workspace().getDir() + File.separator + "WEPPOperations");
    if (unzipDir.canRead()) {
      unZippedFiles = unzipDir.listFiles();
    }
    //Read into wepp_op object
    List<Op> weppOps = getOpsFromFiles(unZippedFiles);

//    String query = "INSERT INTO wepp_ops (wepp_op_path, wepp_op_name, wepp_op_param_set) "
//        + "VALUES (?,?,?)";
    String query = "UPDATE wepp_ops SET wepp_op_param_set=? WHERE wepp_op_path=? AND wepp_op_name=?; "
        + "VALUES (?,?,?)";

    try (Connection connection = resources().getJDBC(getJDBCId())) {
      try (PreparedStatement statement = connection.prepareStatement(query)) {
        for (int i = 0; i < weppOps.size(); i++) {
          statement.setString(1, weppOps.get(i).op_param_set);
          statement.setString(2, weppOps.get(i).op_path);
          statement.setString(3, weppOps.get(i).op_name);

          statement.addBatch();
        }
        connection.setAutoCommit(false);
        try {
          int[] rowResults = statement.executeBatch();
          for (int i = 0; i < rowResults.length; i++) {
            if (rowResults[i] < 0) {
              connection.rollback();
              throw new SQLException("Not all WEPP Operation insert operations succeeded.");
            }
          }
          connection.commit();
          rowsAffected = rowResults.length;
        } catch (SQLException ex) {
          connection.rollback();
          throw ex;
        }
      }
    }
  }

  public List<Op> getOpsFromFiles(File[] opFiles) throws IOException {
    String path = "";
    List<Op> ops = new ArrayList<>();
    if (null != opFiles && opFiles.length > 0) {
      path = opFiles[0].getParent().replace(workspace().getDir().getPath(), "");
    }

    //Get the path...so complicated.
    if (path.indexOf(File.separator, 2) != -1) {
      path = path.substring(path.indexOf(File.separator, 2) + 1);
    } else {
      path = "";
    }

    for (int i = 0; i < opFiles.length; ++i) {
      if (opFiles[i].isDirectory() && !opFiles[i].getName().startsWith(".")) {
        ops.addAll(getOpsFromFiles(opFiles[i].listFiles()));
      } else if (!opFiles[i].isDirectory() && !opFiles[i].getName().startsWith("_")) {
        Op op = new Op();
        op.op_path = path;
        op.op_name = opFiles[i].getName().substring(0, opFiles[i].getName().lastIndexOf(".oprn"));
        op.op_param_set = FileUtils.readFileToString(opFiles[i], "UTF-8");
        System.out.println("Processed: [" + path + File.separator + op.op_name + "]");
        ops.add(op);
      }
    }
    return ops;
  }

  protected String getJDBCId() {
    return CR_LMOD_2018_ID;
  }

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