V2_0.java [src/java/d/crlmod/residueImport] 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.residueImport;

import crlmod.ServiceResources;
import static crlmod.ServiceResources.CR_LMOD_2018_ID;
import static crlmod.ServiceResources.CR_LMOD_2018_JUNE_ID;
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 java.util.logging.Level;
import javax.ws.rs.Path;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.codehaus.jettison.json.JSONException;

@Name("residue Import")
@Description("Residue import service for the CRLMOD_2018 Database")
@VersionInfo("2.0")
@Path("d/residueImport/2.0")
@Resource(from = ServiceResources.class)
public class V2_0 extends ModelDataService {

  private int rowsAffected = -1;

  @Override
  protected void doProcess() throws Exception {
    String error = null;

    try {
      String sourceModel = parameter().getString("source_model");
      if (sourceModel.equalsIgnoreCase("weps")) {
        error = importWeps();
      } else if (sourceModel.equalsIgnoreCase("wepp")) {
        error = importWepp();
      }
      if (error != null) {
        LOG.log(Level.SEVERE, error);
        throw new ServiceException(error);
      }
    } catch (SQLException | JSONException ex) {
      LOG.log(Level.SEVERE, ex.getMessage(), ex);
      throw new ServiceException(ex);
    }
  }

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

  private String importWeps() throws Exception {
    File unzipDir = workspace().getFile("WEPSResidues");
    File[] unZippedFiles = unzipDir.listFiles();
    //Read into weps_op object
    ArrayList<Res> wepsResidues = getResiduesFromFiles(unZippedFiles);

    String query = "INSERT INTO weps_residues (weps_res_path, weps_res_name, weps_res_param_set)\n"
        + "VALUES\n";
    for (int i = 0; i < wepsResidues.size(); ++i) {
      query += "\n('" + wepsResidues.get(i).res_path + "', '"
          + wepsResidues.get(i).res_name + "', '"
          + wepsResidues.get(i).res_param_set
              .replaceAll("'", "''")
              .replaceAll("\r\n", "' + CHAR(13) + CHAR(10) + '") + "')";
      if (i != wepsResidues.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 {
    File unzipDir = workspace().getFile("WEPPResidues");
    File[] unZippedFiles = unzipDir.listFiles();

    //Read into wepp_op object
    ArrayList<Res> weppResidues = getResiduesFromFiles(unZippedFiles);

    String query = "INSERT INTO wepp_residues (wepp_res_path, wepp_res_name, wepp_res_param_set)\n"
        + "VALUES\n";
    for (int i = 0; i < weppResidues.size(); ++i) {
      query += "\n('" + weppResidues.get(i).res_path + "', '"
          + weppResidues.get(i).res_name + "', '"
          + weppResidues.get(i).res_param_set
              .replaceAll("'", "''")
              .replaceAll("\r\n", "' + CHAR(13) + CHAR(10) + '") + "')";
      if (i != weppResidues.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<Res> getResiduesFromFiles(File[] resFiles) throws IOException {
    ArrayList<Res> residues = new ArrayList<>();
    String basePath = workspace().getDir().getAbsolutePath() + "\\WEPSResidues\\";

    for (int i = 0; i < resFiles.length; ++i) {
      if (resFiles[i].isDirectory())
        residues.addAll(getResiduesFromFiles(resFiles[i].listFiles()));
      else {
        Res res = new Res();
        res.res_path = (resFiles[i].getParentFile().getPath() + "\\").replace(basePath, "");
        if (res.res_path.endsWith("\\"))
          res.res_path = res.res_path.substring(0, res.res_path.length() - 1);
        res.res_name = FilenameUtils.getBaseName(resFiles[i].getName());
        res.res_param_set = FileUtils.readFileToString(resFiles[i], "UTF-8");
        //res.res_param_set = Res.res_param_set.replaceAll("\n", "").replaceAll("\t", "");
        residues.add(res);
      }
    }
    return residues;
  }

  protected String getJDBCId() {
    return CR_LMOD_2018_ID;
  }

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