ModelArchive.java [tools/MetaModelTools/src/models] Revision: ec5f4cade4553a8341e1cd241b111bfdb77a87a8  Date: Fri Jan 10 10:59:55 MST 2020
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API, and application suite.
 *
 * 2012-2019, 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 models;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.FileUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author <a href="mailto:shaun.case@colostate.edu">Shaun Case</a>
 */
public class ModelArchive {

  private static final String FAILED_MESSAGE = "FAILED: ";

  protected String service;
  protected String status;
  protected String ctime; // creation time
  protected String etime; // expiration time
  protected String req_ip;
  protected String suid;
  protected String filename;
  protected JSONObject originalRequest;
  protected JSONObject originalResponse;
  protected String logFile;

  public ModelArchive(String suid, String ctime, String etime, String service, String status, String req_ip, String filename) {
    this.ctime = ctime;
    this.etime = etime;
    this.service = service;
    this.status = status;
    this.req_ip = req_ip;
    this.suid = suid;
    this.filename = filename;
  }

  public ModelArchive(String suid, String ctime, String etime, String service, String status, String req_ip, String filename, byte[] fileData) throws IOException, JSONException {
    this.ctime = ctime;
    this.etime = etime;
    this.service = service;
    this.status = status;
    this.req_ip = req_ip;
    this.suid = suid;
    this.filename = filename;

    setFileData(fileData);
  }

  public ModelArchive(JSONObject inputData) throws JSONException {
    suid = inputData.getString(csip.ModelDataService.KEY_SUUID);
    ctime = inputData.getString(csip.ModelDataService.KEY_TSTAMP);
    etime = inputData.getString(csip.ModelDataService.KEY_EXPIRATION_DATE);
    service = inputData.getString(csip.ModelDataService.KEY_SERVICE_URL);
    status = inputData.getString(csip.ModelDataService.KEY_STATUS);
    req_ip = inputData.getString(csip.ModelDataService.KEY_REQ_IP);
    filename = suid + ".zip";
  }

  protected final void setFileData(byte[] fileData) throws IOException, JSONException {
    originalRequest = getServiceRequest(fileData);
    originalResponse = getServiceResponse(fileData);
    logFile = getFileContents(fileData, ".log.txt");
  }

  public void setFileDataEx(byte[] fileData) throws IOException, JSONException {
    setFileData(fileData);
  }

  public final String getFileContents(byte[] fileData, String fileName) throws IOException {
    String fileString = null;

    try (ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData))) {
      ZipEntry entry;

      while ((entry = zin.getNextEntry()) != null) {
        if (entry.getName().contains(fileName)) {
          BufferedReader bReader = new BufferedReader(new InputStreamReader(zin));
          StringBuilder fileContent = new StringBuilder();
          String inputStr;
          while ((inputStr = bReader.readLine()) != null) {
            fileContent.append(inputStr).append(System.lineSeparator());
          }
          fileString = fileContent.toString();
          break;
        }
      }
    }

    return fileString;
  }

  protected JSONObject getServiceRequest(byte[] fileData) throws IOException, JSONException {
    JSONObject requestData;
    requestData = new JSONObject(getFileContents(fileData, ".request"));
    return requestData;
  }

  public String getOriginalRequest(String lookup) {
    String ret_val = ((originalResponseFailed()) ? FAILED_MESSAGE : "");

    JSONArray results = originalRequest.optJSONArray("parameter");

    if (null != results) {
      for (int i = 0; i < results.length(); i++) {
        JSONObject jsonObject = results.optJSONObject(i);
        if (null != jsonObject) {
          if (jsonObject.optString("name") != null) {
            if (jsonObject.optString("name").equalsIgnoreCase(lookup)) {
              if (jsonObject.optString("value") != null) {
                ret_val = jsonObject.optString("value");
              }
            }
          }
        }
      }
    }

    return ret_val;
  }

  protected JSONObject getServiceResponse(byte[] fileData) throws IOException, JSONException {
    JSONObject requestData;
    requestData = new JSONObject(getFileContents(fileData, ".response"));
    return requestData;
  }

  public String getOriginalResponse(String lookup) {
    String ret_val = ((originalResponseFailed()) ? FAILED_MESSAGE : "");

    JSONArray results = originalResponse.optJSONArray("result");

    if (null != results) {
      for (int i = 0; i < results.length(); i++) {
        JSONObject jsonObject = results.optJSONObject(i);
        if (null != jsonObject) {
          if (jsonObject.optString("name") != null) {
            if (jsonObject.optString("name").equalsIgnoreCase(lookup)) {
              if (jsonObject.optString("value") != null) {
                ret_val = jsonObject.optString("value");
              }
            }
          }
        }
      }
    }

    return ret_val;
  }

  public boolean originalResponseFailed() {
    boolean ret_val = true;
    JSONObject metaInfo = originalResponse.optJSONObject("metainfo");

    if (null != metaInfo) {
      String status = metaInfo.optString("status");

      if ((null != status) && (!status.isEmpty())) {
        ret_val = !status.equalsIgnoreCase("finished");
      }
    }

    return ret_val;
  }

  public JSONObject getOriginalRequest() {
    return originalRequest;
  }

  public JSONObject getOriginalResponse() {
    return originalResponse;
  }

  public String getReqIP() {
    return req_ip;
  }

  public String getStatus() {
    return status;
  }

  public String getService() {
    return service;
  }

  public String getSUID() {
    return suid;
  }

  public String getCtime() {
    return ctime;
  }

  public String getEtime() {
    return etime;
  }

  public void saveFileData(byte[] fileData) throws IOException {
    if (null != fileData) {
      if (fileData.length > 0) {
        FileUtils.writeByteArrayToFile(new File(filename), fileData);
      }
    }
  }
}