added svcapi ui and camunda code
[it/otf.git] / otf-frontend / client / src / app / shared / modules / create-test-instance-form / create-test-instance-form.component.ts
diff --git a/otf-frontend/client/src/app/shared/modules/create-test-instance-form/create-test-instance-form.component.ts b/otf-frontend/client/src/app/shared/modules/create-test-instance-form/create-test-instance-form.component.ts
new file mode 100644 (file)
index 0000000..df703b4
--- /dev/null
@@ -0,0 +1,788 @@
+/*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
+#                                                                              #\r
+#   Licensed under the Apache License, Version 2.0 (the "License");            #\r
+#   you may not use this file except in compliance with the License.           #\r
+#   You may obtain a copy of the License at                                    #\r
+#                                                                              #\r
+#       http://www.apache.org/licenses/LICENSE-2.0                             #\r
+#                                                                              #\r
+#   Unless required by applicable law or agreed to in writing, software        #\r
+#   distributed under the License is distributed on an "AS IS" BASIS,          #\r
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
+#   See the License for the specific language governing permissions and        #\r
+#   limitations under the License.                                             #\r
+##############################################################################*/\r
+\r
+\r
+import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\r
+import 'codemirror/mode/yaml/yaml.js';\r
+import { TestInstanceService } from '../../services/test-instance.service';\r
+import { TestDefinitionService } from '../../services/test-definition.service';\r
+import { SchedulingService } from '../../services/scheduling.service';\r
+import { SelectStrategyModalComponent } from '../select-strategy-modal/select-strategy-modal.component';\r
+import { MatDialog, MatSnackBar } from '@angular/material';\r
+import { AlertModalComponent } from '../alert-modal/alert-modal.component';\r
+import { Router } from '@angular/router';\r
+import { AlertSnackbarComponent } from '../alert-snackbar/alert-snackbar.component';\r
+import { ListService } from 'app/shared/services/list.service';\r
+import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';\r
+import { HttpClient, HttpHeaders } from "@angular/common/http";\r
+import { AppGlobals } from "../../../app.global";\r
+import { CookieService } from "ngx-cookie-service";\r
+import * as  YAML from '../../../../../../node_modules/yamljs/lib/Yaml';\r
+import 'codemirror/mode/javascript/javascript.js';\r
+import beautify from 'json-beautify';\r
+import { WorkflowRequest } from './instance.class';\r
+import { PfloInputClass } from './instance.class';\r
+import { GroupService } from 'app/shared/services/group.service';\r
+import { ExecuteService } from 'app/shared/services/execute.service';\r
+\r
+const URL = AppGlobals.baseAPIUrl + 'files';\r
+\r
+\r
+@Component({\r
+  selector: 'app-create-test-instance-form',\r
+  templateUrl: './create-test-instance-form.component.pug',\r
+  styleUrls: ['./create-test-instance-form.component.scss']\r
+})\r
+export class CreateTestInstanceFormComponent implements OnInit {\r
+  yaml;\r
+  //Variable sent between modules\r
+  @Input() public existingInstance: any;\r
+\r
+  @Output() public childEvent = new EventEmitter();\r
+  public dataTemplate: any;\r
+  public configTemplate: any;\r
+\r
+  public codeConfig = {\r
+    mode: "yaml",\r
+    theme: "eclipse",\r
+    lineNumbers: true\r
+  };\r
+\r
+  public codeJsonConfig = {\r
+    mode: "application/json",\r
+    theme: "eclipse",\r
+    lineNumbers: true\r
+  }\r
+\r
+  public testDefinition;\r
+  public testInstance;\r
+  public createResult;\r
+  public selectedDefinition;\r
+  public errorCount = 0;\r
+  public executionFailed = false;\r
+  public editMode = false;\r
+  public httpOptions;\r
+  public selectedBpmn;\r
+  public uploader: FileUploader;\r
+  public isZip = true;\r
+  public scriptFiles = [];\r
+  public uploaders = {};\r
+  public vthInput = {};\r
+  public pfloInput = {};\r
+  public argsToAdd = {};\r
+  public vthInputYaml = {};\r
+  public displayYAML = false;\r
+  public testHeadYAML = false;\r
+  public testHeadNames = {};\r
+  public tiNameLookup = {};\r
+  public instances;\r
+  public search;\r
+  public instanceAdded;\r
+  \r
+\r
+  public uploadOptions = {\r
+    url: AppGlobals.baseAPIUrl + 'file-transfer',\r
+    authTokenHeader: 'Authorization',\r
+    authToken: 'Bearer ' + JSON.parse(this.cookie.get('access_token'))\r
+  };\r
+\r
+  // , private http: HttpClient, private Params: ParamsService, private cookie: CookieService\r
+  constructor(private router: Router, private list: ListService, private dialog: MatDialog, private execute: ExecuteService, private testInstanceService: TestInstanceService, private testDefinitionService: TestDefinitionService, private snack: MatSnackBar, private http: HttpClient, private cookie: CookieService, private groupService: GroupService) {\r
+    this.http = http;\r
+    this.cookie = cookie;\r
+    // this.httpOptions = {\r
+    //     headers: new HttpHeaders({ \r
+    //       'Content-Type': 'application/json',\r
+    //       'Authorization': 'Bearer ' + JSON.parse(this.cookie.get('access_token'))\r
+    //     })\r
+    //   };\r
+  }\r
+  // testingSelect(){\r
+  //   console.log(this.selectedBpmn);\r
+  // }\r
+  myFilter(bpmn) {\r
+    return bpmn.isDeployed;\r
+  }\r
+  ngOnInit() {\r
+    this.search = {};\r
+    this.search.testInstanceName = '';\r
+    this.testInstance = {};\r
+    this.selectedDefinition = {};\r
+    this.selectedBpmn = {};\r
+    this.testInstance.useLatestTestDefinition = true;\r
+    this.testInstance.simulationVthInput = {};\r
+    let currentGroup;\r
+    //options required for the file uploader\r
+    currentGroup = this.groupService.getGroup();\r
+    this.groupService.groupChange().subscribe(group => {\r
+      currentGroup = group;\r
+    });\r
+    \r
+    this.testInstanceService.find({\r
+      groupId: currentGroup['_id'],\r
+      $limit: -1,\r
+      $sort: {\r
+        createdAt: -1,\r
+      },\r
+      $select: ['testInstanceName']\r
+    }).subscribe((result) => {\r
+      this.instances = result;\r
+      for(let i = 0; i < this.instances.length; i++){\r
+        this.instances[i].isSelected = false;\r
+      }\r
+    })\r
+\r
+    //File Uploaders\r
+    //this.uploader = new FileUploader(uploadOptions);\r
+    //if the user is using this page for editing an existing instance\r
+    if (this.existingInstance) {\r
+      //console.log(this.existingInstance)\r
+      if (this.existingInstance.testInstance) {\r
+        this.testInstance = this.existingInstance.testInstance;\r
+        this.selectedDefinition = this.existingInstance.testInstance['testDefinitionId'];\r
+        \r
+        this.convertSimulationVth('string');\r
+        console.log(this.testInstance);\r
+\r
+        //set the bpmn to the selected bpmn. Alert User if no bpmn versions are deployed\r
+        if (this.testInstance.useLatestTestDefinition) {\r
+          this.useLatest();\r
+        } else {\r
+          for (let i = 0; i < this.selectedDefinition.bpmnInstances.length; i++) {\r
+            if (this.selectedDefinition.bpmnInstances[i].processDefintionId === this.testInstance.processDefintionId) {\r
+              this.selectedBpmn = this.selectedDefinition.bpmnInstances[i];\r
+              break;\r
+            }\r
+          }\r
+        }\r
+\r
+        if (this.testInstance.testData === '') {\r
+          this.displayYAML = true;\r
+        }\r
+\r
+        if (!this.testInstance.simulationVthInput) {\r
+          this.testInstance.simulationVthInput = {};\r
+        }\r
+\r
+\r
+        //grab all robot test heads to assign uploaders to each and create the vthInput object\r
+        //for(let j = 0; j < this.selectedBpmn.testHeads.length; j++){\r
+\r
+\r
+        //}\r
+        //console.log(this.uploaders);\r
+        if (this.existingInstance.isEdit == true)\r
+          this.editMode = true;\r
+      }//if the user is creating a new instance from the test definition page\r
+      else if (this.existingInstance.testDefinition) {\r
+        this.selectedDefinition = this.existingInstance.testDefinition;\r
+        this.populateTIName();\r
+        //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
+        this.useLatest();\r
+        this.populateVthInput();\r
+        this.populatePfloInput();\r
+        //grab all robot test heads to assign uploaders to each and set the vthInput object\r
+        for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
+\r
+          if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
+            this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
+          }\r
+        }\r
+\r
+        this.testInstance = {\r
+          "testInstanceDescription": "",\r
+          "testDefinitionId" : this.selectedDefinition["_id"],\r
+          "vthInput" : this.vthInput,\r
+          "pfloInput": this.pfloInput,\r
+          "vthInputYaml": this.vthInputYaml,\r
+          "testData": this.selectedBpmn.testDataTemplate,\r
+          "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
+          "useLatestTestDefinition": true,\r
+          "internalTestData": {},\r
+          "simulationVthInput": {}\r
+        };\r
+\r
+      }\r
+    }\r
+    \r
+  }\r
+\r
+  convertSimulationVth(convertTo) {\r
+    for (let key in this.testInstance.simulationVthInput) {\r
+      if (this.testInstance.simulationVthInput.hasOwnProperty(key)) {\r
+        if(convertTo == 'json')\r
+          this.testInstance.simulationVthInput[key] = JSON.parse(this.testInstance.simulationVthInput[key]);\r
+        else if (convertTo == 'string')\r
+          this.testInstance.simulationVthInput[key] = beautify(this.testInstance.simulationVthInput[key], null, 2, 10);\r
+      }\r
+    }\r
+\r
+  }\r
\r
+\r
+\r
+  simulationMode() {\r
+    let def = {\r
+      delay: 0, response: {}\r
+    };\r
+    //console.log(this.selectedBpmn);\r
+    if (this.testInstance.simulationMode) {\r
+      this.selectedBpmn.testHeads.forEach(e => {\r
+        if(!this.testInstance.simulationVthInput){\r
+          this.testInstance.simulationVthInput = {}\r
+        }\r
+        if (!this.testInstance.simulationVthInput[e.bpmnVthTaskId]) {\r
+          this.testInstance.simulationVthInput[e.bpmnVthTaskId] = beautify(def, null, 2, 10);\r
+        }\r
+      })\r
+    }\r
+  }\r
+\r
+  populateTIName() {\r
+    let list;\r
+    this.testInstanceService.find({ $limit: -1, $select: ['testInstanceName'], testDefinitionId: this.selectedDefinition._id }).subscribe((res) => {\r
+      list = res;\r
+      //console.log(list);\r
+      let num = list.length;\r
+      if (num === 0) {\r
+        this.testInstance.testInstanceName = this.selectedDefinition.testName;\r
+      } else {\r
+        this.testInstance.testInstanceName = this.selectedDefinition.testName + num;\r
+      }\r
+      let isTaken = true;\r
+      let count = 0;\r
+      let alreadyExisted = false;\r
+      while (isTaken === true && count < 10000) {\r
+        for (let i = 0; i < list.length; i++) {\r
+          if (list[i]["testInstanceName"] === this.testInstance.testInstanceName) {\r
+            num++;\r
+            this.testInstance.testInstanceName = this.selectedDefinition.testName + num;\r
+            alreadyExisted = true;\r
+            break;\r
+          }\r
+        }\r
+        if (alreadyExisted) {\r
+          alreadyExisted = false;\r
+        } else {\r
+          isTaken = false;\r
+        }\r
+        count++;\r
+      }\r
+    });\r
+  }\r
+  //Section for implementing Paralell workflow data entry --------------------------------------------------------------------------------------\r
+  populatePfloInput(){\r
+    // this.pfloInput = {\r
+    //   "task123": new PfloInputClass\r
+    // }\r
+    //this.selectedBpmn.pflos = [{"bpmnPfloTaskId" : "task123", "label": "TestPFLO"}]\r
+    \r
+    if(this.testInstance.pfloInput){  \r
+      return;\r
+    }\r
+\r
+    this.pfloInput = {};\r
+   \r
+    if(this.selectedBpmn == {} || !this.selectedBpmn.pflos){\r
+      \r
+      this.testInstance.pfloInput = this.pfloInput;\r
+      return;\r
+    }\r
+\r
+    for(let i = 0; i < this.selectedBpmn.pflos.length; i++){\r
+      if(this.selectedBpmn.pflos[i]['bpmnPfloTaskId'] != null){\r
+        this.pfloInput[this.selectedBpmn.pflos[i]['bpmnPfloTaskId']] = new PfloInputClass;\r
+       \r
+        //this.pfloInput[this.selectedBpmn.pflos[i]['bpmnPfloTaskId'] + "pfloName"] = this.selectedBpmn.pflos[i]['label'];\r
+      }\r
+    }\r
+    this.testInstance.pfloInput = this.pfloInput;\r
+    \r
+  }\r
+\r
+  \r
+  addInstancesToPflo(taskId){\r
+    for(let i = 0; i < this.instances.length; i++){\r
+      if(this.instances[i].isSelected){\r
+        this.tiNameLookup[this.instances[i]._id] = this.instances[i].testInstanceName;\r
+        this.addPfloInput(taskId, this.instances[i]._id);\r
+      }\r
+\r
+    }\r
+  }\r
+\r
+  addPfloInput(taskId, instanceId){\r
+     \r
+    this.testInstance.pfloInput[taskId].args.push(new WorkflowRequest(instanceId));\r
+   \r
+  }\r
+\r
+  clearSelectedValues(){\r
+    this.search.testInstanceName = '';\r
+    for(let i = 0; i < this.instances.length; i++){\r
+      this.instances[i].isSelected = false;\r
+    }\r
+  }\r
+\r
+  saveTestDataOptions(event) {\r
+    this.testInstance.testData = event.object;\r
+  }\r
+\r
+  saveFormOptions(event) {\r
+    this.testInstance.vthInput[event.taskId] = event.object;\r
+    //console.log(this.testInstance);\r
+  }\r
+\r
+  \r
+  checkPfloInputLength(){\r
+  \r
+    if(this.testInstance.pfloInput != null){\r
+      let temp =  Object.keys(this.testInstance.pfloInput);\r
+      if(temp.length)\r
+        return temp.length > 0;\r
+      else\r
+        return false;\r
+    }else{\r
+      return false;\r
+    }\r
+  }\r
+\r
+  deleteWorkReq(pfloId, index){\r
+    this.testInstance.pfloInput[pfloId].args.splice(index, 1);\r
+    //FORCE REFRESH all connected forms to update their index\r
+  }\r
+\r
+  saveWorkReqForm(event) {\r
+    this.testInstance.pfloInput[event.taskId].args[event.index] = event.object;\r
+    //console.log(this.testInstance);\r
+  }\r
+\r
+  convertTestLevelYaml() {\r
+    if (this.displayYAML) {\r
+      this.testInstance.testDataJSON = YAML.parse(this.testInstance.testData);\r
+    } else {\r
+      this.testInstance.testData = YAML.stringify(this.testInstance.testDataJSON);\r
+    }\r
+  }\r
+\r
+  convertVTHYaml() {\r
+    if (this.testHeadYAML) {\r
+      for (let key in this.testInstance.vthInputYaml) {\r
+        this.testInstance.vthInput[key] = YAML.parse(this.testInstance.vthInputYaml[key]);\r
+      }\r
+    } else {\r
+\r
+      for (let key in this.testInstance.vthInput) {\r
+        this.testInstance.vthInputYaml[key] = YAML.stringify(this.testInstance.vthInput[key]);\r
+      }\r
+    }\r
+  }\r
+  //End of Paralell workflow data entry section --------------------------------------------------------------------------------------\r
+\r
+  changeBpmn() {\r
+    //populate the vth inputs when bpmn changes\r
+    this.populateVthInput();\r
+    this.displayYAML = !this.displayYAML;\r
+    this.testInstance.testDataJSON = this.selectedBpmn.testDataTemplateJSON;\r
+    this.testInstance.testData = this.selectedBpmn.testDataTemplate;\r
+    this.convertTestLevelYaml();\r
+    setTimeout(() => {\r
+      this.displayYAML = !this.displayYAML;\r
+    }, 200);\r
+\r
+  }\r
+  //toggle Yaml for test level data\r
+  toggleYaml() {\r
+    this.convertTestLevelYaml();\r
+    this.displayYAML = !this.displayYAML;\r
+  }\r
+  //toggles Yaml for testHeads\r
+  testHeadYaml() {\r
+    this.convertVTHYaml();\r
+    this.testHeadYAML = !this.testHeadYAML;\r
+  }\r
+  //onChange method for the use latest TD toggle\r
+  useLatest() {\r
+    if (this.testInstance.useLatestTestDefinition) {\r
+      let temp;\r
+      let orderNum;\r
+      let processKey;\r
+      for (let i = 0; i < this.selectedDefinition.bpmnInstances.length; i++) {\r
+        if (temp) {\r
+          processKey = this.selectedDefinition.bpmnInstances[i].processDefinitionId\r
+          if(processKey){\r
+            orderNum = processKey.split(":");\r
+            orderNum = orderNum[1];\r
+            //console.log("bpmn check : " + orderNum + " bpmn current: " + temp.processDefinitionId.split(':')[1]);\r
+            if (this.selectedDefinition.bpmnInstances[i].isDeployed && parseInt(orderNum) > parseInt(temp.processDefinitionId.split(':')[1])) {\r
+              temp = this.selectedDefinition.bpmnInstances[i];\r
+            }\r
+          }\r
+        } else {\r
+          if (this.selectedDefinition.bpmnInstances[i].isDeployed) {\r
+            temp = this.selectedDefinition.bpmnInstances[i];\r
+          }\r
+        }\r
+\r
+      }\r
+      if (temp.isDeployed) {\r
+        this.selectedBpmn = temp;\r
+      } else {\r
+        this.dialog.open(AlertModalComponent, {\r
+          width: '450px',\r
+          data: {\r
+            type: 'alert',\r
+            message: 'Test Definition does not contain a deployed bpmn instance. Please return to the Test Definition page and deploy.'\r
+          }\r
+        });\r
+        this.testInstance.useLatestTestDefinition = false;\r
+      }\r
+      this.populateVthInput();\r
+    }\r
+    this.populatePfloInput();\r
+  }\r
+\r
\r
+  //checks if the test instance has a required Name\r
+  allNamed() {\r
+    if (!this.testInstance.testInstanceName) {\r
+      return false;\r
+    }\r
+\r
+    return true;\r
+  }\r
+  \r
+  //populate the vthInputYaml for newly created testInstances\r
+  populateVthInput() {\r
+    this.vthInputYaml = {};\r
+    this.vthInput = {};\r
+    for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
+      this.vthInputYaml[this.selectedBpmn.testHeads[i].bpmnVthTaskId] = this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplate;\r
+      this.vthInputYaml[this.selectedBpmn.testHeads[i].bpmnVthTaskId + "testHeadName"] = this.selectedBpmn.testHeads[i].testHeadId.testHeadName;\r
+      if (this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplateJSON) {\r
+        this.vthInput[this.selectedBpmn.testHeads[i].bpmnVthTaskId] = this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplateJSON;\r
+        this.vthInput[this.selectedBpmn.testHeads[i].bpmnVthTaskId + "testHeadName"] = this.selectedBpmn.testHeads[i].testHeadId.testHeadName;\r
+      }\r
+\r
+    }\r
+\r
+  }\r
+  //Used to grab all test definitions for the user to select.\r
+  getDefinition() {\r
+    const dialogRef = this.dialog.open(SelectStrategyModalComponent, {\r
+      width: '450px',\r
+      data: {}\r
+    });\r
+\r
+    dialogRef.afterClosed().subscribe(result => {\r
+      //If the user already had a selected definition and selected a new one, prompt the user to be sure of change\r
+      if (result != '' && this.selectedDefinition.testName) {\r
+        this.dialog.open(AlertModalComponent, {\r
+          width: '450px',\r
+          data: {\r
+            type: 'confirmation',\r
+            message: 'Changing the Test Definition will erase the Instance you are currently writing.'\r
+          }\r
+        }).afterClosed().subscribe(response => {\r
+          if (response) {\r
+            this.selectedDefinition = result;            \r
+            this.populateTIName();\r
+            //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
+            this.useLatest();\r
+            this.populateVthInput();\r
+            this.populatePfloInput();\r
+            //grab all robot test heads to assign uploaders to each and initialize vthInput\r
+            for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
+              if (this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON']) {\r
+                this.vthInput[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON'];\r
+              }\r
+\r
+              if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
+                this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
+              }\r
+            }\r
+\r
+            this.testInstance = {\r
+              "testInstanceDescription": "",\r
+              "groupId": this.selectedDefinition["groupId"],\r
+              "testDefinitionId": this.selectedDefinition["_id"],\r
+              "vthInput": this.vthInput,\r
+              "pfloInput": this.pfloInput,\r
+              "vthInputYaml": this.vthInputYaml,\r
+              "testData": this.selectedBpmn.testDataTemplate,\r
+              "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
+              "useLatestTestDefinition": true,\r
+              "internalTestData": {},\r
+              "simulationVthInput": {}\r
+\r
+            };\r
+          }\r
+        });\r
+\r
+        //else they did not have a test definition currently selected\r
+      } else {\r
+        this.selectedDefinition = result;\r
+        this.populateTIName();\r
+        //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
+        this.useLatest();\r
+        this.populateVthInput();\r
+        this.populatePfloInput();\r
+        //grab all robot test heads to assign uploaders to each\r
+        for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
+          if (this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON']) {\r
+            this.vthInput[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON'];\r
+          }\r
+          if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
+            this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
+          }\r
+        }\r
+             \r
+          \r
+         \r
+          this.testInstance = {\r
+            "testInstanceDescription": "",\r
+              "groupId": this.selectedDefinition["groupId"],\r
+              "testDefinitionId": this.selectedDefinition["_id"],\r
+              "vthInput": this.vthInput,\r
+              "pfloInput": this.pfloInput,\r
+              "vthInputYaml": this.vthInputYaml,\r
+              "testData": this.selectedBpmn.testDataTemplate,\r
+              "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
+              "useLatestTestDefinition": true,\r
+              "internalTestData": {},\r
+              "simulationVthInput": {}\r
+          };\r
+          \r
+        }\r
+    });\r
+  }\r
+\r
+  //Saves the Test Instance Object to the database \r
+  saveAll() {\r
+    if (!this.allNamed()) {\r
+      this.dialog.open(AlertModalComponent, {\r
+        width: '450px',\r
+        data: {\r
+          type: 'alert',\r
+          message: 'The Instance is not named! Please ensure the Instance are named.'\r
+        }\r
+      }).afterClosed().subscribe((result) => {\r
+        return;\r
+      });\r
+    } else {\r
+\r
+      if (!this.testInstance.processDefinitionId) {\r
+        this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
+      }\r
+      this.errorCount = 0;\r
+      if (!this.displayYAML) {\r
+        this.testInstance.testData = this.testInstance.testDataJSON;\r
+      }\r
+      if (this.testHeadYAML) {\r
+        this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
+      }\r
+\r
+      this.convertSimulationVth('json');\r
+\r
+      this.testInstanceService.create(this.testInstance)\r
+        .subscribe(\r
+          (result) => {\r
+            if (Object.keys(this.uploaders).length > 0)\r
+              this.uploadFiles(result);\r
+\r
+            this.snack.openFromComponent(AlertSnackbarComponent, {\r
+              duration: 1500,\r
+              data: {\r
+                message: 'Test Instance Saved'\r
+              }\r
+            });\r
+            this.dialog.closeAll();\r
+          },\r
+          (error) => {\r
+            this.dialog.open(AlertModalComponent, {\r
+              width: '450px',\r
+              data: {\r
+                type: 'Alert',\r
+                message: error\r
+              }\r
+            });\r
+\r
+          });\r
+    }\r
+  }\r
+\r
+  updateInstance() {\r
+\r
+\r
+    if (!this.testInstance.processDefinitionId) {\r
+      this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
+    }\r
+    this.errorCount = 0;\r
+    if (!this.displayYAML) {\r
+      this.testInstance.testData = this.testInstance.testDataJSON;\r
+    }\r
+    if (this.testHeadYAML) {\r
+      this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
+    }\r
+\r
+    this.convertSimulationVth('json');\r
+\r
+    this.testInstanceService.update(this.testInstance)\r
+      .subscribe((result) => {\r
+        this.snack.openFromComponent(AlertSnackbarComponent, {\r
+          duration: 1500,\r
+          data: {\r
+            message: 'Test Instance Updated'\r
+          }\r
+        });\r
+        this.childEvent.emit();\r
+      });\r
+  }\r
+\r
+  cancel() {\r
+    this.childEvent.emit();\r
+  }\r
+  uploadFiles(result) {\r
+    for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
+      if (!this.uploaders[this.selectedBpmn.testHeads[i].bpmnVthTaskId]) {\r
+        continue;\r
+      }\r
+      let key = this.selectedBpmn.testHeads[i].bpmnVthTaskId;\r
+      let uploader = this.uploaders[key];\r
+      if (uploader.queue.length > 0) {\r
+        uploader.uploadAll();\r
+        uploader.onCompleteItem = (item: FileItem, response: string, status: Number, headers: ParsedResponseHeaders) => {\r
+          this.scriptFiles.push(JSON.parse(response)[0]);\r
+        }\r
+      }\r
+      uploader.onCompleteAll = () => {\r
+\r
+        let scriptFilesId = [];\r
+        for (let i = 0; i < this.scriptFiles.length; i++) {\r
+          scriptFilesId.push(this.scriptFiles[i]['_id']);\r
+        }\r
+       \r
+        for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
+          if (this.selectedBpmn.testHeads[i].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
+            this.testInstance.internalTestData[this.selectedBpmn.testHeads[i].bpmnVthTaskId] =\r
+              {\r
+                "robotFileId": scriptFilesId[0]\r
+              };\r
+          }\r
+        }\r
+        let ti = {\r
+          '_id': result._id,\r
+          'internalTestData': this.testInstance.internalTestData\r
+        }\r
+\r
+        this.testInstanceService.patch(ti).subscribe(\r
+          res => {\r
+            //console.log(res);\r
+            // resolve(res);\r
+          },\r
+          err => {\r
+            // console.log(err);\r
+            // reject(err);\r
+          }\r
+        );\r
+      }\r
+    }\r
+  }\r
+  //saves instance to the database and executes the test using the agenda scheduler\r
+  saveAndExecute() {\r
+    if (!this.allNamed()) {\r
+      this.dialog.open(AlertModalComponent, {\r
+        width: '450px',\r
+        data: {\r
+          type: 'alert',\r
+          message: 'One or more Instance is not named! Please ensure all Instances are named.'\r
+        }\r
+      }).afterClosed().subscribe((result) => {\r
+        return;\r
+      });\r
+    } else {\r
+\r
+      if (!this.testInstance.processDefinitionId) {\r
+        this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
+      }\r
+      this.errorCount = 0;\r
+      if (!this.displayYAML) {\r
+        this.testInstance.testData = this.testInstance.testDataJSON;\r
+      }\r
+      if (this.testHeadYAML) {\r
+        this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
+      }\r
+\r
+      this.convertSimulationVth('json')\r
+\r
+      this.testInstanceService.create(this.testInstance)\r
+        .subscribe(\r
+          (result) => {\r
+            this.executionFailed = false;\r
+            this.createResult = result;\r
+            if (Object.keys(this.uploaders).length > 0)\r
+              this.uploadFiles(result);\r
+\r
+\r
+            this.execute.create({\r
+              _id: this.createResult._id,\r
+              async: true\r
+            })\r
+              .subscribe(\r
+                (response) => {\r
+\r
+                  this.childEvent.emit();\r
+                  this.snack.openFromComponent(AlertSnackbarComponent, {\r
+                    duration: 1500,\r
+                    data: {\r
+                      message: 'Test Instance Saved and Executed'\r
+                    }\r
+                  });\r
+                  this.router.navigateByUrl('/dashboard');\r
+                },\r
+                (error) => {\r
+                  this.executionFailed = true;\r
+                  this.dialog.open(AlertModalComponent, {\r
+                    width: '450px',\r
+                    data: {\r
+                      type: 'Alert',\r
+                      message: "Execution error: " + error\r
+                    }\r
+                  });\r
+                });\r
+          },\r
+          (error) => {\r
+            this.dialog.open(AlertModalComponent, {\r
+              width: '450px',\r
+              data: {\r
+                type: 'Alert',\r
+                message: "Save Error: " + error\r
+              }\r
+            });\r
+          });\r
+    }\r
+  }\r
+\r
+  createNewInstance() {\r
+    this.testInstance = {\r
+      'testInstanceName': '',\r
+      'testInstanceDescription': '',\r
+      'testDefinitionId': this.selectedDefinition._id,\r
+      'testData': '',\r
+      'simulationVthInput': {}\r
+\r
+    }\r
+  }\r
+}\r