V1_1.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.api.server.ServiceException;
import csip.annotations.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.ws.rs.Path;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.codehaus.jettison.json.JSONException;

@Name("operations Import")
@Description("Operation import service for the CRLMOD Database")
@VersionInfo("1.1")
@Path("d/operationImport/1.1")
@Resource(from = ServiceResources.class)
public class V1_1 extends ModelDataService {

  private int rowsAffected = -1;

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

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

  private String importWeps() throws JSONException, SQLException, ServiceException, IOException {
    ArrayList<String> params = new ArrayList<>();
    File zipFile = attachments().getFile("WEPSOps.zip");
    File unzipDir = workspace().getFile("WEPPOperations");

    File[] unZippedFiles = unzipDir.listFiles();
    //Read into weps_op object
    ArrayList<Op> wepsOps = getOpsFromFiles(unZippedFiles);

    String query = "INSERT INTO weps_ops(weps_op_path, weps_op_name, weps_op_param_set)\n"
        + "VALUES\n";
    for (int i = 0; i < wepsOps.size(); ++i) {
      query += "\n('" + wepsOps.get(i).op_path + "','"
          + wepsOps.get(i).op_name + "', '"
          + wepsOps.get(i).op_param_set.replaceAll("'", "''") + "')";
      if (i != wepsOps.size() - 1)
        query += ",";
      else
        query += ";";
    }

    try (Connection connection = resources().getJDBC(getJDBCId())) {
      try (Statement statement = connection.createStatement()) {
        connection.setAutoCommit(false);
        rowsAffected = statement.executeUpdate(query);
        connection.commit();
        statement.clearBatch();
        statement.close();
        connection.close();
      }
    }
    return null;
  }

  private String importWepp() throws JSONException, SQLException, ServiceException, IOException {
    ArrayList<String> params = new ArrayList<>();
    File unzipDir = workspace().getFile("WEPPOperations");

    File[] unZippedFiles = unzipDir.listFiles();
    //Read into wepp_op object
    ArrayList<Op> weppOps = getOpsFromFiles(unZippedFiles);

    String query = "INSERT INTO wepp_ops(wepp_op_path, wepp_op_name, wepp_op_param_set)\n"
        + "VALUES\n";
    for (int i = 0; i < weppOps.size(); ++i) {
      query += "\n('" + weppOps.get(i).op_path + "','"
          + weppOps.get(i).op_name + "', '"
          + weppOps.get(i).op_param_set.replaceAll("'", "''") + "')";
      if (i != weppOps.size() - 1)
        query += ",";
      else
        query += ";";
    }

    try (Connection connection = resources().getJDBC(getJDBCId())) {
      try (Statement statement = connection.createStatement()) {
        connection.setAutoCommit(false);
        rowsAffected = statement.executeUpdate(query);
        connection.commit();
        statement.clearBatch();
        statement.close();
        connection.close();
      }
    }
    return null;
  }

  public ArrayList<Op> getOpsFromFiles(File[] opFiles) throws IOException {
    ArrayList<Op> ops = new ArrayList<Op>();
    String basePath = workspace().getDir().getAbsolutePath();

    for (int i = 0; i < opFiles.length; ++i) {
      if (opFiles[i].isDirectory()) {
        ops.addAll(getOpsFromFiles(opFiles[i].listFiles()));
      } else {
        Op op = new Op();
        String path = opFiles[i].getParent().replace(basePath, "");
        if (path.indexOf("\\", 2) != -1) {
          path = path.substring(path.indexOf("\\", 2) + 1);
        } else {
          path = "";
        }
        System.out.println("[" + path + "]");
        op.op_path = path;
        op.op_name = FilenameUtils.getBaseName(opFiles[i].getName());
        op.op_param_set = FileUtils.readFileToString(opFiles[i], "UTF-8");
        ops.add(op);
      }
    }
    return ops;
  }

  protected String getJDBCId() {
    return CR_LMOD_ID;
  }

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