From 770049ea162573d5afa1aaefed6131fe5e0a77f7 Mon Sep 17 00:00:00 2001 From: danielhanrahan Date: Tue, 15 Feb 2022 18:02:23 +0000 Subject: Refactor apex-editor frontend build Moved frontend from src/main/resources/webapp to src/main/webapp Moved static resources such as jquery-ui to webapp/dist folder Configured jest to exclude webapp/dist from coverage report Removed unused ZIP file assembly Cleaned up POM Issue-ID: POLICY-3896 Signed-off-by: danielhanrahan Change-Id: Ia006eb94a39586219029866eef94aef38912ad65 --- .../gui-editor-apex/src/main/webapp/js/ApexAjax.js | 131 +++ .../src/main/webapp/js/ApexContextAlbumEditForm.js | 493 +++++++++ .../src/main/webapp/js/ApexContextAlbumTab.js | 128 +++ .../main/webapp/js/ApexContextSchemaEditForm.js | 385 +++++++ .../src/main/webapp/js/ApexContextSchemaTab.js | 123 +++ .../src/main/webapp/js/ApexEventEditForm.js | 588 ++++++++++ .../src/main/webapp/js/ApexEventTab.js | 157 +++ .../src/main/webapp/js/ApexFiles.js | 75 ++ .../src/main/webapp/js/ApexFormUtils.js | 50 + .../src/main/webapp/js/ApexKeyInformationTab.js | 117 ++ .../gui-editor-apex/src/main/webapp/js/ApexMain.js | 180 ++++ .../src/main/webapp/js/ApexModelHandling.js | 48 + .../src/main/webapp/js/ApexNewModelForm.js | 241 +++++ .../src/main/webapp/js/ApexPageControl.js | 302 ++++++ .../src/main/webapp/js/ApexPolicyEditForm.js | 830 ++++++++++++++ .../src/main/webapp/js/ApexPolicyEditForm_State.js | 1140 ++++++++++++++++++++ .../src/main/webapp/js/ApexPolicyTab.js | 226 ++++ .../src/main/webapp/js/ApexResultForm.js | 95 ++ .../src/main/webapp/js/ApexTable.js | 39 + .../src/main/webapp/js/ApexTaskEditForm.js | 1024 ++++++++++++++++++ .../src/main/webapp/js/ApexTaskTab.js | 189 ++++ .../src/main/webapp/js/ApexUtils.js | 140 +++ .../src/main/webapp/js/__test__/ApexAjax.test.js | 207 ++++ .../js/__test__/ApexContextAlbumEditForm.test.js | 144 +++ .../webapp/js/__test__/ApexContextAlbumTab.test.js | 27 + .../js/__test__/ApexContextSchemaEditForm.test.js | 110 ++ .../js/__test__/ApexContextSchemaTab.test.js | 54 + .../webapp/js/__test__/ApexEventEditForm.test.js | 193 ++++ .../main/webapp/js/__test__/ApexEventTab.test.js | 119 ++ .../src/main/webapp/js/__test__/ApexFiles.test.js | 57 + .../main/webapp/js/__test__/ApexFormUtils.test.js | 35 + .../js/__test__/ApexKeyInformationTab.test.js | 76 ++ .../src/main/webapp/js/__test__/ApexMain.test.js | 103 ++ .../webapp/js/__test__/ApexModelHandling.test.js | 96 ++ .../webapp/js/__test__/ApexNewModelForm.test.js | 46 + .../webapp/js/__test__/ApexPageControl.test.js | 116 ++ .../webapp/js/__test__/ApexPolicyEditForm.test.js | 174 +++ .../js/__test__/ApexPolicyEditForm_State.test.js | 174 +++ .../main/webapp/js/__test__/ApexPolicyTab.test.js | 305 ++++++ .../main/webapp/js/__test__/ApexResultForm.test.js | 37 + .../src/main/webapp/js/__test__/ApexTable.test.js | 43 + .../webapp/js/__test__/ApexTaskEditForm.test.js | 179 +++ .../main/webapp/js/__test__/ApexTaskTab.test.js | 52 + .../src/main/webapp/js/__test__/ApexUtils.test.js | 116 ++ .../main/webapp/js/__test__/contextMenu.test.js | 118 ++ .../main/webapp/js/__test__/dropdownList.test.js | 68 ++ .../src/main/webapp/js/__test__/fileMenu.test.js | 31 + .../webapp/js/__test__/showhideElement.test.js | 49 + .../webapp/js/__test__/showhideTextArea.test.js | 48 + .../src/main/webapp/js/__test__/test-env.js | 2 + .../src/main/webapp/js/contextMenu.js | 235 ++++ .../src/main/webapp/js/dropdownList.js | 213 ++++ .../gui-editor-apex/src/main/webapp/js/fileMenu.js | 146 +++ .../src/main/webapp/js/showhideElement.js | 66 ++ .../src/main/webapp/js/showhideTextarea.js | 133 +++ 55 files changed, 10273 insertions(+) create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaEditForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexFormUtils.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm_State.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexResultForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexTable.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/ApexUtils.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFormUtils.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexNewModelForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm_State.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexResultForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTable.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexUtils.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/contextMenu.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/dropdownList.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/fileMenu.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideElement.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideTextArea.test.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/__test__/test-env.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/contextMenu.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/dropdownList.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/fileMenu.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/showhideElement.js create mode 100644 gui-editors/gui-editor-apex/src/main/webapp/js/showhideTextarea.js (limited to 'gui-editors/gui-editor-apex/src/main/webapp/js') diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js new file mode 100644 index 0000000..4a6dc7d --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js @@ -0,0 +1,131 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const { + pageControl_restError, pageControl_status, + pageControl_successStatus +} = require("./ApexPageControl"); + +function ajax_get(requestURL, callback) { + $.ajax({ + type : 'GET', + url : requestURL, + dataType : "json", // data type of response + success : function(data, textStatus, jqXHR) { + pageControl_successStatus(data); + callback(data); + }, + error : function(jqXHR, textStatus, errorThrown) { + pageControl_restError(requestURL, jqXHR, textStatus, errorThrown); + } + }); +} + +function ajax_getWithKeyInfo(requestURL, objectType, callback, keyNam) { + let keyName = keyNam || "key"; + let keyInfoURL = window.restRootURL + "/KeyInformation/Get?name=&version="; + ajax_get(keyInfoURL, function(dataKeyInfos) { + ajax_get(requestURL, function(data) { + var keyInfos = []; + for ( let value of dataKeyInfos.messages.message) { + var ki = JSON.parse(value).apexKeyInfo; + keyInfos.push(ki); + } + var object = JSON.parse(data.messages.message[0])[objectType]; + var keyInfo = keyInfos.filter(function(ki) { + return ki.key.name === object[keyName].name + && ki.key.version === object[keyName].version; + }); + if (keyInfo.length > 0) { + object.uuid = keyInfo[0].UUID; + object.description = keyInfo[0].description; + } + callback(object); + }); + }); +} + +function ajax_getOKOrFail(requestURL, callback) { + $.ajax({ + type : 'GET', + url : requestURL, + dataType : "json", // data type of response + success : function(data, textStatus, jqXHR) { + pageControl_status(data); + callback(data); + }, + error : function(jqXHR, textStatus, errorThrown) { + pageControl_restError(requestURL, jqXHR, textStatus, errorThrown); + } + }); +} + +function ajax_put(requestURL, requestData, callback) { + $.ajax({ + type : 'PUT', + contentType : 'application/json', + url : requestURL, + dataType : "json", + data : requestData, + success : function(responseData, textStatus, jqXHR) { + pageControl_successStatus(responseData); + callback(responseData); + }, + error : function(jqXHR, textStatus, errorThrown) { + pageControl_restError(requestURL, jqXHR, textStatus, errorThrown); + } + }); +} + +function ajax_post(requestURL, requestData, callback) { + $.ajax({ + type : 'POST', + contentType : 'application/json', + url : requestURL, + dataType : "json", + data : requestData, + success : function(responseData, textStatus, jqXHR) { + pageControl_successStatus(responseData); + callback(responseData); + }, + error : function(jqXHR, textStatus, errorThrown) { + pageControl_restError(requestURL, jqXHR, textStatus, errorThrown); + } + }); +} + +function ajax_delete(requestURL, callback) { + $.ajax({ + type : 'DELETE', + url : requestURL, + dataType : "json", // data type of response + success : function(data, textStatus, jqXHR) { + pageControl_successStatus(data); + callback(data); + }, + error : function(jqXHR, textStatus, errorThrown) { + pageControl_restError(requestURL, jqXHR, textStatus, errorThrown); + } + }); +} + +export {ajax_get, ajax_delete, ajax_post, ajax_put, ajax_getOKOrFail, ajax_getWithKeyInfo}; \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js new file mode 100644 index 0000000..9534a99 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js @@ -0,0 +1,493 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; +const {ajax_delete, ajax_getWithKeyInfo, ajax_get} = require("./ApexAjax"); +const {contextAlbumTab_reset} = require("./ApexContextAlbumTab"); +const {apexUtils_removeElement, apexUtils_emptyElement, scrollToTop, apexUtils_areYouSure} = require("./ApexUtils"); +const {dropdownList} = require("./dropdownList"); +const { formUtils_generateDescription, formUtils_generateUUID } = require("./ApexFormUtils"); + +function editContextAlbumForm_createContextAlbum(formParent) { + // Get all contextSchemas too for album item schema + var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + editContextAlbumForm_activate(formParent, "CREATE", null, contextSchemas); + }); +} + +function editContextAlbumForm_deleteContextAlbum(parent, name, version) { + var message = "Are you sure you want to delete ContextAlbum \"" + name + ":" + version + "\"?"; + if (apexUtils_areYouSure(message)) { + var requestURL = window.restRootURL + "/ContextAlbum/Delete?name=" + name + "&version=" + version; + ajax_delete(requestURL, function(data) { + apexUtils_removeElement("editContextAlbumFormDiv"); + contextAlbumTab_reset(); + keyInformationTab_reset() + }); + } +} + +function editContextAlbumForm_viewContextAlbum(parent, name, version) { + var requestURL = window.restRootURL + "/ContextAlbum/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexContextAlbum", function(contextAlbum) { + // Get all contextSchemas too for album item schema + requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + editContextAlbumForm_activate(parent, "VIEW", contextAlbum, contextSchemas); + }); + }); +} + +function editContextAlbumForm_editContextAlbum(formParent, name, version) { + var requestURL = window.restRootURL + "/ContextAlbum/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexContextAlbum", function(contextAlbum) { + // Get all contextSchemas too for album item schema + requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + editContextAlbumForm_activate(formParent, "EDIT", contextAlbum, contextSchemas); + }); + }); +} + +function editContextAlbumForm_activate(parent, operation, contextAlbum, contextSchemas) { + apexUtils_removeElement("editContextAlbumFormDiv"); + var formParent = document.getElementById(parent); + + //Test Purposes + if(formParent === null){ + formParent = document.createElement(parent); + } + apexUtils_emptyElement(parent); + + var createEditOrView = ""; + + if (!operation) { + console.warn("No operation specified for ContextAlbumForm form") + } else { + createEditOrView = operation.toUpperCase(); + } + + if (createEditOrView == "EDIT" || createEditOrView == "VIEW") { + + if (!contextAlbum) { + console.warn("Invalid value (\"" + contextAlbum + + "\") passed as a value for \"contextAlbum\" for ContextAlbumForm form."); + } else { + if (!contextAlbum.key || !contextAlbum.key.name || contextAlbum.key.name == "") { + console.warn("Invalid value (\"" + contextAlbum.key.name + + "\") passed as a value for \"name\" for ContextAlbumForm form."); + } + if (!contextAlbum.key || !contextAlbum.key.version || contextAlbum.key.version == "") { + console.warn("Invalid value (\"" + contextAlbum.key.version + + "\") passed as a value for \"version\" for ContextAlbumForm form."); + } + if (!contextAlbum.uuid || contextAlbum.uuid == "") { + console.warn("Invalid value (\"" + contextAlbum.uuid + + "\") passed as a value for \"uuid\" for ContextAlbumForm form."); + } + if (createEditOrView == "VIEW") { + if (!contextAlbum.description) { + console.warn("Invalid value (\"" + contextAlbum.description + + "\") passed as a value for \"description\" for ContextAlbumForm form."); + } + if (!contextAlbum.scope || contextAlbum.scope == "") { + console.warn("Invalid value (\"" + contextAlbum.scope + + "\") passed as a value for \"scope\" for ContextAlbumForm form."); + } + if (!contextAlbum.itemSchema || !contextAlbum.itemSchema.name || contextAlbum.itemSchema.name == "" + || !contextAlbum.itemSchema.version || contextAlbum.itemSchema.version == "") { + console.warn("Invalid value (\"" + contextAlbum.itemSchema + + "\") passed as a value for \"itemSchema\" for ContextAlbumForm form."); + } + if (!contextAlbum.isWritable || contextAlbum.isWritable == "") { + console.warn("Invalid value (\"" + contextAlbum.isWritable + + "\") passed as a value for \"isWritable\" for ContextAlbumForm form."); + } + } + } + } else { + console + .warn("Invalid operation (\"" + + operation + + "\") specified for ContextAlbumForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported"); + } + + var contentelement = document.createElement("editContextAlbumFormDiv"); + var formDiv = document.createElement("div"); + contentelement.appendChild(formDiv); + formDiv.setAttribute("id", "editContextAlbumFormDiv"); + formDiv.setAttribute("class", "editContextAlbumFormDiv"); + + var headingSpan = document.createElement("h2"); + formDiv.appendChild(headingSpan); + headingSpan.innerHTML = "Context Item Album Editor"; + + var form = document.createElement("editContextAlbumForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "editContextAlbumForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + form.setAttribute("createEditOrView", createEditOrView); + + var formul = document.createElement("ul"); + form.appendChild(formul); + + var nameLI = document.createElement("li"); + formul.appendChild(nameLI); + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + nameLabel.setAttribute("for", "editContextAlbumFormNameInput"); + nameLabel.innerHTML = "Name: "; + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + nameInput.setAttribute("id", "editContextAlbumFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editContextAlbumFormameInput"); + nameInput.setAttribute("class", "field ebInput"); + nameInput.setAttribute("placeholder", "name"); + if (contextAlbum && contextAlbum.key && contextAlbum.key.name) { + nameInput.value = contextAlbum.key.name; + } + if (createEditOrView != "CREATE") { + nameInput.readOnly = true; + } + + var versionLI = document.createElement("li"); + formul.appendChild(versionLI); + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + versionLabel.setAttribute("for", "editContextAlbumFormVersionInput"); + versionLabel.innerHTML = "Version: "; + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + versionInput.setAttribute("id", "editContextAlbumFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "editContextAlbumFormVersionInput"); + versionInput.setAttribute("class", "field ebInput"); + versionInput.setAttribute("placeholder", "0.0.1"); + if (contextAlbum && contextAlbum.key && contextAlbum.key.version) { + versionInput.value = contextAlbum.key.version; + } + if (createEditOrView != "CREATE") { + versionInput.readOnly = true; + } + + var uuidLI = document.createElement("li"); + formul.appendChild(uuidLI); + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + uuidLabel.setAttribute("for", "editContextAlbumFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + uuidInput.setAttribute("id", "editContextAlbumFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "editContextAlbumFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + if (contextAlbum && contextAlbum.uuid) { + uuidInput.value = contextAlbum.uuid; + } + if (createEditOrView != "CREATE") { + uuidInput.readOnly = true; + } + + var disabled = (createEditOrView != "CREATE" && createEditOrView != "EDIT"); + + var descriptionLI = document.createElement("li"); + formul.appendChild(descriptionLI); + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "editContextAlbumFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + descriptionTextArea.setAttribute("id", "editContextAlbumFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "editContextAlbumFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + if (contextAlbum && contextAlbum.description) { + descriptionTextArea.value = contextAlbum.description; + } + descriptionTextArea.readOnly = disabled; + + var albumScopeLI = document.createElement("li"); + formul.appendChild(albumScopeLI); + var albumScopeLabel = document.createElement("label"); + albumScopeLI.appendChild(albumScopeLabel); + albumScopeLabel.setAttribute("for", "editContextAlbumFormAlbumScopeInput"); + albumScopeLabel.innerHTML = "Context Album Scope: "; + var albumScopeInput = document.createElement("input"); + albumScopeLI.appendChild(albumScopeInput); + albumScopeInput.setAttribute("id", "editContextAlbumFormAlbumScopeInput"); + albumScopeInput.setAttribute("type", "text"); + albumScopeInput.setAttribute("name", "editContextAlbumFormAlbumScopeInput"); + albumScopeInput.setAttribute("class", "field-albumScope ebInput"); + albumScopeInput.setAttribute("placeholder", "Global"); + if (contextAlbum && contextAlbum.scope) { + albumScopeInput.value = contextAlbum.scope; + } + albumScopeInput.readOnly = disabled; + + var albumReadOnlyLI = document.createElement("li"); + formul.appendChild(albumReadOnlyLI); + var albumReadOnlyLabel = document.createElement("label"); + albumReadOnlyLI.appendChild(albumReadOnlyLabel); + albumReadOnlyLabel.setAttribute("for", "editContextAlbumFormAlbumReadOnlyInput"); + albumReadOnlyLabel.innerHTML = "Read Only? "; + var albumReadOnlyInput = document.createElement("input"); + albumReadOnlyInput.setAttribute("type", "checkbox"); + albumReadOnlyLI.appendChild(albumReadOnlyInput); + albumReadOnlyInput.setAttribute("id", "editContextAlbumFormAlbumReadOnlyCheckbox"); + albumReadOnlyInput.setAttribute("name", "editContextAlbumFormAlbumReadOnlyCheckbox"); + albumReadOnlyInput.setAttribute("class", "field-albumReadonlyCheckbox"); + if (contextAlbum && contextAlbum.isWritable != null && contextAlbum.isWritable === false) { + albumReadOnlyInput.checked = true; + } else { + albumReadOnlyInput.checked = false; + } + albumReadOnlyInput.disabled = disabled; + + var albumItemSchemaLI = document.createElement("li"); + formul.appendChild(albumItemSchemaLI); + var albumItemSchemaLabel = document.createElement("label"); + albumItemSchemaLI.appendChild(albumItemSchemaLabel); + albumItemSchemaLabel.setAttribute("for", "editContextAlbumFormAlbumItemSchema"); + albumItemSchemaLabel.innerHTML = "Schema/Type of Album items: "; + var selected = null; + if (contextAlbum && contextAlbum.itemSchema != null && contextAlbum.itemSchema.name != null + && contextAlbum.itemSchema.version != null && contextAlbum.itemSchema.name != "" + && contextAlbum.itemSchema.version != "") { + selected = { + "name" : contextAlbum.itemSchema.name, + "version" : contextAlbum.itemSchema.version, + "displaytext" : contextAlbum.itemSchema.name + ":" + contextAlbum.itemSchema.version, + "contextAlbum" : contextAlbum + }; + } + var selectDiv = dropdownList("editContextAlbumFormAlbumItemSchema", contextSchemas, selected, disabled, null); + if (selectDiv == null) { + console.error("Cannot create a Context Album because there are no contextSchemas to add to it"); + alert("Cannot create a Context Album because there are no contextSchemas to add to it"); + editContextAlbumForm_cancelPressed(); + } else { + albumItemSchemaLI.appendChild(selectDiv); + } + + var inputLI = document.createElement("li"); + formul.appendChild(inputLI); + if (createEditOrView == "CREATE") { + var generateUUIDInput = document.createElement("button"); + inputLI.appendChild(generateUUIDInput); + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + generateUUIDInput.onclick = editContextAlbumForm_generateUUIDPressed; + generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value"); + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + } + if (createEditOrView == "CREATE") { + var generateDescriptionInput = document.createElement("button"); + inputLI.appendChild(generateDescriptionInput); + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + generateDescriptionInput.onclick = editContextAlbumForm_generateDescriptionPressed; + generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value"); + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + } + + var cancelInput = document.createElement("button"); + inputLI.appendChild(cancelInput); + cancelInput.setAttribute("id", "cancel"); + cancelInput.setAttribute("class", "ebBtn ebBtn_large"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + cancelInput.onclick = editContextAlbumForm_cancelPressed; + cancelInput.innerHTML = cancelInput.getAttribute("value"); + + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + + var submitInput = document.createElement("button"); + inputLI.appendChild(submitInput); + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "ebBtn ebBtn_large"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + submitInput.onclick = editContextAlbumForm_submitPressed; + submitInput.innerHTML = submitInput.getAttribute("value"); + } + + formParent.appendChild(contentelement); + scrollToTop(); +} + +function editContextAlbumForm_generateUUIDPressed() { + document.getElementById("editContextAlbumFormUuidInput").value = formUtils_generateUUID(); +} + +function editContextAlbumForm_generateDescriptionPressed() { + document.getElementById("editContextAlbumFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("editContextAlbumFormNameInput").value, document + .getElementById("editContextAlbumFormVersionInput").value, document + .getElementById("editContextAlbumFormUuidInput").value); +} + +function editContextAlbumForm_cancelPressed() { + apexUtils_removeElement("editContextAlbumFormDiv"); + contextAlbumTab_reset(); +} + +function editContextAlbumForm_submitPressed() { + var createEditOrView = $('#editContextAlbumForm').attr("createEditOrView"); + if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) { + console.error("Invalid operation \"" + createEditOrView + + "\" passed to editContextAlbumForm_submitPressed function. Edit failed"); + apexUtils_removeElement("editContextAlbumFormDiv"); + contextAlbumTab_reset(); + return; + } + + var name = $('#editContextAlbumFormNameInput').val(); + var version = $('#editContextAlbumFormVersionInput').val(); + + var selectedschema = document.getElementById("editContextAlbumFormAlbumItemSchema_dropdownList").selectedOption; + if (selectedschema == null) { + alert("Context Album \"" + name + "\" has no selected Album Item Schema/Type"); + return false; + } + var itemschema = { + "name" : selectedschema.name, + "version" : selectedschema.version + }; + + var scope = $('#editContextAlbumFormAlbumScopeInput').val().toUpperCase(); + if (scope != "APPLICATION" && scope != "EXTERNAL" && scope != "GLOBAL") { + var message = "Are you sure you want to set the scope ContextAlbum to \"" + scope + + "\"? Currently the only scope supported are: \"APPLICATION\", \"EXTERNAL\" and \"GLOBAL\""; + if (!apexUtils_areYouSure(message)) { + return false; + } + } + var readonly = $('#editContextAlbumFormAlbumReadOnlyCheckbox').prop('checked'); + if (readonly && scope != "EXTERNAL") { + message = "Are you sure you want to set the scope ContextAlbum to \"" + + scope + + "\" while it is set as Read Only. It only makes sense to use readonly for \"EXTERNAL\" Context Albums. If this Album is readonly it cannot be set!"; + if (!apexUtils_areYouSure(message)) { + return false; + } + } + if (!readonly && scope == "EXTERNAL") { + message = "Are you sure you want to set the scope ContextAlbum to \"" + + scope + + "\" while it is not set as Read Only. It only makes sense to use readonly for \"EXTERNAL\" Context Albums since EXTERNAL context cannot be set in policies."; + if (!apexUtils_areYouSure(message)) { + return false; + } + } + + var jsonString = JSON.stringify({ + "name" : name, + "version" : version, + "uuid" : $('#editContextAlbumFormUuidInput').val(), + "description" : $('#editContextAlbumFormDescriptionTextArea').val(), + "itemSchema" : itemschema, + "scope" : scope, + "writeable" : !readonly + }); + + if (createEditOrView == "CREATE") { + var requestURL = window.restRootURL + "/ContextAlbum/Create"; + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editContextAlbumFormDiv"); + contextAlbumTab_reset(); + keyInformationTab_reset() + }); + } else if (createEditOrView == "EDIT") { + requestURL = window.restRootURL + "/ContextAlbum/Update"; + ajax_put(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editContextAlbumFormDiv"); + contextAlbumTab_reset(); + keyInformationTab_reset() + }); + } + +} + +export { + editContextAlbumForm_viewContextAlbum, + editContextAlbumForm_generateUUIDPressed, + editContextAlbumForm_generateDescriptionPressed, + editContextAlbumForm_editContextAlbum, + editContextAlbumForm_deleteContextAlbum, + editContextAlbumForm_createContextAlbum, + editContextAlbumForm_cancelPressed, + editContextAlbumForm_activate, + editContextAlbumForm_submitPressed +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js new file mode 100644 index 0000000..821e5f6 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js @@ -0,0 +1,128 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {rightClickMenu_scopePreserver} from './contextMenu'; +import {createTable} from './ApexTable'; +import {ajax_get} from './ApexAjax'; +import {apexUtils_removeElement} from "./ApexUtils"; + +function contextAlbumTab_reset() { + contextAlbumTab_deactivate(); + contextAlbumTab_activate(); +} + +function contextAlbumTab_activate() { + contextAlbumTab_create(); + + var requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#contextAlbumTableBody").find("tr:gt(0)").remove(); + + for (let value of data.messages.message) { + var contextAlbum = JSON.parse(value).apexContextAlbum; + + var contextAlbumRow_tr = document.createElement("tr"); + + var contextAlbumTableRow = + "" + + contextAlbum.key.name + ":" + contextAlbum.key.version + + "" + + "" + + contextAlbum.scope + + "" + + "" + + contextAlbum.isWritable + + "" + + "" + + contextAlbum.itemSchema.name + ":" + contextAlbum.itemSchema.version + + "" ; + + contextAlbumRow_tr.innerHTML = contextAlbumTableRow; + contextAlbumRow_tr.addEventListener('contextmenu', rightClickMenu_scopePreserver("contextAlbumTabContent", "contextAlbum", contextAlbum.key.name, contextAlbum.key.version)); + + $("#contextAlbumTableBody").append(contextAlbumRow_tr); + + } + }); +} + +function contextAlbumTab_deactivate() { + apexUtils_removeElement("contextAlbumTabContent"); +} + +function contextAlbumTab_create() { + var contextAlbumTab = document.getElementById("contextAlbumsTab"); + + //Testing purposes + if(contextAlbumTab === null){ + contextAlbumTab = document.createElement('contextAlbumsTab'); + } + + var contextAlbumTabContent = document.getElementById("contextAlbumTabContent"); + if (contextAlbumTabContent != null) { + return + } + + contextAlbumTabContent = document.createElement("contextAlbumTabContent"); + contextAlbumTab.appendChild(contextAlbumTabContent); + contextAlbumTabContent.setAttribute("id", "contextAlbumTabContent"); + contextAlbumTabContent.addEventListener('contextmenu', rightClickMenu_scopePreserver("contextAlbumTabContent", "contextAlbum",null, null)); + + var contextAlbumTable = createTable("contextAlbumTable"); + contextAlbumTabContent.appendChild(contextAlbumTable); + + var contextAlbumTableHeader = document.createElement("thead"); + contextAlbumTable.appendChild(contextAlbumTableHeader); + contextAlbumTableHeader.setAttribute("id", "contextAlbumTableHeader"); + + var contextAlbumTableHeaderRow = document.createElement("tr"); + contextAlbumTableHeader.appendChild(contextAlbumTableHeaderRow); + contextAlbumTableHeaderRow.setAttribute("id", "contextAlbumTableHeaderRow"); + + var contextAlbumTableKeyHeader = document.createElement("th"); + contextAlbumTableHeaderRow.appendChild(contextAlbumTableKeyHeader); + contextAlbumTableKeyHeader.setAttribute("id", "contextAlbumTableKeyHeader"); + contextAlbumTableKeyHeader.appendChild(document.createTextNode("Context Album")); + + var contextAlbumTableScopeHeader = document.createElement("th"); + contextAlbumTableHeaderRow.appendChild(contextAlbumTableScopeHeader); + contextAlbumTableScopeHeader.setAttribute("id", "contextAlbumTableScopeHeader"); + contextAlbumTableScopeHeader.appendChild(document.createTextNode("Scope")); + + var contextAlbumTableWriteableHeader = document.createElement("th"); + contextAlbumTableHeaderRow.appendChild(contextAlbumTableWriteableHeader); + contextAlbumTableWriteableHeader.setAttribute("id", "contextAlbumTableWritableHeader"); + contextAlbumTableWriteableHeader.appendChild(document.createTextNode("Writable")); + + var contextAlbumTableItemSchemaHeader = document.createElement("th"); + contextAlbumTableHeaderRow.appendChild(contextAlbumTableItemSchemaHeader); + contextAlbumTableItemSchemaHeader.setAttribute("id", "contextAlbumTableItemSchemaHeader"); + contextAlbumTableItemSchemaHeader.appendChild(document.createTextNode("Item Schema")); + + var contextAlbumTableBody = document.createElement("tbody"); + contextAlbumTable.appendChild(contextAlbumTableBody); + contextAlbumTable.setAttribute("id", "contextAlbumTableBody"); +} + +//Testing purposes +export { contextAlbumTab_reset, contextAlbumTab_create, contextAlbumTab_activate, contextAlbumTab_deactivate }; \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaEditForm.js new file mode 100644 index 0000000..06c4402 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaEditForm.js @@ -0,0 +1,385 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {ajax_delete, ajax_getWithKeyInfo, ajax_post, ajax_put} from "./ApexAjax"; +import {apexUtils_removeElement, apexUtils_emptyElement, scrollToTop, apexUtils_areYouSure} from "./ApexUtils"; +import { + formUtils_generateDescription, + formUtils_generateUUID +} from "./ApexFormUtils"; +import {contextSchemaTab_reset} from "./ApexContextSchemaTab"; +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; + +function editContextSchemaForm_createContextSchema(formParent) { + return editContextSchemaForm_activate(formParent, "CREATE", null); +} + +function editContextSchemaForm_deleteContextSchema(parent, name, version) { + var message = "Are you sure you want to delete ContextSchema \"" + name + ":" + version + "\"?"; + if (apexUtils_areYouSure(message)) { + var requestURL = window.restRootURL + "/ContextSchema/Delete?name=" + name + "&version=" + version; + ajax_delete(requestURL, function(data) { + apexUtils_removeElement("editContextSchemaFormDiv"); + contextSchemaTab_reset(); + keyInformationTab_reset() + }); + } +} + +function editContextSchemaForm_viewContextSchema(parent, name, version) { + var requestURL = window.restRootURL + "/ContextSchema/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexContextSchema", function(contextSchema) { + editContextSchemaForm_activate(parent, "VIEW", contextSchema); + }); +} + +function editContextSchemaForm_editContextSchema(formParent, name, version) { + var requestURL = window.restRootURL + "/ContextSchema/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexContextSchema", function(contextSchema) { + editContextSchemaForm_activate(formParent, "EDIT", contextSchema); + }); +} + +function editContextSchemaForm_activate(parent, operation, contextSchema) { + apexUtils_removeElement("editContextSchemaFormDiv"); + var formParent = document.getElementById(parent); + + //Testing purposes + if(formParent === null){ + formParent = document.createElement("formParentTest") + } + apexUtils_emptyElement(parent); + + var createEditOrView = ""; + + if (!operation) { + console.warn("No operation specified for ContextSchemaForm form") + } else { + createEditOrView = operation.toUpperCase(); + } + + if (createEditOrView == "EDIT" || createEditOrView == "VIEW") { + + if (!contextSchema) { + console.warn("Invalid value (\"" + contextSchema + + "\") passed as a value for \"contextSchema\" for ContextSchemaForm form."); + } else { + if (!contextSchema.key || !contextSchema.key.name || contextSchema.key.name == "") { + console.warn("Invalid value (\"" + contextSchema.key.name + + "\") passed as a value for \"name\" for ContextSchemaForm form."); + } + if (!contextSchema.key || !contextSchema.key.version || contextSchema.key.version == "") { + console.warn("Invalid value (\"" + contextSchema.key.version + + "\") passed as a value for \"version\" for ContextSchemaForm form."); + } + if (!contextSchema.uuid || contextSchema.uuid == "") { + console.warn("Invalid value (\"" + contextSchema.uuid + + "\") passed as a value for \"uuid\" for ContextSchemaForm form."); + } + if (createEditOrView == "VIEW") { + if (!contextSchema.description) { + console.warn("Invalid value (\"" + contextSchema.description + + "\") passed as a value for \"description\" for ContextSchemaForm form."); + } + if (!contextSchema.schemaFlavour || contextSchema.schemaFlavour == "") { + console.warn("Invalid value (\"" + contextSchema.schemaFlavour + + "\") passed as a value for \"schemaFlavour\" for ContextSchemaForm form."); + } + if (!contextSchema.schemaDefinition || contextSchema.schemaDefinition == "") { + console.warn("Invalid value (\"" + contextSchema.schemaDefinition + + "\") passed as a value for \"schemaDefinition\" for ContextSchemaForm form."); + } + } + } + } else { + console + .warn("Invalid operation (\"" + + operation + + "\") specified for ContextSchemaForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported"); + } + + var contentelement = document.createElement("editContextSchemaFormDiv"); + var formDiv = document.createElement("div"); + contentelement.appendChild(formDiv); + formDiv.setAttribute("id", "editContextSchemaFormDiv"); + formDiv.setAttribute("class", "editContextSchemaFormDiv"); + + var headingSpan = document.createElement("h2"); + headingSpan.innerHTML = "Context Item Schema Editor"; + formDiv.appendChild(headingSpan); + + var form = document.createElement("editContextSchemaForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "editContextSchemaForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + form.setAttribute("createEditOrView", createEditOrView); + + var formul = document.createElement("ul"); + form.appendChild(formul); + + var nameLI = document.createElement("li"); + formul.appendChild(nameLI); + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + nameLabel.setAttribute("for", "editContextSchemaFormNameInput"); + nameLabel.innerHTML = "Name: "; + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + nameInput.setAttribute("id", "editContextSchemaFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editContextSchemaFormameInput"); + nameInput.setAttribute("class", "field ebInput"); + nameInput.setAttribute("placeholder", "name"); + if (contextSchema && contextSchema.key && contextSchema.key.name) { + nameInput.value = contextSchema.key.name; + } + if (createEditOrView != "CREATE") { + nameInput.readOnly = true; + } + + var versionLI = document.createElement("li"); + formul.appendChild(versionLI); + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + versionLabel.setAttribute("for", "editContextSchemaFormVersionInput"); + versionLabel.innerHTML = "Version: "; + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + versionInput.setAttribute("id", "editContextSchemaFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "editContextSchemaFormVersionInput"); + versionInput.setAttribute("class", "field ebInput"); + versionInput.setAttribute("placeholder", "0.0.1"); + if (contextSchema && contextSchema.key && contextSchema.key.version) { + versionInput.value = contextSchema.key.version; + } + if (createEditOrView != "CREATE") { + versionInput.readOnly = true; + } + + var uuidLI = document.createElement("li"); + formul.appendChild(uuidLI); + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + uuidLabel.setAttribute("for", "editContextSchemaFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + uuidInput.setAttribute("id", "editContextSchemaFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "editContextSchemaFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + if (contextSchema && contextSchema.uuid) { + uuidInput.value = contextSchema.uuid; + } + if (createEditOrView != "CREATE") { + uuidInput.readOnly = true; + } + + var descriptionLI = document.createElement("li"); + formul.appendChild(descriptionLI); + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "editContextSchemaFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + descriptionTextArea.setAttribute("id", "editContextSchemaFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "editContextSchemaFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + if (contextSchema && contextSchema.description) { + descriptionTextArea.value = contextSchema.description; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + descriptionTextArea.readOnly = true; + } + + var schemaFlavourLI = document.createElement("li"); + formul.appendChild(schemaFlavourLI); + var schemaFlavourLabel = document.createElement("label"); + schemaFlavourLI.appendChild(schemaFlavourLabel); + schemaFlavourLabel.setAttribute("for", "editContextSchemaFormSchemaFlavourInput"); + schemaFlavourLabel.innerHTML = "Schema Flavour: "; + var schemaFlavourInput = document.createElement("input"); + schemaFlavourLI.appendChild(schemaFlavourInput); + schemaFlavourInput.setAttribute("id", "editContextSchemaFormSchemaFlavourInput"); + schemaFlavourInput.setAttribute("type", "text"); + schemaFlavourInput.setAttribute("name", "editContextSchemaFormSchemaFlavourInput"); + schemaFlavourInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + schemaFlavourInput.setAttribute("placeholder", "Java"); + if (contextSchema && contextSchema.schemaFlavour) { + schemaFlavourInput.value = contextSchema.schemaFlavour; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + schemaFlavourInput.readOnly = true; + } + + var schemaDefinitionLI = document.createElement("li"); + formul.appendChild(schemaDefinitionLI); + var schemaDefinitionLabel = document.createElement("label"); + schemaDefinitionLI.appendChild(schemaDefinitionLabel); + schemaDefinitionLabel.setAttribute("for", "editContextSchemaFormSchemaDefinitionInput"); + schemaDefinitionLabel.innerHTML = "Schema Definition: "; + var schemaDefinitionInput = document.createElement("textarea"); + schemaDefinitionLI.appendChild(schemaDefinitionInput); + schemaDefinitionInput.setAttribute("id", "editContextSchemaFormSchemaDefinitionInput"); + schemaDefinitionInput.setAttribute("type", "text"); + schemaDefinitionInput.setAttribute("name", "editContextSchemaFormSchemaDefinitionInput"); + schemaDefinitionInput.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + schemaDefinitionInput.setAttribute("placeholder", "java.lang.String"); + if (contextSchema && contextSchema.schemaDefinition) { + schemaDefinitionInput.value = contextSchema.schemaDefinition; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + schemaDefinitionInput.readOnly = true; + } + + var inputLI = document.createElement("li"); + formul.appendChild(inputLI); + if (createEditOrView == "CREATE") { + var generateUUIDInput = document.createElement("button"); + inputLI.appendChild(generateUUIDInput); + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + generateUUIDInput.onclick = editContextSchemaForm_generateUUIDPressed; + generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value"); + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + } + if (createEditOrView == "CREATE") { + var generateDescriptionInput = document.createElement("button"); + inputLI.appendChild(generateDescriptionInput); + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + generateDescriptionInput.onclick = editContextSchemaForm_generateDescriptionPressed; + generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value"); + + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + } + + var cancelInput = document.createElement("button"); + inputLI.appendChild(cancelInput); + cancelInput.setAttribute("id", "cancel"); + cancelInput.setAttribute("class", "ebBtn ebBtn_large"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + cancelInput.onclick = editContextSchemaForm_cancelPressed; + cancelInput.innerHTML = cancelInput.getAttribute("value"); + + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + + var submitInput = document.createElement("button"); + inputLI.appendChild(submitInput); + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "ebBtn ebBtn_large"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + submitInput.onclick = editContextSchemaForm_submitPressed; + submitInput.innerHTML = submitInput.getAttribute("value"); + } + + formParent.appendChild(contentelement); + scrollToTop(); +} + +function editContextSchemaForm_generateUUIDPressed() { + document.getElementById("editContextSchemaFormUuidInput").value = formUtils_generateUUID(); +} + +function editContextSchemaForm_generateDescriptionPressed() { + document.getElementById("editContextSchemaFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("editContextSchemaFormNameInput").value, document + .getElementById("editContextSchemaFormVersionInput").value, document + .getElementById("editContextSchemaFormUuidInput").value); +} + +function editContextSchemaForm_cancelPressed() { + apexUtils_removeElement("editContextSchemaFormDiv"); + contextSchemaTab_reset(); +} + +function editContextSchemaForm_submitPressed() { + var createEditOrView = $('#editContextSchemaForm').attr("createEditOrView"); + if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) { + console.error("Invalid operation \"" + createEditOrView + + "\" passed to editContextSchemaForm_submitPressed function. Edit failed"); + apexUtils_removeElement("editContextSchemaFormDiv"); + contextSchemaTab_reset(); + return; + } + + var name = $('#editContextSchemaFormNameInput').val(); + var version = $('#editContextSchemaFormVersionInput').val() + + var requestURL; + + var jsonString = JSON.stringify({ + "name" : name, + "version" : version, + "uuid" : $('#editContextSchemaFormUuidInput').val(), + "description" : $('#editContextSchemaFormDescriptionTextArea').val(), + "schemaFlavour" : $('#editContextSchemaFormSchemaFlavourInput').val(), + "schemaDefinition" : $('#editContextSchemaFormSchemaDefinitionInput').val(), + }); + + if (createEditOrView == "CREATE") { + requestURL = window.restRootURL + "/ContextSchema/Create"; + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editContextSchemaFormDiv"); + contextSchemaTab_reset(); + keyInformationTab_reset() + }); + } else if (createEditOrView == "EDIT") { + requestURL = window.restRootURL + "/ContextSchema/Update"; + ajax_put(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editContextSchemaFormDiv"); + contextSchemaTab_reset(); + keyInformationTab_reset() + }); + } + +} + +export { + editContextSchemaForm_activate, editContextSchemaForm_cancelPressed, editContextSchemaForm_createContextSchema, + editContextSchemaForm_deleteContextSchema, editContextSchemaForm_editContextSchema, editContextSchemaForm_generateDescriptionPressed, + editContextSchemaForm_generateUUIDPressed, editContextSchemaForm_submitPressed, editContextSchemaForm_viewContextSchema +}; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js new file mode 100644 index 0000000..fa5ed6f --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js @@ -0,0 +1,123 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const {ajax_get} = require("./ApexAjax"); +const {createTable} = require('./ApexTable'); +const {rightClickMenu_scopePreserver} = require('./contextMenu'); +const {apexUtils_escapeHtml, apexUtils_removeElement} = require('./ApexUtils'); + +function contextSchemaTab_reset() { + contextSchemaTab_deactivate(); + contextSchemaTab_activate(); +} +function contextSchemaTab_activate() { + contextSchemaTab_create(); + + var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#contextSchemaTableBody").find("tr:gt(0)").remove(); + + for (let value of data.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + + var contextSchemaRow_tr = document.createElement("tr"); + var contextSchemaid = contextSchema.key.name + ":" + contextSchema.key.version; + + var contextSchemaRow = + "" + + contextSchemaid + + "" + + "" + + contextSchema.schemaFlavour + + "" + + "" + + apexUtils_escapeHtml(contextSchema.schemaDefinition) + + ""; + + contextSchemaRow_tr.innerHTML = contextSchemaRow; + contextSchemaRow_tr.addEventListener('contextmenu', rightClickMenu_scopePreserver("contextSchemaTabContent", "ContextSchema", contextSchema.key.name, contextSchema.key.version)); + + $("#contextSchemaTableBody").append(contextSchemaRow_tr); + } + }); +} + +function contextSchemaTab_deactivate() { + apexUtils_removeElement("contextSchemaTabContent"); +} + +function contextSchemaTab_create() { + var contextSchemaTab = document.getElementById("contextSchemasTab"); + + //Testing purposes + if(contextSchemaTab === null){ + contextSchemaTab = document.createElement('contextSchemasTab'); + } + + var contextSchemaTabContent = document.getElementById("contextSchemaTabContent"); + if (contextSchemaTabContent != null) { + return + } + + contextSchemaTabContent = document.createElement("contextSchemaTabContent"); + contextSchemaTab.appendChild(contextSchemaTabContent); + contextSchemaTabContent.setAttribute("id", "contextSchemaTabContent"); + contextSchemaTabContent.addEventListener('contextmenu', rightClickMenu_scopePreserver("contextSchemaTabContent", "ContextSchema",null,null)); + + var contextSchemaTable = createTable("contextSchemaTable"); + contextSchemaTabContent.appendChild(contextSchemaTable); + + var contextSchemaTableHeader = document.createElement("thead"); + contextSchemaTable.appendChild(contextSchemaTableHeader); + contextSchemaTableHeader.setAttribute("id", "contextSchemaTableHeader"); + + var contextSchemaTableHeaderRow = document.createElement("tr"); + contextSchemaTableHeader.appendChild(contextSchemaTableHeaderRow); + contextSchemaTableHeaderRow.setAttribute("id", "contextSchemaTableHeaderRow"); + + var contextSchemaTableKeyHeader = document.createElement("th"); + contextSchemaTableHeaderRow.appendChild(contextSchemaTableKeyHeader); + contextSchemaTableKeyHeader.setAttribute("id", "contextSchemaTableKeyHeader"); + contextSchemaTableKeyHeader.appendChild(document.createTextNode("Context Item")); + + var contextSchemaTableSchemaFlavourHeader = document.createElement("th"); + contextSchemaTableHeaderRow.appendChild(contextSchemaTableSchemaFlavourHeader); + contextSchemaTableSchemaFlavourHeader.setAttribute("id", "contextSchemaTableJavatypeHeader"); + contextSchemaTableSchemaFlavourHeader.appendChild(document.createTextNode("Schema Flavour")); + + var contextSchemaTableSchemaDefHeader = document.createElement("th"); + contextSchemaTableHeaderRow.appendChild(contextSchemaTableSchemaDefHeader); + contextSchemaTableSchemaDefHeader.setAttribute("id", "contextSchemaTableJavatypeHeader"); + contextSchemaTableSchemaDefHeader.appendChild(document.createTextNode("Context Item Schema Definition")); + + var contextSchemaTableBody = document.createElement("tbody"); + contextSchemaTable.appendChild(contextSchemaTableBody); + contextSchemaTable.setAttribute("id", "contextSchemaTableBody"); +} + +//Testing purposes +export { + contextSchemaTab_activate, + contextSchemaTab_deactivate, + contextSchemaTab_reset, + contextSchemaTab_create +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js new file mode 100644 index 0000000..fef9278 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js @@ -0,0 +1,588 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import { formUtils_generateDescription, formUtils_generateUUID } from "./ApexFormUtils"; +import {dropdownList} from "./dropdownList"; +import {ajax_post, ajax_put, ajax_delete, ajax_get, ajax_getWithKeyInfo} from "./ApexAjax"; +import {eventTab_reset} from "./ApexEventTab"; +import {apexUtils_areYouSure, apexUtils_removeElement, apexUtils_emptyElement, createAddFormButton, scrollToTop} from './ApexUtils'; +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; + +function editEventForm_deleteEvent(parent, name, version) { + var message = "Are you sure you want to delete Event \"" + name + ":" + version + "\"?"; + if (apexUtils_areYouSure(message)) { + var requestURL = window.restRootURL + "/Event/Delete?name=" + name + "&version=" + version; + ajax_delete(requestURL, function(data) { + apexUtils_removeElement("editEventFormDiv"); + eventTab_reset(); + keyInformationTab_reset() + }); + } +} + +function editEventForm_viewEvent(formParent, name, version) { + editEventForm_editEvent_inner(formParent, name, version, "VIEW"); +} + +function editEventForm_editEvent(formParent, name, version) { + editEventForm_editEvent_inner(formParent, name, version, "EDIT"); +} + +function editEventForm_createEvent(formParent) { + // Get all contextSchemas too for event params + var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + var dt = { + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }; + contextSchemas.push(dt); + } + editEventForm_activate(formParent, "CREATE", null, contextSchemas); + }); +} + +function editEventForm_editEvent_inner(formParent, name, version, viewOrEdit) { + var requestURL = window.restRootURL + "/Event/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexEvent", function(event) { + // Get all contextSchemas too for event params + requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + editEventForm_activate(formParent, viewOrEdit, event, contextSchemas); + }); + }); +} + +function editEventForm_activate(parent, operation, event, contextSchemas) { + apexUtils_removeElement("editEventFormDiv"); + var formParent = document.getElementById(parent); + + //Testing purposes + if(formParent === null){ + formParent = document.createElement('testFormParent'); + } + apexUtils_emptyElement(parent); + + var createEditOrView = ""; + if (!operation) { + console.warn("No operation specified for EventForm form") + } else { + createEditOrView = operation.toUpperCase() + } + + if (createEditOrView == "EDIT" || createEditOrView == "VIEW") { + + if (!event) { + console.warn("Invalid value (\"" + event + "\") passed as a value for \"event\" for EventForm form."); + } else { + if (!event.key || !event.key.name || event.key.name == "") { + console.warn("Invalid value (\"" + event.key.name + + "\") passed as a value for \"name\" for EventForm form."); + } + if (!event.key || !event.key.version || event.key.version == "") { + console.warn("Invalid value (\"" + event.key.version + + "\") passed as a value for \"version\" for EventForm form."); + } + if (!event.uuid || event.uuid == "") { + console.warn("Invalid value (\"" + event.uuid + + "\") passed as a value for \"uuid\" for EventForm form."); + } + } + } else { + console.warn("Invalid operation (\"" + operation + + "\") specified for EventForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported"); + } + + var contentelement = document.createElement("editEventFormDiv"); + var formDiv = document.createElement("div"); + contentelement.appendChild(formDiv); + formDiv.setAttribute("id", "editEventFormDiv"); + formDiv.setAttribute("class", "editEventFormDiv"); + + var headingSpan = document.createElement("h2"); + formDiv.appendChild(headingSpan); + + headingSpan.innerHTML = "Event Editor"; + + var form = document.createElement("editEventForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "editEventForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + form.setAttribute("createEditOrView", createEditOrView); + + var formul = document.createElement("ul"); + form.appendChild(formul); + + var nameLI = document.createElement("li"); + formul.appendChild(nameLI); + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + nameLabel.setAttribute("for", "editEventFormNameInput"); + nameLabel.innerHTML = "Name: "; + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + nameInput.setAttribute("id", "editEventFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editEventFormNameInput"); + nameInput.setAttribute("class", "field ebInput"); + nameInput.setAttribute("placeholder", "name"); + if (event && event.key && event.key.name) { + nameInput.value = event.key.name; + } + if (createEditOrView != "CREATE") { + nameInput.readOnly = true; + } + + var versionLI = document.createElement("li"); + formul.appendChild(versionLI); + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + versionLabel.setAttribute("for", "editEventFormVersionInput"); + versionLabel.innerHTML = "Version: "; + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + versionInput.setAttribute("id", "editEventFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "editEventFormVersionInput"); + versionInput.setAttribute("class", "field ebInput"); + versionInput.setAttribute("placeholder", "0.0.1"); + if (event && event.key && event.key.version) { + versionInput.value = event.key.version; + } + if (createEditOrView != "CREATE") { + versionInput.readOnly = true; + } + + var uuidLI = document.createElement("li"); + formul.appendChild(uuidLI); + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + uuidLabel.setAttribute("for", "editEventFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + uuidInput.setAttribute("id", "editEventFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "editEventFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + if (event && event.uuid) { + uuidInput.value = event.uuid; + } + if (createEditOrView != "CREATE") { + uuidInput.readOnly = true; + } + + var descriptionLI = document.createElement("li"); + formul.appendChild(descriptionLI); + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "editEventFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + descriptionTextArea.setAttribute("id", "editEventFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "editEventFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + if (event && event.description) { + descriptionTextArea.value = event.description; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + descriptionTextArea.readOnly = true; + } + + var namespaceLI = document.createElement("li"); + formul.appendChild(namespaceLI); + var namespaceLabel = document.createElement("label"); + namespaceLI.appendChild(namespaceLabel); + namespaceLabel.setAttribute("for", "editEventFormNamespaceInput"); + namespaceLabel.innerHTML = "Namespace: "; + var namespaceInput = document.createElement("input"); + namespaceLI.appendChild(namespaceInput); + namespaceInput.setAttribute("id", "editEventFormNamespaceInput"); + namespaceInput.setAttribute("type", "text"); + namespaceInput.setAttribute("name", "editEventFormNamespaceInput"); + namespaceInput.setAttribute("class", "field-namespace ebInput ebInput ebInput_width_full"); + namespaceInput.setAttribute("placeholder", ""); + if (event && event.nameSpace) { + namespaceInput.value = event.nameSpace; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + namespaceInput.readOnly = true; + } + + var sourceLI = document.createElement("li"); + formul.appendChild(sourceLI); + var sourceLabel = document.createElement("label"); + sourceLI.appendChild(sourceLabel); + sourceLabel.setAttribute("for", "editEventFormSourceInput"); + sourceLabel.innerHTML = "Source: "; + var sourceInput = document.createElement("input"); + sourceLI.appendChild(sourceInput); + sourceInput.setAttribute("id", "editEventFormSourceInput"); + sourceInput.setAttribute("type", "text"); + sourceInput.setAttribute("name", "editEventFormSourceInput"); + sourceInput.setAttribute("class", "field-source ebInput"); + sourceInput.setAttribute("placeholder", ""); + if (event && event.source) { + sourceInput.value = event.source; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + sourceInput.readOnly = true; + } + + var targetLI = document.createElement("li"); + formul.appendChild(targetLI); + var targetLabel = document.createElement("label"); + targetLI.appendChild(targetLabel); + targetLabel.setAttribute("for", "editEventFormTargetInput"); + targetLabel.innerHTML = "Target: "; + var targetInput = document.createElement("input"); + targetLI.appendChild(targetInput); + targetInput.setAttribute("id", "editEventFormTargetInput"); + targetInput.setAttribute("type", "text"); + targetInput.setAttribute("name", "editEventFormTargetInput"); + targetInput.setAttribute("class", "field-target ebInput"); + targetInput.setAttribute("placeholder", ""); + if (event && event.target) { + targetInput.value = event.target; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + targetInput.readOnly = true; + } + + var parametersLI = document.createElement("li"); + formul.appendChild(parametersLI); + var parametersLabel = document.createElement("label"); + parametersLI.appendChild(parametersLabel); + parametersLabel.setAttribute("for", "editEventFormParametersTable"); + parametersLabel.innerHTML = "Event Parameters: "; + var paramstable = document.createElement("table"); + paramstable.setAttribute("id", "editEventFormParametersTable"); + paramstable.setAttribute("name", "editEventFormParametersTable"); + paramstable.setAttribute("class", "table-eventparam"); + parametersLI.appendChild(paramstable); + var paramstable_head = document.createElement("thead"); + paramstable.appendChild(paramstable_head); + var paramstable_head_tr = document.createElement("tr"); + paramstable_head.appendChild(paramstable_head_tr); + paramstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var paramstable_head_th = document.createElement("th"); + paramstable_head_tr.appendChild(paramstable_head_th); + paramstable_head_th.innerHTML = "Parameter Name: "; + paramstable_head_th.setAttribute("class", "table-eventparam-heading form-heading"); + paramstable_head_th = document.createElement("th"); + paramstable_head_tr.appendChild(paramstable_head_th); + paramstable_head_th.innerHTML = "Parameter Type/Schema: "; + paramstable_head_th.setAttribute("class", "table-eventparam-heading form-heading"); + paramstable_head_th = document.createElement("th"); + paramstable_head_tr.appendChild(paramstable_head_th); + paramstable_head_th.innerHTML = "Optional: "; + paramstable_head_th.setAttribute("class", "table-eventparam-heading form-heading"); + var paramstable_body = document.createElement("tbody"); + paramstable.appendChild(paramstable_body); + // Add the parameters + if (event && event.parameter && event.parameter.entry) { + for (let fieldEntry of event.parameter.entry) { + var contextSchema = fieldEntry.value.fieldSchemaKey; + var optional = fieldEntry.value.optional; + contextSchema["displaytext"] = contextSchema.name + ":" + contextSchema.version; + editEventForm_addEventParam(paramstable_body, (createEditOrView == "VIEW"), fieldEntry.key, optional, + contextSchema, contextSchemas); + } + } + // add the New Parameter button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var paramTR = document.createElement("tr"); + paramTR.setAttribute("class", "field-eventparam-tr.new"); + paramstable_body.appendChild(paramTR); + var paramTD = document.createElement("td"); + paramTD.setAttribute("colspan", "4"); + paramTR.appendChild(paramTD); + var addParamInput = createAddFormButton(); + paramTD.appendChild(addParamInput); + addParamInput.onclick = function() { + editEventForm_addEventParam(paramstable_body, false, null, false, null, contextSchemas); + }; + } + + var inputLI = document.createElement("li"); + formul.appendChild(inputLI); + if (createEditOrView == "CREATE") { + var generateUUIDInput = document.createElement("button"); + inputLI.appendChild(generateUUIDInput); + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + generateUUIDInput.onclick = editEventForm_generateUUIDPressed; + generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value"); + + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + } + if (createEditOrView == "CREATE") { + var generateDescriptionInput = document.createElement("button"); + inputLI.appendChild(generateDescriptionInput); + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + generateDescriptionInput.onclick = editEventForm_generateDescriptionPressed; + generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value"); + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + } + + var cancelInput = document.createElement("button"); + inputLI.appendChild(cancelInput); + cancelInput.setAttribute("id", "cancel"); + cancelInput.setAttribute("class", "ebBtn ebBtn_large"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + cancelInput.onclick = editEventForm_cancelPressed; + cancelInput.innerHTML = cancelInput.getAttribute("value"); + + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + var submitInput = document.createElement("button"); + inputLI.appendChild(submitInput); + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "ebBtn ebBtn_large"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + + submitInput.onclick = editEventForm_submitPressed; + submitInput.innerHTML = submitInput.getAttribute("value") + } + + formParent.appendChild(contentelement); + scrollToTop(); +} + +function editEventForm_addEventParam(parentTBody, disabled, name, optional, contextSchema, contextSchemas) { + var random_suffix = formUtils_generateUUID(); + + var paramTR = parentTBody.insertRow(parentTBody.rows.length - 1); + paramTR.setAttribute("param_id", random_suffix); + paramTR.setAttribute("class", "field-eventparam-tr"); + if (name == null && contextSchema == null && !disabled) { + paramTR.setAttribute("class", "field-eventparam-tr.new field-add-new"); + $(paramTR).show("fast"); + } + var deleteTD = document.createElement("td"); + paramTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(paramTR).hide("fast", function() { + paramTR.parentNode.removeChild(paramTR); + }); + }; + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + + var nameTD = document.createElement("td"); + paramTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editEventFormParamName" + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editEventFormParamName" + "_" + random_suffix); + nameInput.setAttribute("class", "field-eventparam-name ebInput ebInput_width_xLong"); + if (name == null && contextSchema == null && !disabled) { + nameInput.setAttribute("class", "field-eventparam-name.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "Parameter Name"); + if (name) { + nameInput.value = name; + } + nameInput.readOnly = disabled; + + var contextSchemaTD = document.createElement("td"); + paramTR.appendChild(contextSchemaTD); + + var selectDiv = dropdownList("editEventFormParamContextSchema" + "_" + random_suffix, contextSchemas, + contextSchema, disabled, null) + contextSchemaTD.appendChild(selectDiv); + + var paramOptionalTD = document.createElement("td"); + paramOptionalTD.setAttribute("class", "field-checkbox-center"); + paramTR.appendChild(paramOptionalTD); + var paramOptionalInput = document.createElement("input"); + paramOptionalInput.setAttribute("type", "checkbox"); + paramOptionalInput.setAttribute("id", "editEventFormParamOptional" + "_" + random_suffix); + paramOptionalInput.setAttribute("name", "editEventFormParamOptional" + "_" + random_suffix); + paramOptionalInput.setAttribute("class", "field-eventparam-optional"); + if (name == null && contextSchema == null && !disabled) { + paramOptionalInput.setAttribute("class", "field-eventparam-optional.new"); + } + if (optional) { + paramOptionalInput.checked = true; + } else { + paramOptionalInput.checked = false; + } + paramOptionalInput.disabled = disabled; + paramOptionalTD.appendChild(paramOptionalInput); +} + +function editEventForm_generateUUIDPressed() { + document.getElementById("editEventFormUuidInput").value = formUtils_generateUUID(); +} + +function editEventForm_generateDescriptionPressed() { + document.getElementById("editEventFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("editEventFormNameInput").value, + document.getElementById("editEventFormVersionInput").value, document + .getElementById("editEventFormUuidInput").value); +} + +function editEventForm_cancelPressed() { + apexUtils_removeElement("editEventFormDiv"); + eventTab_reset(); +} + +function editEventForm_submitPressed() { + var createEditOrView = document.getElementById("editEventForm").getAttribute("createEditOrView"); + if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) { + console.error("Invalid operation \"" + createEditOrView + + "\" passed to editEventForm_submitPressed function. Edit failed"); + apexUtils_removeElement("editEventFormDiv"); + eventTab_reset(); + return; + } + + var name = document.getElementById('editEventFormNameInput').value; + var version = document.getElementById('editEventFormVersionInput').value; + + var eventbean_params = null; + // get the event parameters + var paramstablerows = document.getElementById("editEventFormParametersTable").rows; + if (paramstablerows && paramstablerows.length >= 2) { + eventbean_params = new Object(); + for (var i = 1; i < paramstablerows.length - 1; i++) { + var paramTR = paramstablerows[i]; + if (paramTR && paramTR.getAttribute("param_id")) { + var param_id = paramTR.getAttribute("param_id"); + var paramname = document.getElementById("editEventFormParamName" + "_" + param_id).value; + var paramoptional = document.getElementById("editEventFormParamOptional" + "_" + param_id).checked; + var param_dt = document.getElementById("editEventFormParamContextSchema" + "_" + param_id + + "_dropdownList").selectedOption; + if (eventbean_params[paramname]) { + alert("Event \"" + name + "\" contains more than one Parameter called \"" + paramname + "\""); + return false; + } + if (param_dt == null) { + alert("Event \"" + name + "\" has no selected Context Item Schema for the Parameter called \"" + + paramname + "\""); + return false; + } + var param_dt_name = param_dt.name; + var param_dt_version = param_dt.version; + eventbean_params[paramname] = { + "localName" : paramname, + "name" : param_dt_name, + "version" : param_dt_version, + "optional" : paramoptional + }; + } + } + } + // generate an event bean to json-ify and send in rest request + var eventbean = { + "name" : name, + "version" : version, + "uuid" : document.getElementById('editEventFormUuidInput').value, + "description" : document.getElementById('editEventFormDescriptionTextArea').value, + "source" : document.getElementById('editEventFormSourceInput').value, + "target" : document.getElementById('editEventFormTargetInput').value, + "nameSpace" : document.getElementById('editEventFormNamespaceInput').value, + "parameters" : eventbean_params + } + var jsonString = JSON.stringify(eventbean); + + var requestURL; + + if (createEditOrView == "CREATE") { + requestURL = window.restRootURL + "/Event/Create"; + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editEventFormDiv"); + eventTab_reset(); + keyInformationTab_reset() + }); + } else if (createEditOrView == "EDIT") { + requestURL = window.restRootURL + "/Event/Update"; + ajax_put(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editEventFormDiv"); + eventTab_reset(); + keyInformationTab_reset() + }); + } + +} + +export { + editEventForm_activate, + editEventForm_addEventParam, + editEventForm_cancelPressed, + editEventForm_createEvent, + editEventForm_deleteEvent, + editEventForm_editEvent, + editEventForm_editEvent_inner, + editEventForm_generateDescriptionPressed, + editEventForm_generateUUIDPressed, + editEventForm_submitPressed, + editEventForm_viewEvent +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js new file mode 100644 index 0000000..44458c2 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js @@ -0,0 +1,157 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + + +import {ajax_get} from "./ApexAjax"; +import {rightClickMenu_scopePreserver} from "./contextMenu"; +import {createTable} from "./ApexTable"; +import {apexUtils_removeElement} from "./ApexUtils"; + +function eventTab_reset() { + eventTab_deactivate(); + eventTab_activate(); +} + +function eventTab_activate() { + eventTab_create(); + + var requestURL = window.restRootURL + "/Event/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#eventTableBody").find("tr:gt(0)").remove(); + + + for (let value of data.messages.message) { + var event = JSON.parse(value).apexEvent; + + var eventTableRow_tr = document.createElement("tr"); + var eventid = event.key.name + ":" + event.key.version; + + var eventTableRow = + "" + + eventid + + "" + + "" + + event.nameSpace + + "" + + "" + + event.source + + "" + + "" + + event.target + + ""; + + eventTableRow += ""; + + for (let fieldEntry of event.parameter.entry) { + + eventTableRow += + "" + + ""; + } + + eventTableRow += "
ParameterParameter Type/SchemaOptional
" + + fieldEntry.key + + "" + + fieldEntry.value.fieldSchemaKey.name + ":" + fieldEntry.value.fieldSchemaKey.version + + "" + + fieldEntry.value.optional + + "
"; + + eventTableRow_tr.innerHTML = eventTableRow; + + eventTableRow_tr.addEventListener('contextmenu', rightClickMenu_scopePreserver("eventTabContent", "Event", event.key.name, event.key.version)); + + $("#eventTableBody").append(eventTableRow_tr); + } + }); +} + +function eventTab_deactivate() { + apexUtils_removeElement("eventTabContent"); +} + +function eventTab_create() { + var eventTab = document.getElementById("eventsTab"); + + //Testing purposes + if(eventTab === null){ + eventTab = document.createElement('eventsTab'); + } + + var eventTabContent = document.getElementById("eventTabContent"); + if (eventTabContent != null) { + return + } + + eventTabContent = document.createElement("eventTabContent"); + eventTab.appendChild(eventTabContent); + eventTabContent.setAttribute("id", "eventTabContent"); + eventTabContent.addEventListener('contextmenu', rightClickMenu_scopePreserver("eventTabContent", "Event", null, null)); + + var eventTable = createTable("eventTable"); + eventTabContent.appendChild(eventTable); + + var eventTableHeader = document.createElement("thead"); + eventTable.appendChild(eventTableHeader); + eventTableHeader.setAttribute("id", "eventTableHeader"); + + var eventTableHeaderRow = document.createElement("tr"); + eventTableHeader.appendChild(eventTableHeaderRow); + eventTableHeaderRow.setAttribute("id", "eventTableHeaderRow"); + + var eventTableKeyHeader = document.createElement("th"); + eventTableHeaderRow.appendChild(eventTableKeyHeader); + eventTableKeyHeader.setAttribute("id", "eventTableKeyHeader"); + eventTableKeyHeader.appendChild(document.createTextNode("Event")); + + var eventTableNamespaceHeader = document.createElement("th"); + eventTableHeaderRow.appendChild(eventTableNamespaceHeader); + eventTableNamespaceHeader.setAttribute("id", "eventTableNamespaceHeader"); + eventTableNamespaceHeader.appendChild(document.createTextNode("Name Space")); + + var eventTableSourceHeader = document.createElement("th"); + eventTableHeaderRow.appendChild(eventTableSourceHeader); + eventTableSourceHeader.setAttribute("id", "eventTableSourceHeader"); + eventTableSourceHeader.appendChild(document.createTextNode("Source")); + + var eventTableTargetHeader = document.createElement("th"); + eventTableHeaderRow.appendChild(eventTableTargetHeader); + eventTableTargetHeader.setAttribute("id", "eventTableTargetHeader"); + eventTableTargetHeader.appendChild(document.createTextNode("Target")); + + var eventTableParameterHeader = document.createElement("th"); + eventTableHeaderRow.appendChild(eventTableParameterHeader); + eventTableParameterHeader.setAttribute("id", "eventTableParameterHeader"); + eventTableParameterHeader.appendChild(document.createTextNode("Parameters")); + + var eventTableBody = document.createElement("tbody"); + eventTable.appendChild(eventTableBody); + eventTable.setAttribute("id", "eventTableBody"); +} + +export { + eventTab_reset, + eventTab_activate, + eventTab_deactivate, + eventTab_create +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js new file mode 100644 index 0000000..de9edf3 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {resultForm_activate} from "./ApexResultForm"; + +const {ajax_put, ajax_get, ajax_getOKOrFail} = require("./ApexAjax"); +const {pageControl_modelMode} = require("./ApexPageControl"); +const {modelFileName} = require("./ApexNewModelForm"); + +function files_fileOpen() { + $('').on('change', function() { + var reader = new FileReader(); + var fileName = this.files[0].name; + reader.readAsText(this.files[0]); + + reader.onload = function(event) { + var requestURL = window.restRootURL + "/Model/Load"; + ajax_put(requestURL, event.target.result, function(resultData) { + localStorage.setItem("apex_model_loaded", true); + requestURL = window.restRootURL + "/Model/GetKey"; + ajax_get(requestURL, function(data) { + var modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + pageControl_modelMode(modelKey.name, modelKey.version, fileName); + }); + }); + }; + }).click(); +} + +function files_fileDownload() { + var requestURL = window.restRootURL + "/Model/Download"; + + var downloadLink = document.createElement("a"); + document.body.appendChild(downloadLink); + downloadLink.download = modelFileName; + downloadLink.href = requestURL; + downloadLink.click(); + document.body.removeChild(downloadLink); +} + +function files_fileUpload() { + let requestURL = window.restRootURL + "/Model/Upload"; + const userId = new URLSearchParams(window.location.search).get('userId'); + if (userId) { + requestURL = requestURL + "?userId=" + userId; + } + ajax_getOKOrFail(requestURL, function(data) { + let uploadResultString = ""; + for (let value of data.messages.message) { + uploadResultString += (value + "\n"); + } + resultForm_activate(document.getElementById("mainArea"), "Model Upload Result", uploadResultString); + }); +} + +export {files_fileUpload, files_fileDownload, files_fileOpen}; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFormUtils.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFormUtils.js new file mode 100644 index 0000000..f2a5983 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFormUtils.js @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function formUtils_generateUUID() { // Public Domain/MIT + var d = new Date().getTime(); + if (typeof performance !== 'undefined' && typeof performance.now === 'function') { + d += performance.now(); // use high-precision timer if available + } + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); + }); +} + +function formUtils_generateDescription(name, version, uuid) { + if (!name) { + name = "null"; + } + if (!version) { + version = "null"; + } + if (!uuid) { + uuid = "null"; + } + + return "Generated description for a concept called \"" + name + "\" with version \"" + version + + "\" and UUID \"" + uuid + "\""; +} + +export {formUtils_generateDescription, formUtils_generateUUID}; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js new file mode 100644 index 0000000..6cfc28d --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js @@ -0,0 +1,117 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {ajax_get} from "./ApexAjax"; +import {apexUtils_escapeHtml, apexUtils_removeElement} from "./ApexUtils"; +import {createTable} from "./ApexTable"; + +function keyInformationTab_reset() { + keyInformationTab_deactivate(); + keyInformationTab_activate(); +} + +function keyInformationTab_activate() { + keyInformationTab_create(); + + var requestURL = window.restRootURL + "/KeyInformation/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#keyInformationTableBody").find("tr:gt(0)").remove(); + + for (let value of data.messages.message) { + var keyInfo = JSON.parse(value).apexKeyInfo; + + var keyInfoRow_tr = document.createElement("tr"); + var keyInfoRow = + "" + + keyInfo.key.name + ":" + keyInfo.key.version + + "" + + "" + + apexUtils_escapeHtml(keyInfo.UUID) + + "" + + "" + + apexUtils_escapeHtml(keyInfo.description) + + ""; + keyInfoRow_tr.innerHTML = keyInfoRow; + // keyInfoRow_tr.addEventListener('contextmenu', + // rightClickMenu_scopePreserver("keyInformationTabContent", + // "KeyInformation", keyInfo.key.name, keyInfo.key.version)); + $("#keyInformationTableBody").append(keyInfoRow_tr); + + } + }); +} + +function keyInformationTab_deactivate() { + apexUtils_removeElement("keyInformationTabContent"); +} + +function keyInformationTab_create() { + var keyInformationTab = document.getElementById("keyInformationTab"); + + var keyInformationTabContent = document.getElementById("keyInformationTabContent"); + if (keyInformationTabContent != null) { + return + } + + keyInformationTabContent = document.createElement("keyInformationTabContent"); + keyInformationTab.appendChild(keyInformationTabContent); + keyInformationTabContent.setAttribute("id", "keyInformationTabContent"); + + var keyInformationTable = createTable("keyInformationTable"); + keyInformationTable.oncontextmenu = new Function("return false;") + keyInformationTabContent.appendChild(keyInformationTable); + + var keyInformationTableHeader = document.createElement("thead"); + keyInformationTable.appendChild(keyInformationTableHeader); + keyInformationTableHeader.setAttribute("id", "keyInformationTableHeader"); + + var keyInformationTableHeaderRow = document.createElement("tr"); + keyInformationTableHeader.appendChild(keyInformationTableHeaderRow); + keyInformationTableHeaderRow.setAttribute("id", "keyInformationTableHeaderRow"); + + var keyInformationTableKeyHeader = document.createElement("th"); + keyInformationTableHeaderRow.appendChild(keyInformationTableKeyHeader); + keyInformationTableKeyHeader.setAttribute("id", "keyInformationTableKeyHeader"); + keyInformationTableKeyHeader.appendChild(document.createTextNode("Key Information")); + + var keyInformationTableUUIDHeader = document.createElement("th"); + keyInformationTableHeaderRow.appendChild(keyInformationTableUUIDHeader); + keyInformationTableUUIDHeader.setAttribute("id", "keyInformationTableUUIDHeader"); + keyInformationTableUUIDHeader.appendChild(document.createTextNode("UUID")); + + var keyInformationTableDescriptionHeader = document.createElement("th"); + keyInformationTableHeaderRow.appendChild(keyInformationTableDescriptionHeader); + keyInformationTableDescriptionHeader.setAttribute("id", "keyInformationTableDescriptionHeader"); + keyInformationTableDescriptionHeader.appendChild(document.createTextNode("Description")); + + var keyInformationTableBody = document.createElement("tbody"); + keyInformationTable.appendChild(keyInformationTableBody); + keyInformationTable.setAttribute("id", "keyInformationTableBody"); +} + +export { + keyInformationTab_activate, + keyInformationTab_create, + keyInformationTab_deactivate, + keyInformationTab_reset +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js new file mode 100644 index 0000000..3fc3cd5 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js @@ -0,0 +1,180 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {pageControl_noModelMode, pageControl_modelMode} from "./ApexPageControl"; +import {newModelForm_activate} from "./ApexNewModelForm"; +import {files_fileDownload, files_fileOpen, files_fileUpload} from "./ApexFiles"; +import {ajax_delete, ajax_get} from "./ApexAjax"; +import {modelHandling_analyse, modelHandling_validate} from "./ApexModelHandling"; + +var restRootURL = null; +var modelFileName = null; + +$(document).ready(function() { + $("#menu").fileMenu({ + slideSpeed : 200 + }); + pageControl_noModelMode(); + main_getRestRootURL(); + $(".content").fadeIn(); +}); + +$("#menu li").not(".emptyMessage").click(function() { + switch (this.id) { + case "menuFileNew": + newModelForm_activate(document.getElementById("mainArea")); + break; + + case "menuFileOpen": + files_fileOpen(); + break; + case "menuFileDownload": + files_fileDownload(); + break; + case "menuFileUpload": + files_fileUpload(); + break; + + case "menuFileClear": + if (confirm("Clear the current model?")) { + var requestURL = restRootURL + "/Model/Delete"; + + ajax_delete(requestURL, function(data) { + localStorage.removeItem("apex_model_loaded"); + localStorage.removeItem("apex_tab_index"); + $("#mainTabs").tabs("option", "active", 0); + pageControl_noModelMode(); + }); + } + break; + + case "menuFileNewSession": + clearLocalStorage(); + location.reload(); + break; + + case "menuFileClose": + if (confirm("Close Apex Editor?")) { + clearLocalStorage(); + window.location.href = window.location.href + "close.html"; + } + break; + + case "menuModelAnalyse": + modelHandling_analyse(); + break; + + case "menuModelValidate": + modelHandling_validate(); + break; + + case "menuConceptsContextSchemas": + $("#mainTabs").tabs("option", "active", 0); + break; + case "menuConceptsEvents": + $("#mainTabs").tabs("option", "active", 1); + break; + case "menuConceptsContextAlbums": + $("#mainTabs").tabs("option", "active", 2); + break; + case "menuConceptsTasks": + $("#mainTabs").tabs("option", "active", 3); + break; + case "menuConceptsPolicies": + $("#mainTabs").tabs("option", "active", 4); + break; + case "menuConceptsKeyInformation": + $("#mainTabs").tabs("option", "active", 5); + break; + + default: + break; + } +}); + +function main_getRestRootURL() { + const href = location.protocol + + "//" + + window.location.hostname + + (location.port ? ':' + location.port : '') + + (location.pathname.endsWith("/editor/") ? location.pathname.substring(0, location.pathname + .indexOf("editor/")) : location.pathname); + const restContext = "apexservices/editor/"; + if (localStorage.getItem("apex_session")) { + restRootURL = href + restContext + localStorage.getItem("apex_session"); + window.restRootURL = restRootURL; + const requestURL = restRootURL + "/Model/GetKey"; + ajax_get(requestURL, function(data) { + $("#statusMessageTable").append(" REST root URL set to: " + restRootURL + ""); + if (localStorage.getItem("apex_model_loaded")) { + const modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + pageControl_modelMode(modelKey.name, modelKey.version, modelFileName); + if (localStorage.getItem("apex_tab_index")) { + $("#mainTabs").tabs({ + active: localStorage.getItem("apex_tab_index") + }); + } + } + }); + } else { + const createSessionURL = href + restContext + "-1/Session/Create"; + + ajax_get(createSessionURL, function(data) { + localStorage.setItem("apex_session", data.messages.message[0]); + restRootURL = href + restContext + localStorage.getItem("apex_session"); + window.restRootURL = restRootURL; + $("#statusMessageTable").append(" REST root URL set to: " + restRootURL + ""); + }); + } +} + +function clearLocalStorage() { + localStorage.removeItem("apex_session"); + localStorage.removeItem("apex_model_loaded"); + localStorage.removeItem("apex_tab_index"); +} + +/* Inline Message */ +var ebInlineMessageHeight = $(".ebInlineMessage").height(); + +$(".ebInlineMessage").mouseenter(function(e) { + e.stopPropagation(); + $(this).stop(); + var contentHeight = $(this).children('.ebInlineMessage-contentHolder').height(); + if (contentHeight > ebInlineMessageHeight) { + $(".ebInlineMessage").animate({ + height : contentHeight + 12 + }, 200); + } +}); + +$(".ebInlineMessage").mouseleave(function(e) { + e.stopPropagation(); + $(this).stop(); + $(".ebInlineMessage").animate({ + height : ebInlineMessageHeight + }, 200); +}); + +export { + clearLocalStorage, + main_getRestRootURL +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js new file mode 100644 index 0000000..9c04102 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {ajax_getOKOrFail, ajax_get} from "./ApexAjax"; +import {resultForm_activate} from "./ApexResultForm"; + +function modelHandling_analyse() { + var requestURL = window.restRootURL + "/Model/Analyse"; + + ajax_get(requestURL, function(data) { + resultForm_activate(document.getElementById("mainArea"), "Model Analysis Result", data.messages.message[0]); + }); +} + +function modelHandling_validate() { + var requestURL = window.restRootURL + "/Model/Validate"; + + ajax_getOKOrFail(requestURL, function(data) { + var validationResultString = ""; + for (var i = 1; i < data.messages.message.length; i++) { + validationResultString += (data.messages.message[i] + "\n"); + } + resultForm_activate(document.getElementById("mainArea"), "Model Validation Result", validationResultString); + }); +} + +export { + modelHandling_analyse, + modelHandling_validate +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js new file mode 100644 index 0000000..d7e5ccd --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js @@ -0,0 +1,241 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import { formUtils_generateDescription, formUtils_generateUUID } from "./ApexFormUtils"; +import {apexUtils_removeElement} from "./ApexUtils"; +import {pageControl_modelMode} from "./ApexPageControl"; +import {ajax_post, ajax_get} from "./ApexAjax"; +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; + +function newModelForm_activate(formParent) { + apexUtils_removeElement("newModelFormDiv"); + + var contentelement = document.createElement("newModelFormDiv"); + var formDiv = document.createElement("div"); + var backgroundDiv = document.createElement("div"); + backgroundDiv.setAttribute("id", "newModelDivBackground"); + backgroundDiv.setAttribute("class", "newModelDivBackground"); + + backgroundDiv.appendChild(formDiv); + contentelement.appendChild(backgroundDiv); + formParent.appendChild(contentelement); + + formDiv.setAttribute("id", "newModelFormDiv"); + formDiv.setAttribute("class", "newModelFormDiv"); + + var headingSpan = document.createElement("span"); + formDiv.appendChild(headingSpan); + + headingSpan.setAttribute("class", "headingSpan"); + headingSpan.innerHTML = "Model Details"; + + var form = document.createElement("newModelForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "newModelForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + + var ul = document.createElement("ul"); + form.appendChild(ul); + + var nameLI = document.createElement("li"); + form.appendChild(nameLI); + + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + + nameLabel.setAttribute("for", "newModelFormNameInput"); + nameLabel.innerHTML = "Name: "; + + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + + nameInput.setAttribute("id", "newModelFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "newModelFormameInput"); + nameInput.setAttribute("class", "field ebInput ebInput_width_xLong"); + nameInput.setAttribute("placeholder", "name"); + + var versionLI = document.createElement("li"); + form.appendChild(versionLI); + + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + + versionLabel.setAttribute("for", "newModelFormVersionInput"); + versionLabel.innerHTML = "Version: "; + + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + + versionInput.setAttribute("id", "newModelFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "newModelFormVersionInput"); + versionInput.setAttribute("class", "field ebInput ebInput_width_xLong"); + versionInput.setAttribute("placeholder", "0.0.1"); + + var uuidLI = document.createElement("li"); + form.appendChild(uuidLI); + + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + + uuidLabel.setAttribute("for", "newModelFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + + uuidInput.setAttribute("id", "newModelFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "newModelFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + + var descriptionLI = document.createElement("li"); + form.appendChild(descriptionLI); + + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "newModelFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + + descriptionTextArea.setAttribute("id", "newModelFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "newModelFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + + var inputLI = document.createElement("li"); + form.appendChild(inputLI); + + var generateUUIDInput = document.createElement("input"); + inputLI.appendChild(generateUUIDInput); + + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "button ebBtn"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + + generateUUIDInput.onclick = newModelForm_generateUUIDPressed; + + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + + var generateDescriptionInput = document.createElement("input"); + inputLI.appendChild(generateDescriptionInput); + + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "button ebBtn"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + + generateDescriptionInput.onclick = newModelForm_generateDescriptionPressed; + + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + + var cancelInput = document.createElement("input"); + inputLI.appendChild(cancelInput); + + cancelInput.setAttribute("id", "generateDescription"); + cancelInput.setAttribute("class", "button ebBtn"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + + cancelInput.onclick = newModelForm_cancelPressed; + + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + + var submitInput = document.createElement("input"); + inputLI.appendChild(submitInput); + + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "button ebBtn"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + + submitInput.onclick = newModelForm_submitPressed; +} + +function newModelForm_generateUUIDPressed() { + document.getElementById("newModelFormUuidInput").value = formUtils_generateUUID(); +} + +function newModelForm_generateDescriptionPressed() { + document.getElementById("newModelFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("newModelFormNameInput").value, document.getElementById("newModelFormVersionInput").value, + document.getElementById("newModelFormUuidInput").value); +} + +function newModelForm_cancelPressed() { + apexUtils_removeElement("newModelDivBackground"); +} + +function newModelForm_submitPressed() { + var jsonString = JSON.stringify({ + "name" : $('#newModelFormNameInput').val(), + "version" : $('#newModelFormVersionInput').val(), + "uuid" : $('#newModelFormUuidInput').val(), + "description" : $('#newModelFormDescriptionTextArea').val() + }); + + var requestURL = window.restRootURL + "/Model/Create"; + + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("newModelDivBackground"); + + requestURL = window.restRootURL + "/Model/GetKey"; + + ajax_get(requestURL, function(data) { + var modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + var modelFileName = modelKey.name + ".json"; + pageControl_modelMode(modelKey.name, modelKey.version, modelFileName); + }); + keyInformationTab_reset() + }); +} + +export { + newModelForm_activate, + newModelForm_cancelPressed, + newModelForm_generateDescriptionPressed, + newModelForm_generateUUIDPressed, + newModelForm_submitPressed +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js new file mode 100644 index 0000000..7b1b884 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js @@ -0,0 +1,302 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import { + contextSchemaTab_activate, + contextSchemaTab_deactivate +} from "./ApexContextSchemaTab"; +import {eventTab_activate, eventTab_deactivate} from "./ApexEventTab"; +import { + contextAlbumTab_activate, + contextAlbumTab_deactivate +} from "./ApexContextAlbumTab"; +import {taskTab_activate, taskTab_deactivate} from "./ApexTaskTab"; +import {policyTab_activate, policyTab_deactivate} from "./ApexPolicyTab"; +import { + keyInformationTab_activate, + keyInformationTab_deactivate +} from "./ApexKeyInformationTab"; +import {clearLocalStorage} from "./ApexMain"; + +function pageControl_modelMode(name, version, fileName) { + $('#modelName').html(name); + $('#modelVersion').html(version); + $('#modelFileName').html(fileName ? fileName : "N/A"); + + $("#menuFileNew").addClass("disabled"); + $("#menuFileOpen").addClass("disabled"); + $("#menuFileDownload").removeClass("disabled"); + $("#menuFileUpload").removeClass("disabled"); + $("#menuFileClear").removeClass("disabled"); + $("#menuModelAnalyse").removeClass("disabled"); + $("#menuModelValidate").removeClass("disabled"); + $("#menuModelCompare").removeClass("disabled"); + $("#menuModelSplit").removeClass("disabled"); + $("#menuModelMerge").removeClass("disabled"); + $("#menuConceptsContextSchemas").removeClass("disabled"); + $("#menuConceptsEvents").removeClass("disabled"); + $("#menuConceptsContextAlbums").removeClass("disabled"); + $("#menuConceptsTasks").removeClass("disabled"); + $("#menuConceptsPolicies").removeClass("disabled"); + $("#menuConceptsKeyInformation").removeClass("disabled"); + + $(".modelTag").show("slide", { + direction : "left" + }, 200); + + try{ + $("#mainTabs").tabs({ + classes : { + "ui-tabs-tab" : "ui-tabs-tab-custom", + "ui-tabs-active" : "ui-tabs-active-custom", + "ui-tabs-anchor" : "ui-tabs-anchor-custom" + }, + disabled : false, + activate : function(event, ui) { + localStorage.setItem("apex_tab_index", ui.newTab.index()); + } + }); + } + catch(err){ + console.error('TypeError! Failed to get tabs function'); + } + + + contextSchemaTab_activate(); + eventTab_activate(); + contextAlbumTab_activate(); + taskTab_activate(); + policyTab_activate(); + keyInformationTab_activate(); + showPlaceholder(false); +} + +function pageControl_noModelMode() { + $(".modelTag").hide("slide", { + direction : "left" + }, 200); + + $('#modelName').html("N/A"); + $('#modelVersion').html("N/A"); + $('#modelFileName').html("N/A"); + + $("#menuFileNew").removeClass("disabled"); + $("#menuFileOpen").removeClass("disabled"); + $("#menuFileDownload").addClass("disabled"); + $("#menuFileUpload").addClass("disabled"); + $("#menuFileClear").addClass("disabled"); + $("#menuModelAnalyse").addClass("disabled"); + $("#menuModelValidate").addClass("disabled"); + $("#menuModelCompare").addClass("disabled"); + $("#menuModelSplit").addClass("disabled"); + $("#menuModelMerge").addClass("disabled"); + $("#menuConceptsContextSchemas").addClass("disabled"); + $("#menuConceptsEvents").addClass("disabled"); + $("#menuConceptsContextAlbums").addClass("disabled"); + $("#menuConceptsTasks").addClass("disabled"); + $("#menuConceptsPolicies").addClass("disabled"); + $("#menuConceptsKeyInformation").addClass("disabled"); + + contextSchemaTab_deactivate(); + eventTab_deactivate(); + contextAlbumTab_deactivate(); + taskTab_deactivate(); + policyTab_deactivate(); + keyInformationTab_deactivate(); + try{ + $("#mainTabs").tabs({ + classes : { + "ui-tabs-tab" : "ui-tabs-tab-custom", + "ui-tabs-active" : "ui-tabs-active-custom", + "ui-tabs-anchor" : "ui-tabs-anchor-custom" + }, + disabled : [ 0, 1, 2, 3, 4, 5 ] + }); + } + catch(err){ + console.error('TypeError! Failed to get tabs function'); + } + showPlaceholder(true); +} + +function pageControl_busyMode() { + $("#menuFile").addClass("disabled"); + $("#menuFileNew").addClass("disabled"); + $("#menuFileOpen").addClass("disabled"); + $("#menuFileDownload").addClass("disabled"); + $("#menuFileClear").addClass("disabled"); + $("#menuModelAnalyse").addClass("disabled"); + $("#menuModelValidate").addClass("disabled"); + $("#menuModelCompare").addClass("disabled"); + $("#menuModelSplit").addClass("disabled"); + $("#menuModelMerge").addClass("disabled"); + $("#menuConceptsContextSchemas").addClass("disabled"); + $("#menuConceptsEvents").addClass("disabled"); + $("#menuConceptsContextAlbums").addClass("disabled"); + $("#menuConceptsTasks").addClass("disabled"); + $("#menuConceptsPolicies").addClass("disabled"); + $("#menuConceptsKeyInformation").addClass("disabled"); + try{ + $("#mainTabs").tabs({ + classes : { + "ui-tabs-tab" : "ui-tabs-tab-custom", + "ui-tabs-active" : "ui-tabs-active-custom", + "ui-tabs-anchor" : "ui-tabs-anchor-custom" + }, + disabled : false + }); + } + catch(err){ + console.error('TypeError! Failed to get tabs function'); + } + contextSchemaTab_activate(); + eventTab_activate(); + contextAlbumTab_activate(); + taskTab_activate(); + policyTab_activate(); + keyInformationTab_activate(); + showPlaceholder(false); +} + +function pageControl_readyMode() { + $("#menuFile").removeClass("disabled"); + $("#menuFileNew").removeClass("disabled"); + $("#menuFileOpen").removeClass("disabled"); + $("#menuFileDownload").removeClass("disabled"); + $("#menuFileClear").removeClass("disabled"); + $("#menuModelAnalyse").removeClass("disabled"); + $("#menuModelValidate").removeClass("disabled"); + $("#menuModelCompare").removeClass("disabled"); + $("#menuModelSplit").removeClass("disabled"); + $("#menuModelMerge").removeClass("disabled"); + $("#menuConceptsContextSchemas").removeClass("disabled"); + $("#menuConceptsEvents").removeClass("disabled"); + $("#menuConceptsContextAlbums").removeClass("disabled"); + $("#menuConceptsTasks").removeClass("disabled"); + $("#menuConceptsPolicies").removeClass("disabled"); + $("#menuConceptsKeyInformation").removeClass("disabled"); + + contextSchemaTab_deactivate(); + eventTab_deactivate(); + contextAlbumTab_deactivate(); + taskTab_deactivate(); + policyTab_deactivate(); + keyInformationTab_deactivate(); + try{ + $("#mainTabs").tabs({ + classes : { + "ui-tabs-tab" : "ui-tabs-tab-custom", + "ui-tabs-active" : "ui-tabs-active-custom", + "ui-tabs-anchor" : "ui-tabs-anchor-custom" + }, + disabled : [ 0, 1, 2, 3, 4, 5 ] + }); + } + catch(err){ + console.error('TypeError! Failed to get tabs function'); + } + showPlaceholder(true); +} + +function pageControl_successStatus(data) { + $('#statusString').html(data.result); + $("#statusMessageTable").empty(); + + if (data.ok) { + $('#statusString').css("color", "green"); + $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_tick"); + } else { + $('#statusString').css("color", "red"); + $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_error"); + for (let value of data.messages.message) { + $("#statusMessageTable").append("" + value + ""); + } + // A session with session ID "0" does not exist + var sessionDoesNotExistStringStart = "A session with session ID "; + var sessionDoesNotExistStringEnd = " does not exist"; + if (data.content.indexOf(sessionDoesNotExistStringStart) !== -1 + && data.content.indexOf(sessionDoesNotExistStringEnd) !== -1) { + clearLocalStorage(); + location.reload(); + } + throw "REST call returned an error\n" + data; + } +} + +function pageControl_status(data) { + $('#statusString').html(data.result); + $("#statusMessageTable").empty(); + + if (data.ok) { + $('#statusString').css("color", "green"); + $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_tick"); + } else { + $('#statusString').css("color", "red"); + $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_error"); + } +} + +function pageControl_restError(requestURL, jqXHR, textStatus, errorThrown) { + $('#statusString').html("REST_ERROR"); + $('#statusString').css("color", "red"); + $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_error"); + + $("#statusMessageTable").empty(); + $("#statusMessageTable").append( + "request \"" + requestURL + "\" returned \"" + textStatus + "\" " + jqXHR.status + " \"" + + errorThrown + "\""); + +} + +function pageControl_recursiveDisable(el, disableValue, visibleValue) { + try { + el.readOnly = disableValue; + el.style.visibility = (visibleValue ? "visible" : "hidden"); + } catch (E) { + } + + if (el.childNodes && el.childNodes.length > 0) { + for (let value of el.childNodes) { + recursiveDisable(value, disableValue, visibleValue); + } + } +} + +function showPlaceholder(show) { + if (show) { + $(".placeholder").show(); + } else { + $(".placeholder").hide(); + } +} + +export { + showPlaceholder, + pageControl_busyMode, + pageControl_modelMode, + pageControl_noModelMode, + pageControl_readyMode, + pageControl_recursiveDisable, + pageControl_restError, + pageControl_status, + pageControl_successStatus +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js new file mode 100644 index 0000000..4c53959 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js @@ -0,0 +1,830 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {apexUtils_removeElement, apexUtils_emptyElement, apexUtils_areYouSure, scrollToTop} from "./ApexUtils"; +import {dropdownList, dropdownList_ChangeOptions} from "./dropdownList"; +import {ajax_get, ajax_delete, ajax_getWithKeyInfo, ajax_post, ajax_put} from "./ApexAjax"; +import {policyTab_reset} from "./ApexPolicyTab"; +import { editPolicyForm_State_generateStateDiv, editPolicyForm_State_getStateBean } from "./ApexPolicyEditForm_State"; +import { formUtils_generateDescription, formUtils_generateUUID } from "./ApexFormUtils"; +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; +import {showHideElement} from "./showhideElement" + +function editPolicyForm_createPolicy(formParent) { + editPolicyForm_editPolicy_inner(formParent, null, "CREATE"); +} + +function editPolicyForm_deletePolicy(parent, name, version) { + var message = "Are you sure you want to delete Policy \"" + name + ":" + version + "\"?"; + if (apexUtils_areYouSure(message)) { + var requestURL = restRootURL + "/Policy/Delete?name=" + name + "&version=" + version; + ajax_delete(requestURL, function(data) { + apexUtils_removeElement("editPolicyFormDiv"); + policyTab_reset(); + keyInformationTab_reset() + }); + } +} + +function editPolicyForm_viewPolicy(formParent, name, version) { + // get the policy + var requestURL = window.restRootURL + "/Policy/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexPolicy", function(policy) { + editPolicyForm_editPolicy_inner(formParent, policy, "VIEW"); + }, "policyKey"); +} + +function editPolicyForm_editPolicy(formParent, name, version) { + // get the policy + var requestURL = window.restRootURL + "/Policy/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexPolicy", function(policy) { + editPolicyForm_editPolicy_inner(formParent, policy, "EDIT"); + }, "policyKey"); +} + +function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) { + // Get all contextSchemas too + var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + // Get all tasks + requestURL = window.restRootURL + "/Task/Get?name=&version="; + var tasks = new Array(); + ajax_get(requestURL, function(data3) { + for (let value of data3.messages.message) { + var task = JSON.parse(value).apexTask; + tasks.push({ + "name" : task.key.name, + "version" : task.key.version, + "displaytext" : task.key.name + ":" + task.key.version, + "task" : task + }); + } + // Get all ContextAlbums + requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; + var albums = new Array(); + ajax_get(requestURL, function(data4) { + for (let value of data4.messages.message) { + var album = JSON.parse(value).apexContextAlbum; + albums.push({ + "name" : album.key.name, + "version" : album.key.version, + "displaytext" : album.key.name + ":" + album.key.version, + "album" : album + }); + } + // Get all Events + requestURL = window.restRootURL + "/Event/Get?name=&version="; + var events = new Array(); + ajax_get(requestURL, function(data5) { + for (let value of data5.messages.message) { + var event = JSON.parse(value).apexEvent; + events.push({ + "name" : event.key.name, + "version" : event.key.version, + "displaytext" : event.key.name + ":" + event.key.version, + "event" : event + }); + } + editPolicyForm_activate(formParent, viewOrEdit, policy, tasks, events, albums, contextSchemas); + }); + }); + }); + }); +} + +function editPolicyForm_activate(parent, operation, policy, tasks, events, contextAlbums, contextItemSchemas) { + apexUtils_removeElement("editPolicyFormDiv"); + var formParent = document.getElementById(parent); + + //Testing purposes + if(formParent === null) { + formParent = document.createElement("testFormParent"); + } + apexUtils_emptyElement(parent); + + var createEditOrView = ""; + + if (!operation) { + console.warn("No operation specified for PolicyForm form") + } else { + createEditOrView = operation.toUpperCase(); + } + + if (createEditOrView == "EDIT" || createEditOrView == "VIEW") { + + if (!policy) { + console.warn("Invalid value (\"" + policy + "\") passed as a value for \"policy\" for PolicyForm form."); + } else { + if (!policy.policyKey || !policy.policyKey.name || policy.policyKey.name == "") { + console.warn("Invalid value (\"" + policy.policyKey.name + + "\") passed as a value for \"name\" for PolicyForm form."); + } + if (!policy.policyKey || !policy.policyKey.version || policy.policyKey.version == "") { + console.warn("Invalid value (\"" + policy.policyKey.version + + "\") passed as a value for \"version\" for PolicyForm form."); + } + if (!policy.uuid || policy.uuid == "") { + console.warn("Invalid value (\"" + policy.uuid + + "\") passed as a value for \"uuid\" for PolicyForm form."); + } + } + } else { + console.warn("Invalid operation (\"" + operation + + "\") specified for PolicyForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported"); + } + + var contentelement = document.createElement("editPolicyFormDiv"); + var formDiv = document.createElement("div"); + contentelement.appendChild(formDiv); + formDiv.setAttribute("id", "editPolicyFormDiv"); + formDiv.setAttribute("class", "editPolicyFormDiv"); + + var headingSpan = document.createElement("h2"); + formDiv.appendChild(headingSpan); + headingSpan.innerHTML = "Policy Editor"; + + var form = document.createElement("editPolicyForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "editPolicyForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + form.setAttribute("createEditOrView", createEditOrView); + + var formul = document.createElement("ul"); + form.appendChild(formul); + + // name + var nameLI = document.createElement("li"); + formul.appendChild(nameLI); + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + nameLabel.setAttribute("for", "editPolicyFormNameInput"); + nameLabel.innerHTML = "Name: "; + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + nameInput.setAttribute("id", "editPolicyFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editPolicyFormNameInput"); + nameInput.setAttribute("class", "field ebInput"); + nameInput.setAttribute("placeholder", "name"); + if (policy != null && policy.policyKey != null && policy.policyKey.name != null) { + nameInput.value = policy.policyKey.name; + } + if (createEditOrView != "CREATE") { + nameInput.readOnly = true; + } + + // version + var versionLI = document.createElement("li"); + formul.appendChild(versionLI); + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + versionLabel.setAttribute("for", "editPolicyFormVersionInput"); + versionLabel.innerHTML = "Version: "; + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + versionInput.setAttribute("id", "editPolicyFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "editPolicyFormVersionInput"); + versionInput.setAttribute("class", "field ebInput"); + versionInput.setAttribute("placeholder", "0.0.1"); + if (policy != null && policy.policyKey != null && policy.policyKey.version != null) { + versionInput.value = policy.policyKey.version; + } + if (createEditOrView != "CREATE") { + versionInput.readOnly = true; + } + + // uuid + var uuidLI = document.createElement("li"); + formul.appendChild(uuidLI); + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + uuidLabel.setAttribute("for", "editPolicyFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + uuidInput.setAttribute("id", "editPolicyFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "editPolicyFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + if (policy != null && policy.uuid != null) { + uuidInput.value = policy.uuid; + } + if (createEditOrView != "CREATE") { + uuidInput.readOnly = true; + } + + var edit_disabled = (createEditOrView != "CREATE" && createEditOrView != "EDIT"); + + // description + var descriptionLI = document.createElement("li"); + formul.appendChild(descriptionLI); + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "editPolicyFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + descriptionTextArea.setAttribute("id", "editPolicyFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "editPolicyFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long ebTextArea ebTextArea_width_full"); + if (policy != null && policy.description != null) { + descriptionTextArea.value = policy.description; + } + descriptionTextArea.readOnly = edit_disabled; + + // template type + var templateTypeLI = document.createElement("li"); + formul.appendChild(templateTypeLI); + var templateTypeLabel = document.createElement("label"); + templateTypeLI.appendChild(templateTypeLabel); + templateTypeLabel.setAttribute("for", "editEventFormTemplateTypeInput"); + templateTypeLabel.innerHTML = "Policy Type / Flavour: "; + var templateTypeInput = document.createElement("input"); + templateTypeLI.appendChild(templateTypeInput); + templateTypeInput.setAttribute("id", "editEventFormTemplateTypeInput"); + templateTypeInput.setAttribute("type", "text"); + templateTypeInput.setAttribute("name", "editEventFormTemplateTypeInput"); + templateTypeInput.setAttribute("class", "field-policyTemplateType ebInput"); + templateTypeInput.setAttribute("placeholder", "FREEFORM"); + if (policy != null && policy.template != null) { + templateTypeInput.value = policy.template; + } else { + templateTypeInput.value = "FREEFORM"; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + templateTypeInput.readOnly = true; + } + + // first state + var firstStateLI = document.createElement("li"); + formul.appendChild(firstStateLI); + var firstStateLabel = document.createElement("label"); + firstStateLI.appendChild(firstStateLabel); + firstStateLabel.setAttribute("for", "editEventFormSelectFirstState_dropdownList"); + firstStateLabel.innerHTML = "First State: "; + var firststateoptions = new Array(); + var firststateselected = null; + if (policy != null && policy.state != null) { + for (let value of policy.state.entry) { + if (value != null && value.key != null) { + var statename = value.key; + firststateoptions.push({ + "name" : statename, + "displaytext" : statename + }); + } + } + } + if (policy != null && policy.firstState != null && policy.firstState != "") { + firststateselected = { + "name" : policy.firstState, + "displaytext" : policy.firstState + } + } + var firstStateSelectDiv = dropdownList("editEventFormSelectFirstState", firststateoptions, firststateselected, + (createEditOrView != "CREATE" && createEditOrView != "EDIT"), function() { + return editPolicyForm_updateTriggerEventOptions(events); + }, function() { + return editPolicyForm_getStateOptions(); + }); + firstStateLI.appendChild(firstStateSelectDiv); + + // Trigger event + var triggerLI = document.createElement("li"); + formul.appendChild(triggerLI); + var triggerLabel = document.createElement("label"); + triggerLI.appendChild(triggerLabel); + triggerLabel.setAttribute("for", "editEventFormSelectTrigger_dropdownList"); + triggerLabel.innerHTML = "Policy Trigger Event: "; + var triggerevent = null; + if (policy != null && policy.firstState != null && policy.firstState != "" && policy.state != null) { + for (let entry of policy.state.entry) { + if (entry != null && entry.key != null) { + statename = entry.key; + var state = entry.value; + if (statename != null && statename == policy.firstState) { + triggerevent = { + "name" : state.trigger.name, + "version" : state.trigger.version, + "displaytext" : state.trigger.name + ":" + state.trigger.version + }; + } + } + } + } + // var triggerSelectDiv = dropdownList("editEventFormSelectTrigger", events, + // triggerevent, true, null); // ewatkmi: replaced dropdown with label + var triggerSelectDiv = document.createElement("label"); + triggerSelectDiv.setAttribute("class", "policy-trigger-event"); + triggerSelectDiv.setAttribute("id", "editEventFormSelectTrigger_dropdownList"); + triggerSelectDiv.innerHTML = triggerevent ? triggerevent.displaytext : "No Event Selected"; + triggerLI.appendChild(triggerSelectDiv); + var triggerPeriodicEventCheckbox = document.createElement("input"); + triggerPeriodicEventCheckbox.setAttribute("type", "checkbox"); + triggerPeriodicEventCheckbox.setAttribute("id", "periodicEventsCheckbox"); + triggerPeriodicEventCheckbox.setAttribute("class", "field-checkbox-center periodic-events-checkbox"); + triggerPeriodicEventCheckbox.disabled = createEditOrView != "EDIT"; + triggerPeriodicEventCheckbox.onclick = function() { + var firstState = document.getElementById("editEventFormSelectFirstState_dropdownList_display").innerHTML; + var firstStateDropdown = document.getElementById("editPolicyFormTrigger_" + firstState + "_dropdownList"); + if ($(triggerPeriodicEventCheckbox).is(":checked")) { + var periodicEvent = undefined; + var tmpEvents = $.merge([], events); + for ( var e in events) { + if (events[e].name.indexOf("PeriodicEvent") !== -1) { + periodicEvent = events[e]; + break; + } + } + if (!periodicEvent) { + periodicEvent = { + name : "PeriodicEvent", + version : "0.0.1", + displaytext : "PeriodicEvent:0.0.1", + event : { + description : "", + key : { + name : "PeriodicEvent", + version : "0.0.1" + }, + nameSpace : "org.onap.policy.apex.domains.aadm.events", + parameter : { + entry : [ { + key : "PERIODIC_EVENT_COUNT", + value : { + key : "PERIODIC_EVENT_COUNT", + optional : false, + fieldSchemaKey : { + name : "PeriodicEventCount", + version : "0.0.1" + } + } + } ] + }, + source : "System", + target : "Apex", + uuid : "44236da1-3d47-4988-8033-b6fee9d6a0f4" + }, + }; + tmpEvents.push(periodicEvent); + } + + dropdownList_ChangeOptions(firstStateDropdown, tmpEvents, periodicEvent, false); + editPolicyForm_updateTriggerEventOptions(tmpEvents); + } else { + dropdownList_ChangeOptions(firstStateDropdown, events, events[0], false); + editPolicyForm_updateTriggerEventOptions(events); + } + } + + triggerLI.appendChild(triggerPeriodicEventCheckbox); + + var triggerPeriodicEventLabel = document.createElement("label"); + triggerPeriodicEventLabel.setAttribute("class", "periodic-events-label"); + triggerPeriodicEventLabel.innerHTML = "is Periodic Event"; + triggerLI.appendChild(triggerPeriodicEventLabel); + + // states + var statesLI = document.createElement("li"); + formul.appendChild(statesLI); + var statesLabel = document.createElement("label"); + statesLI.appendChild(statesLabel); + statesLabel.setAttribute("for", "editEventFormStates"); + statesLabel.innerHTML = "States: "; + var statesUL = document.createElement("ul"); + statesUL.setAttribute("id", "editEventFormStates"); + statesLI.appendChild(statesUL); + if (policy && policy.state) { + var states = policy.state.entry; + for ( var s in states) { + state = states[s]; + if (state.key == policy.firstState) { + states.splice(s, 1); + states.unshift(state); + break; + } + } + for (let stateEntry of policy.state.entry) { + statename = stateEntry.key; + state = stateEntry.value; + var stateLI = editPolicyForm_addState(statename, state, createEditOrView, policy, tasks, events, + contextAlbums, contextItemSchemas); + statesUL.appendChild(stateLI); + } + } + + // add new state + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var newStateLI = document.createElement("li"); + statesUL.appendChild(newStateLI); + var newStateLabel = document.createElement("label"); + newStateLI.appendChild(newStateLabel); + newStateLabel.setAttribute("for", "editPolicyFormStateDiv_"); + newStateLabel.innerHTML = "Add a new State: "; + var newStDiv = document.createElement("div"); + newStateLI.appendChild(newStDiv); + newStDiv.setAttribute("id", "editPolicyFormStateDiv_"); + newStDiv.setAttribute("class", "editPolicyFormStateDiv"); + var newStateInput = document.createElement("input"); + newStDiv.appendChild(newStateInput); + newStateInput.setAttribute("id", "editEventFormNewStateInput"); + newStateInput.setAttribute("type", "text"); + newStateInput.setAttribute("name", "editEventFormTemplateTypeInput"); + newStateInput.setAttribute("class", "field-policyTemplateType ebInput ebInput_width_xLong"); + newStateInput.setAttribute("placeholder", "Name for new State ... "); + var addState = document.createElement("button"); + newStDiv.appendChild(addState); + addState.setAttribute("id", "addStateButton"); + addState.setAttribute("class", "ebBtn"); + addState.setAttribute("type", "submit"); + addState.setAttribute("value", "Add a new State"); + addState.style["margin-left"] = "10px"; + addState.onclick = function() { + return editPolicyForm_addNewState(statesUL, createEditOrView, policy, tasks, events, contextAlbums, + contextItemSchemas); + }; + addState.innerHTML = addState.getAttribute("value"); + } + + // buttons + var inputLI = document.createElement("li"); + formul.appendChild(inputLI); + if (createEditOrView == "CREATE") { + var generateUUIDInput = document.createElement("button"); + inputLI.appendChild(generateUUIDInput); + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + generateUUIDInput.onclick = editPolicyForm_generateUUIDPressed; + generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value"); + + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + + var generateDescriptionInput = document.createElement("button"); + inputLI.appendChild(generateDescriptionInput); + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + generateDescriptionInput.onclick = editPolicyForm_generateDescriptionPressed; + generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value"); + + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + } + + var cancelInput = document.createElement("button"); + inputLI.appendChild(cancelInput); + cancelInput.setAttribute("id", "cancel"); + cancelInput.setAttribute("class", "ebBtn ebBtn_large"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + cancelInput.onclick = editPolicyForm_cancelPressed; + cancelInput.innerHTML = cancelInput.getAttribute("value"); + + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + var submitInput = document.createElement("button"); + inputLI.appendChild(submitInput); + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "ebBtn ebBtn_large"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + submitInput.onclick = editPolicyForm_submitPressed; + submitInput.innerHTML = submitInput.getAttribute("value"); + } + + formParent.appendChild(contentelement); + scrollToTop(); +} + +function editPolicyForm_addNewState(statesUL, createEditOrView, policy, tasks, events, contextAlbums, + contextItemSchemas) { + var statename = document.getElementById("editEventFormNewStateInput").value; + if (statename == null || statename == "") { + alert("Please enter a value for the name of the new state\"" + paramname + "\""); + document.getElementById("editEventFormNewStateInput").focus(); + return false; + } else if (statename.toUpperCase() == "NULL" || statename.toUpperCase() == "NONE") { + alert("Please enter a valid value for the name of the new state\"" + paramname + + "\". Values \"NULL\" and \"None\" are not allowed"); + document.getElementById("editEventFormNewStateInput").focus(); + return false; + } else { + document.getElementById("editEventFormNewStateInput").value = ""; + } + if (policy && policy.state) { + for (let value of policy.state.entry) { + if (statename.toUpperCase() == value.key.toUpperCase()) { + alert("Policy " + policy.policyKey.name + ":" + policy.policyKey.version + + " already contains a state called \"" + statename + "\"."); + document.getElementById("editEventFormNewStateInput").focus(); + return false; + } + } + } + var stateLI = editPolicyForm_addState(statename, null, createEditOrView, policy, tasks, events, contextAlbums, + contextItemSchemas); + statesUL.insertBefore(stateLI, statesUL.lastElementChild); + editPolicyForm_updateTriggerEventOptions(events); +} + +function editPolicyForm_getStateOptions() { + var stateoptions = new Array(); + var stateslis = document.getElementById("editEventFormStates").querySelectorAll( + "#editEventFormStates > li[stateName]"); // get li direct child + // elements with an + // attribute "stateName" + for (let value of stateslis) { + if (stateslis != null && value != null && value.getAttribute("stateName") != null) { + stateoptions.push({ + "name" : value.getAttribute("stateName"), + "displaytext" : value.getAttribute("stateName") + }); + } + } + return stateoptions; +} + +function editPolicyForm_getNextStateOptions() { + var stateoptions = editPolicyForm_getStateOptions(); + stateoptions.push({ + "name" : "NULL", + "displaytext" : "None" + }); + return stateoptions; +} + +function editPolicyForm_updateTriggerEventOptions(events) { + var stateevent = null; + var triggerSelectDiv = document.getElementById("editEventFormSelectTrigger_dropdownList"); + var firstStateSelectDiv = document.getElementById("editEventFormSelectFirstState_dropdownList"); + var firststate = firstStateSelectDiv.selectedOption; + var createEditOrView = document.getElementById("editPolicyForm").getAttribute("createEditOrView"); + if (firststate != null && firststate.name != null) { + var statename = firststate.name; + var stateeventselect = document.getElementById("editPolicyFormTrigger_" + statename + "_dropdownList"); + if (stateeventselect != null && stateeventselect.selectedOption) { + stateevent = stateeventselect.selectedOption; + } + if (createEditOrView == "CREATE") { + var periodicCheckbox = document.getElementById("periodicEventsCheckbox"); + if (periodicCheckbox.hasAttribute("disabled")) { + periodicCheckbox.removeAttribute("disabled"); + } + } + } else { + triggerSelectDiv = document.getElementById("editEventFormSelectTrigger_dropdownList"); + triggerSelectDiv.innerHTML = "No Event Selected"; + var periodicEventsCheckbox = $("#periodicEventsCheckbox"); + if (periodicEventsCheckbox.is(":checked")) { + periodicEventsCheckbox.attr("checked", false); + } + if (createEditOrView == "CREATE") { + periodicCheckbox = document.getElementById("periodicEventsCheckbox"); + if (!periodicCheckbox.hasAttribute("disabled")) { + periodicCheckbox.disabled = true; + } + } + } + if (stateevent) { + triggerSelectDiv.innerHTML = stateevent.displaytext; + if (stateevent.displaytext.indexOf("PeriodicEvent") == -1) { + periodicEventsCheckbox = $("#periodicEventsCheckbox"); + if (periodicEventsCheckbox.is(":checked")) { + periodicEventsCheckbox.attr("checked", false); + } + } + } +} + +function editPolicyForm_addState(statename, state, createEditOrView, policy, tasks, events, contextAlbums, + contextItemSchemas) { + var stateLI = document.createElement("li"); + stateLI.setAttribute("stateName", statename); + var deleteDiv = document.createElement("div"); + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(stateLI) + .hide( + "fast", + function() { + stateLI.parentNode.removeChild(stateLI); + var firstState = document + .getElementById("editEventFormSelectFirstState_dropdownList_display").innerHTML; + var selected = (statename !== firstState) ? { + name : firstState, + displaytext : firstState + } : undefined; + dropdownList_ChangeOptions(document + .getElementById("editEventFormSelectFirstState_dropdownList"), + editPolicyForm_getStateOptions(), selected, false, + editPolicyForm_getStateOptions); + editPolicyForm_updateTriggerEventOptions(); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + deleteDiv.style["vertical-align"] = "baseline"; + stateLI.appendChild(deleteDiv); + var stateLabel = document.createElement("label"); + stateLabel.style.display = "inline-block"; + stateLabel.style["min-width"] = "120px"; + stateLabel.style["padding-left"] = "10px"; + stateLabel.style["vertical-align"] = "middle"; + stateLabel.innerHTML = statename; + stateLI.appendChild(stateLabel); + var stateDiv = editPolicyForm_State_generateStateDiv(createEditOrView, policy, statename, state, tasks, events, + contextAlbums, contextItemSchemas); + var showhideDIV = showHideElement("editEventFormStates_" + statename, stateDiv, true, "Show " + statename + " ...", + "Hide " + statename + " ...", "showhide_div_show", "showhide_div_hide", "showhide_button_show", + "showhide_button_hide"); + showhideDIV.style.display = "inline-block"; + showhideDIV.style["vertical-align"] = "middle"; + stateLabel.setAttribute("for", stateDiv.id); + stateLI.appendChild(showhideDIV); + stateLI.appendChild(stateDiv); + return stateLI; +} + +function editPolicyForm_generateUUIDPressed() { + document.getElementById("editPolicyFormUuidInput").value = formUtils_generateUUID(); +} + +function editPolicyForm_generateDescriptionPressed() { + document.getElementById("editPolicyFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("editPolicyFormNameInput").value, + document.getElementById("editPolicyFormVersionInput").value, document + .getElementById("editPolicyFormUuidInput").value); +} + +function editPolicyForm_cancelPressed() { + apexUtils_removeElement("editPolicyFormDiv"); + policyTab_reset(); +} + +function editPolicyForm_submitPressed() { + var createEditOrView = document.getElementById("editPolicyForm").getAttribute("createEditOrView"); + if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) { + console.error("Invalid operation \"" + createEditOrView + + "\" passed to editPolicyForm_submitPressed function. Edit failed"); + apexUtils_removeElement("editPolicyFormDiv"); + policyTab_reset(); + return; + } + + var policybean = editPolicyForm_getPolicyBean(); + if (policybean == null) { + return false; + } + var jsonString = JSON.stringify(policybean); + + if (createEditOrView == "CREATE") { + var requestURL = window.restRootURL + "/Policy/Create"; + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editPolicyFormDiv"); + policyTab_reset(); + keyInformationTab_reset(); + }); + } else if (createEditOrView == "EDIT") { + var firstStatePeriodic = $("#periodicEventsCheckbox").is(":checked") + requestURL = window.restRootURL + "/Policy/Update?firstStatePeriodic=" + firstStatePeriodic; + ajax_put(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editPolicyFormDiv"); + policyTab_reset(); + keyInformationTab_reset(); + }); + } + +} + +function editPolicyForm_getPolicyBean() { + + var name = document.getElementById('editPolicyFormNameInput').value; + if (name == null || name == "") { + console.error("No Name is specified for the policy"); + alert("No Name is specified for the policy"); + return null; + } + var version = document.getElementById('editPolicyFormVersionInput').value; + if (version == null || version == "") { + console.error("No Version is specified for the policy"); + alert("No Version is specified for the policy"); + return null; + } + var uuid = document.getElementById('editPolicyFormUuidInput').value; + if (uuid == null || uuid == "") { + console.error("No UUID is specified for the policy"); + alert("No UUID is specified for the policy"); + return null; + } + var desc = document.getElementById('editPolicyFormDescriptionTextArea').value; + if (desc == null) { + desc = ""; + } + var template = document.getElementById('editEventFormTemplateTypeInput').value; + if (template == null) { + template = ""; + } + var firststateselectedoption = document.getElementById("editEventFormSelectFirstState" + "_dropdownList").selectedOption; + if (firststateselectedoption == null) { + console.error("Please select an option for First State"); + alert("Please select an option for First State"); + return null; + } + var states = new Object(); + var stateslis = document.getElementById("editEventFormStates").querySelectorAll( + "#editEventFormStates > li[stateName]"); // get li direct child + // elements with an + // attribute "stateName" + for (let value of stateslis) { // ignore last li ... it has + // the new state button etc. + if (stateslis != null && value != null && value.getAttribute("stateName") != null) { + var statename = value.getAttribute("stateName"); + var state = editPolicyForm_State_getStateBean(statename); + if (state == null) { + return null; + } + states[statename] = state; + } + } + + return { + "name" : name, + "version" : version, + "uuid" : uuid, + "description" : desc, + "template" : template, + "firstState" : firststateselectedoption.name, + "states" : states + }; +} + +export { + editPolicyForm_activate, + editPolicyForm_editPolicy_inner, + editPolicyForm_State_getStateBean, + editPolicyForm_addNewState, + editPolicyForm_addState, + editPolicyForm_cancelPressed, + editPolicyForm_createPolicy, + editPolicyForm_deletePolicy, + editPolicyForm_editPolicy, + editPolicyForm_generateDescriptionPressed, + editPolicyForm_generateUUIDPressed, + editPolicyForm_getNextStateOptions, + editPolicyForm_getPolicyBean, + editPolicyForm_getStateOptions, + editPolicyForm_State_generateStateDiv, + editPolicyForm_submitPressed, + editPolicyForm_updateTriggerEventOptions, + editPolicyForm_viewPolicy +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm_State.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm_State.js new file mode 100644 index 0000000..aa0db4b --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm_State.js @@ -0,0 +1,1140 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import { dropdownList } from "./dropdownList"; +import { createAddFormButton } from "./ApexUtils"; +import { showHideTextarea } from "./showhideTextarea"; +import { formUtils_generateUUID } from "./ApexFormUtils"; +import {editPolicyForm_getNextStateOptions, editPolicyForm_updateTriggerEventOptions} from "./ApexPolicyEditForm"; + +function editPolicyForm_State_generateStateDiv(createEditOrView, policy, statename, state, tasks, events, + contextAlbums, contextItemSchemas) { + var retDiv = document.createElement("div"); + retDiv.setAttribute("id", "editPolicyFormStateDiv_" + statename); + retDiv.setAttribute("class", "editPolicyFormStateDiv"); + var divUL = document.createElement("ul"); + retDiv.appendChild(divUL); + + // input event + var triggerLI = document.createElement("li"); + divUL.appendChild(triggerLI); + var triggerLabel = document.createElement("label"); + triggerLI.appendChild(triggerLabel); + triggerLabel.setAttribute("for", "editPolicyFormTrigger" + "_" + statename); + triggerLabel.innerHTML = "Input Event for State: "; + var eventselected = null; + if (state != null && state.trigger != null) { + eventselected = { + "name" : state.trigger.name, + "version" : state.trigger.version, + "displaytext" : state.trigger.name + ":" + state.trigger.version + }; + } + var ineventSelectDiv = dropdownList("editPolicyFormTrigger" + "_" + statename, events, eventselected, + (createEditOrView == "VIEW"), function() { + return editPolicyForm_updateTriggerEventOptions(events) + }); + triggerLI.appendChild(ineventSelectDiv); + + // Context Albums references + var contextsLI = document.createElement("li"); + divUL.appendChild(contextsLI); + var contextsLabel = document.createElement("label"); + contextsLI.appendChild(contextsLabel); + contextsLabel.setAttribute("for", "editPolicyFormContextsTable" + "_" + statename); + contextsLabel.innerHTML = "Context Albums used in Task Selection Logic / State Output Logic: "; + var contextstable = document.createElement("table"); + contextstable.setAttribute("id", "editPolicyFormContextsTable" + "_" + statename); + contextstable.setAttribute("name", "editPolicyFormContextsTable" + "_" + statename); + contextstable.setAttribute("class", "table-policycontext"); + contextsLI.appendChild(contextstable); + // var contextstable_head = document.createElement("thead"); + // contextstable.appendChild(contextstable_head); + // var contextstable_head_tr = document.createElement("tr"); + // contextstable_head.appendChild(contextstable_head_tr); + // contextstable_head_tr.appendChild(document.createElement("th")); //empty, + // for delete button + // var contextstable_head_th = document.createElement("th"); + // contextstable_head_tr.appendChild(contextstable_head_th); + // contextstable_head_th.innerHTML = "Context Album: "; + // contextstable_head_th.setAttribute("class", + // "table-policycontext-heading"); + var contextstable_body = document.createElement("tbody"); + contextstable.appendChild(contextstable_body); + // Add the contexts + if (state && state.contextAlbumReference && $.isArray(state.contextAlbumReference)) { + for (let contextEntry of state.contextAlbumReference) { + var contextName = contextEntry.name + ":" + contextEntry.version; + var ce = { + "name" : contextEntry.name, + "version" : contextEntry.version, + "displaytext" : contextName + }; + editPolicyForm_State_addPolicyContext(contextstable_body, (createEditOrView == "VIEW"), statename, + contextName, ce, contextAlbums); + } + } + // add the Policy Context button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var contextTR = document.createElement("tr"); + contextTR.setAttribute("class", "field-policycontext-tr.new"); + contextstable_body.appendChild(contextTR); + + var contextTD = document.createElement("td"); + contextTD.setAttribute("colspan", "2"); + contextTR.appendChild(contextTD); + var addContextInput = createAddFormButton("Add New Policy Logic Context"); + contextTD.appendChild(addContextInput); + // addContextInput.setAttribute("id", "addContextButton"); + // addContextInput.setAttribute("class", "ebBtn ebBtn_large"); + // addContextInput.setAttribute("type", "submit"); + // addContextInput.setAttribute("value", "Add New Policy Logic + // Context"); + // addContextInput.innerHTML = addContextInput.getAttribute("value"); + addContextInput.onclick = function() { + return editPolicyForm_State_addPolicyContext(contextstable_body, false, statename, null, null, + contextAlbums); + }; + } + + // Task references + var tasksLI = document.createElement("li"); + divUL.appendChild(tasksLI); + var tasksLabel = document.createElement("label"); + tasksLI.appendChild(tasksLabel); + tasksLabel.setAttribute("for", "editPolicyFormTasksTable" + "_" + statename); + tasksLabel.innerHTML = "State Tasks:"; + var taskstable = document.createElement("table"); + taskstable.setAttribute("id", "editPolicyFormTasksTable" + "_" + statename); + taskstable.setAttribute("name", "editPolicyFormTasksTable" + "_" + statename); + taskstable.setAttribute("class", "table-policytask"); + tasksLI.appendChild(taskstable); + var taskstable_head = document.createElement("thead"); + taskstable.appendChild(taskstable_head); + var taskstable_head_tr = document.createElement("tr"); + taskstable_head.appendChild(taskstable_head_tr); + taskstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var taskstable_isdefault_head_th = document.createElement("th"); + taskstable_head_tr.appendChild(taskstable_isdefault_head_th); + taskstable_isdefault_head_th.innerHTML = "Default Task? "; + taskstable_isdefault_head_th.setAttribute("class", "table-policytask-heading form-heading"); + var taskstable_localname_head_th = document.createElement("th"); + taskstable_head_tr.appendChild(taskstable_localname_head_th); + taskstable_localname_head_th.innerHTML = "Local Name for Task: "; + taskstable_localname_head_th.setAttribute("class", "table-policytask-heading form-heading"); + var taskstable_head_th = document.createElement("th"); + taskstable_head_tr.appendChild(taskstable_head_th); + taskstable_head_th.innerHTML = "Task: "; + taskstable_head_th.setAttribute("class", "table-policytask-heading form-heading"); + var taskstable_outputtype_head_th = document.createElement("th"); + taskstable_head_tr.appendChild(taskstable_outputtype_head_th); + taskstable_outputtype_head_th.innerHTML = "Output Mapping type: "; + taskstable_outputtype_head_th.setAttribute("class", "table-policytask-heading form-heading"); + taskstable_outputtype_head_th.setAttribute("colspan", "2"); + var taskstable_outputsel_head_th = document.createElement("th"); + taskstable_head_tr.appendChild(taskstable_outputsel_head_th); + taskstable_outputsel_head_th.innerHTML = "Output Mapping: "; + taskstable_outputsel_head_th.setAttribute("class", "table-policytask-heading form-heading"); + var taskstable_body = document.createElement("tbody"); + taskstable.appendChild(taskstable_body); + var defaulttask = null; + if (state && state.defaultTask && state.defaultTask.name && state.defaultTask.version) { + defaulttask = state.defaultTask.name + ":" + state.defaultTask.version; + } + // Add the tasks + if (state && state.taskReferences && $.isArray(state.taskReferences.entry)) { + for (let taskEntry of state.taskReferences.entry) { + var taskName = taskEntry.key.name + ":" + taskEntry.key.version; + var taskselected = { + "name" : taskEntry.key.name, + "version" : taskEntry.key.version, + "displaytext" : taskName + }; + var taskreference = taskEntry.value; + editPolicyForm_State_addPolicyTask(taskstable_body, (createEditOrView == "VIEW"), + (defaulttask == taskName), state, statename, taskreference, taskselected, tasks); + } + } + // add the Policy Task button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var taskTR = document.createElement("tr"); + taskTR.setAttribute("class", "field-policytask-tr.new"); + taskstable_body.appendChild(taskTR); + var taskTD = document.createElement("td"); + taskTD.setAttribute("colspan", "4"); + taskTR.appendChild(taskTD); + var addTaskInput = createAddFormButton("Add New Task"); + taskTD.appendChild(addTaskInput); + // addTaskInput.setAttribute("id", "addTaskButton"); + // addTaskInput.setAttribute("class", "ebBtn ebBtn_large"); + // addTaskInput.setAttribute("type", "submit"); + // addTaskInput.setAttribute("value", "Add New Task"); + // addTaskInput.innerHTML = addTaskInput.getAttribute("value"); + addTaskInput.onclick = function() { + return editPolicyForm_State_addPolicyTask(taskstable_body, false, false, state, statename, null, null, + tasks); + }; + } + + // tasksellogic + var tasksellogicLI = document.createElement("li"); + divUL.appendChild(tasksellogicLI); + var tasksellogicLabel = document.createElement("label"); + tasksellogicLI.appendChild(tasksellogicLabel); + tasksellogicLabel.setAttribute("for", "editEventFormTaskSelLogicDiv" + "_" + statename); + tasksellogicLabel.innerHTML = "Task Selection Logic: "; + var tasksellogicdiv = document.createElement("div"); + tasksellogicdiv.setAttribute("id", "editEventFormTaskSelLogicDiv" + "_" + statename); + + var logic = ""; + if (state && state.taskSelectionLogic && state.taskSelectionLogic.logic && state.taskSelectionLogic.logic != "") { + logic = state.taskSelectionLogic.logic; + } + var edit_disabled = false; + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + edit_disabled = true; + } + var textarea = showHideTextarea("editEventFormTaskSelLogicInput" + "_" + statename, logic, false, !edit_disabled, + false); + + tasksellogicLI.appendChild(textarea); + + // tasksellogic type + var tasksellogicTypeLabel = document.createElement("label"); + tasksellogicdiv.appendChild(tasksellogicTypeLabel); + tasksellogicTypeLabel.setAttribute("for", "editPolicyFormTaskSelLogicTypeInput" + "_" + statename); + tasksellogicTypeLabel.innerHTML = "Task Selection Logic Type / Flavour: "; + var tasksellogicTypeInput = document.createElement("input"); + tasksellogicdiv.appendChild(tasksellogicTypeInput); + tasksellogicTypeInput.setAttribute("id", "editPolicyFormTaskSelLogicTypeInput" + "_" + statename); + tasksellogicTypeInput.setAttribute("type", "text"); + tasksellogicTypeInput.setAttribute("name", "editPolicyFormTaskSelLogicTypeInput" + "_" + statename); + tasksellogicTypeInput.setAttribute("class", "field-taskSelLogicType ebInput ebInput_width_xLong"); + tasksellogicTypeInput.setAttribute("placeholder", "MVEL"); + if (state && state.taskSelectionLogic && state.taskSelectionLogic.logicFlavour != null + && state.taskSelectionLogic.logicFlavour != "" + && state.taskSelectionLogic.logicFlavour.toUpperCase() != "UNDEFINED") { + tasksellogicTypeInput.value = state.taskSelectionLogic.logicFlavour; + } + tasksellogicTypeInput.readOnly = (createEditOrView != "CREATE" && createEditOrView != "EDIT"); + + divUL.appendChild(tasksellogicdiv); + + // Output mappings + var outputsLI = document.createElement("li"); + divUL.appendChild(outputsLI); + var outputsLabel = document.createElement("label"); + outputsLI.appendChild(outputsLabel); + outputsLabel.innerHTML = "State Output Mappings: "; + outputsLabel.setAttribute("for", "editPolicyFormOutputsUL" + "_" + statename); + var outsUL = document.createElement("ul"); + outsUL.setAttribute("id", "editPolicyFormOutputsUL" + "_" + statename); + outputsLI.appendChild(outsUL); + // Direct Output Mappings + var dir_outputsLI = document.createElement("li"); + outsUL.appendChild(dir_outputsLI); + var dir_outputsLabel = document.createElement("label"); + dir_outputsLI.appendChild(dir_outputsLabel); + dir_outputsLI.innerHTML = "Direct State Output Mappings: "; + dir_outputsLabel.setAttribute("for", "editPolicyFormDirOutputsTable" + "_" + statename); + var dir_outputstable = document.createElement("table"); + dir_outputstable.setAttribute("id", "editPolicyFormDirOutputsTable" + "_" + statename); + dir_outputstable.setAttribute("name", "editPolicyFormDirOutputsTable" + "_" + statename); + dir_outputstable.setAttribute("class", "table-policyoutput"); + dir_outputsLI.appendChild(dir_outputstable); + var dir_outputstable_head = document.createElement("thead"); + dir_outputstable.appendChild(dir_outputstable_head); + var dir_outputstable_head_tr = document.createElement("tr"); + dir_outputstable_head.appendChild(dir_outputstable_head_tr); + dir_outputstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var dir_outputstable_name_head_th = document.createElement("th"); + dir_outputstable_head_tr.appendChild(dir_outputstable_name_head_th); + dir_outputstable_name_head_th.innerHTML = "Local Name for Output Mapping: "; + dir_outputstable_name_head_th.setAttribute("class", "table-policyoutput-heading form-heading"); + var dir_outputstable_nextstate_head_th = document.createElement("th"); + dir_outputstable_head_tr.appendChild(dir_outputstable_nextstate_head_th); + dir_outputstable_nextstate_head_th.innerHTML = "Next State: "; + dir_outputstable_nextstate_head_th.setAttribute("class", "table-policyoutput-heading form-heading"); + var dir_outputstable_event_head_th = document.createElement("th"); + dir_outputstable_head_tr.appendChild(dir_outputstable_event_head_th); + dir_outputstable_event_head_th.innerHTML = "State Output Event: "; + dir_outputstable_event_head_th.setAttribute("class", "table-policyoutput-heading form-heading"); + var dir_outputstable_body = document.createElement("tbody"); + dir_outputstable.appendChild(dir_outputstable_body); + var stateNextStateOptions = new Array(); + stateNextStateOptions.push({ + "name" : "NULL", + "displaytext" : "None", + "state" : null + }); + if (policy && policy.state && policy.state.entry && $.isArray(policy.state.entry)) { + for (let st of policy.state.entry) { + if (statename != st.key) { // state cannot have itself as nextstate + stateNextStateOptions.push({ + "name" : st.key, + "displaytext" : st.key, + "state" : st.value + }); + } + } + } + if (state && state.stateOutputs && $.isArray(state.stateOutputs.entry)) { + for (let outputEntry of state.stateOutputs.entry) { + var outputName = outputEntry.key; + var nextState = null; + var nxtst = outputEntry.value.nextState.localName; + if (nxtst != null && nxtst.toUpperCase() != "NULL") { + nextState = { + "name" : nxtst, + "displaytext" : nxtst + }; + } + if (nxtst != null && nxtst.toUpperCase() == "NULL") { + nextState = { + "name" : "NULL", + "displaytext" : "None" + }; + } + var outEvent = null; + var oute = outputEntry.value.outgoingEvent; + if (oute != null && oute.name != null && oute.version != null) { + outEvent = { + "name" : oute.name, + "version" : oute.version, + "displaytext" : oute.name + ":" + oute.version + }; + } + editPolicyForm_State_addStateDirectOutput(dir_outputstable_body, (createEditOrView == "VIEW"), statename, + state, outputName, nextState, outEvent, stateNextStateOptions, events); + } + } + // add the new Direct output button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var dir_outputTR = document.createElement("tr"); + dir_outputTR.setAttribute("class", "field-policyoutput-tr.new"); + dir_outputstable_body.appendChild(dir_outputTR); + var dir_outputTD = document.createElement("td"); + dir_outputTD.setAttribute("colspan", "4"); + dir_outputTR.appendChild(dir_outputTD); + var addStateDirOutput = createAddFormButton("Add New Direct State Output Mapping") + dir_outputTD.appendChild(addStateDirOutput); + // addStateDirOutput.setAttribute("id", + // "editPolicyFormDirOutputsAddOutput"+"_"+statename); + // addStateDirOutput.setAttribute("class", "ebBtn ebBtn_large"); + // addStateDirOutput.setAttribute("type", "submit"); + // addStateDirOutput.setAttribute("value", Add New Direct State Output + // Mapping); + // addStateDirOutput.innerHTML = + // addStateDirOutput.getAttribute("value"); + addStateDirOutput.onclick = function() { + return editPolicyForm_State_addStateDirectOutput(dir_outputstable_body, false, statename, state, null, + null, null, stateNextStateOptions, events); + }; + } + // Logic-based Output Mappings + var logic_outputsLI = document.createElement("li"); + outsUL.appendChild(logic_outputsLI); + var logic_outputsLabel = document.createElement("label"); + logic_outputsLI.appendChild(dir_outputsLabel); + logic_outputsLI.innerHTML = "Logic-based State Output Mappings / Finalizers: "; + logic_outputsLabel.setAttribute("for", "editPolicyFormLogicOutputsTable" + "_" + statename); + var logic_outputstable = document.createElement("table"); + logic_outputstable.setAttribute("id", "editPolicyFormLogicOutputsTable" + "_" + statename); + logic_outputstable.setAttribute("name", "editPolicyFormLogicOutputsTable" + "_" + statename); + logic_outputstable.setAttribute("class", "table-policyoutput"); + logic_outputsLI.appendChild(logic_outputstable); + var logic_outputstable_head = document.createElement("thead"); + logic_outputstable.appendChild(logic_outputstable_head); + var logic_outputstable_head_tr = document.createElement("tr"); + logic_outputstable_head.appendChild(logic_outputstable_head_tr); + logic_outputstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var logic_outputstable_name_head_th = document.createElement("th"); + logic_outputstable_head_tr.appendChild(logic_outputstable_name_head_th); + logic_outputstable_name_head_th.innerHTML = "Local Name for Output Mapping: "; + logic_outputstable_name_head_th.setAttribute("class", "table-policyoutput-heading form-heading"); + var logic_outputstablelogic_head_th = document.createElement("th"); + logic_outputstable_head_tr.appendChild(logic_outputstablelogic_head_th); + logic_outputstablelogic_head_th.style.textAlign = "left"; + logic_outputstablelogic_head_th.innerHTML = "Output Mapping / Finalizer Logic: "; + logic_outputstablelogic_head_th.setAttribute("class", "table-policyoutput-heading form-heading"); + var logic_outputstable_body = document.createElement("tbody"); + logic_outputstable.appendChild(logic_outputstable_body); + if (state && state.stateFinalizerLogicMap && $.isArray(state.stateFinalizerLogicMap.entry)) { + for (let outputEntry of state.stateFinalizerLogicMap.entry) { + outputName = outputEntry.key; + logic = null; + if (outputEntry.value != null && outputEntry.value.logic != null) { + logic = outputEntry.value.logic; + } + var flavour = null; + if (outputEntry.value != null && outputEntry.value.logicFlavour != null) { + flavour = outputEntry.value.logicFlavour; + } + editPolicyForm_State_addStateLogicOutput(logic_outputstable_body, (createEditOrView == "VIEW"), statename, + state, outputName, logic, flavour); + } + } + // add the new Logic output button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var logic_outputTR = document.createElement("tr"); + logic_outputTR.setAttribute("class", "field-policyoutput-tr.new"); + logic_outputstable_body.appendChild(logic_outputTR); + var logic_outputTD = document.createElement("td"); + logic_outputTD.setAttribute("colspan", "3"); + logic_outputTR.appendChild(logic_outputTD); + var addStateLogicOutput = createAddFormButton("Add New Logic-based State Output Mapping / Finalizer"); + logic_outputTD.appendChild(addStateLogicOutput); + // addStateLogicOutput.setAttribute("id", + // "editPolicyFormLogicOutputsAddOutput"+"_"+statename); + // addStateLogicOutput.setAttribute("class", "ebBtn ebBtn_large"); + // addStateLogicOutput.setAttribute("type", "submit"); + // addStateLogicOutput.setAttribute("value", "Add New Logic-based State + // Output Mapping / Finalizer"); + // addStateLogicOutput.innerHTML = + // addStateLogicOutput.getAttribute("value"); + addStateLogicOutput.onclick = function() { + return editPolicyForm_State_addStateLogicOutput(logic_outputstable_body, false, statename, state, null, + null, null); + }; + } + return retDiv; +} +function editPolicyForm_State_addStateLogicOutput(parentTBody, disabled, statename, state, outputName, logic, flavour) { + var random_suffix = formUtils_generateUUID(); + var outputTR = parentTBody.insertRow(parentTBody.rows.length - 1); + outputTR.style.verticalAlign = "top"; + outputTR.style.textAlign = "left"; + outputTR.setAttribute("finalizer_id", random_suffix); + outputTR.setAttribute("class", "field-policyoutput-tr"); + if (outputName == null && !disabled) { + outputTR.setAttribute("class", "field-policyoutput-tr.new"); + } + // delete + var deleteTD = document.createElement("td"); + outputTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(outputTR).hide("fast", function() { + outputTR.parentNode.removeChild(outputTR); + }); + }; + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + // name + var nameTD = document.createElement("td"); + nameTD.style.whiteSpace = "nowrap"; + outputTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editPolicyFormLogicOutputNameValue" + "_" + statename + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editPolicyFormLogicOutputNameValue" + "_" + statename + "_" + random_suffix); + nameInput.setAttribute("class", "field-policy-outputname"); + if (outputName == null && logic == null && flavour == null && !disabled) { + nameInput.setAttribute("class", "field-policy-outputname.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "A name for this Output mapper"); + if (outputName) { + nameInput.value = outputName; + } + nameInput.readOnly = disabled; + // logic + var logicTD = document.createElement("td"); + logicTD.style.width = "99%"; + logicTD.style.whiteSpace = "nowrap"; + outputTR.appendChild(logicTD); + var finalizerlogicdiv = document.createElement("div"); + logicTD.appendChild(finalizerlogicdiv); + finalizerlogicdiv.setAttribute("id", "editEventFormFinalizerLogicDiv" + "_" + statename + "_" + random_suffix); + var finalizerlogicLabel = document.createElement("label"); + finalizerlogicdiv.appendChild(finalizerlogicLabel); + finalizerlogicLabel.setAttribute("for", "editEventFormfinalizerLogicInput" + "_" + statename + "_" + random_suffix); + finalizerlogicLabel.innerHTML = "Logic: "; + + var edit_readOnly = disabled; + var textarea = showHideTextarea("editEventFormfinalizerLogicInput" + "_" + statename + "_" + random_suffix, logic, + false, !edit_readOnly, false); + finalizerlogicdiv.appendChild(textarea); + + // finalizerlogic type + var finalizerlogicTypeLabel = document.createElement("label"); + finalizerlogicdiv.appendChild(finalizerlogicTypeLabel); + finalizerlogicTypeLabel.setAttribute("for", "editPolicyFormFinalizerLogicTypeInput" + "_" + statename + "_" + + random_suffix); + finalizerlogicTypeLabel.innerHTML = "Type / Flavour: "; + var finalizerlogicTypeInput = document.createElement("input"); + finalizerlogicdiv.appendChild(finalizerlogicTypeInput); + finalizerlogicTypeInput.setAttribute("id", "editPolicyFormFinalizerLogicTypeInput" + "_" + statename + "_" + + random_suffix); + finalizerlogicTypeInput.setAttribute("type", "text"); + finalizerlogicTypeInput.setAttribute("name", "editPolicyFormFinalizerLogicTypeInput" + "_" + statename + "_" + + random_suffix); + finalizerlogicTypeInput.setAttribute("class", "field-finalizerLogicType ebInput ebInput_width_xLong"); + finalizerlogicTypeInput.setAttribute("placeholder", "MVEL"); + if (flavour != null) { + finalizerlogicTypeInput.value = flavour; + } + finalizerlogicTypeInput.readOnly = disabled; + + logicTD.appendChild(finalizerlogicdiv); +} + +function editPolicyForm_State_addStateDirectOutput(parentTBody, disabled, stateName, state, outputName, nextState, + outEvent, stateNextStateOptions, events) { + var random_suffix = formUtils_generateUUID(); + var outputTR = parentTBody.insertRow(parentTBody.rows.length - 1); + outputTR.setAttribute("output_id", random_suffix); + outputTR.setAttribute("class", "field-policyoutput-tr"); + if (outputName == null && nextState == null && nextState == null && !disabled) { + outputTR.setAttribute("class", "field-policyoutput-tr.new"); + } + // delete + var deleteTD = document.createElement("td"); + outputTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(outputTR).hide("fast", function() { + outputTR.parentNode.removeChild(outputTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + // name + var nameTD = document.createElement("td"); + outputTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editPolicyFormDirectOutputNameValue" + "_" + stateName + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editPolicyFormDirectOutputNameValue" + "_" + stateName + "_" + random_suffix); + nameInput.setAttribute("class", "field-policy-outputname ebInput ebInput_width_xLong"); + if (outputName == null && nextState == null && nextState == null && !disabled) { + nameInput.setAttribute("class", "field-policy-outputname.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "A name for this Output mapper"); + if (outputName) { + nameInput.value = outputName; + } + nameInput.readOnly = disabled; + // outputEvent + var outeventTD = document.createElement("td"); + var outeventSelectDiv = dropdownList("editPolicyFormOutputEventValue" + "_" + stateName + "_" + random_suffix, + events, outEvent, disabled, null); + outeventTD.appendChild(outeventSelectDiv); + // nextstate + var nextstateTD = document.createElement("td"); + var nextstateSelectDiv = dropdownList("editPolicyFormOutputNextStateValue" + "_" + stateName + "_" + random_suffix, + stateNextStateOptions, nextState, disabled, null, function() { + return editPolicyForm_getNextStateOptions(); + }); + nextstateTD.appendChild(nextstateSelectDiv); + + outputTR.appendChild(nextstateTD); + outputTR.appendChild(outeventTD); + +} + +function editPolicyForm_State_addPolicyContext(parentTBody, disabled, stateName, contextName, contextreference, + contextAlbums) { + var random_suffix = formUtils_generateUUID(); + var contextTR = parentTBody.insertRow(parentTBody.rows.length - 1); + contextTR.setAttribute("context_id", random_suffix); + contextTR.setAttribute("class", "field-policycontext-tr"); + if (contextName == null && contextreference == null && !disabled) { + contextTR.setAttribute("class", "field-policycontext-tr.new"); + } + // delete + var deleteTD = document.createElement("td"); + contextTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(contextTR).hide("fast", function() { + contextTR.parentNode.removeChild(contextTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + // context + var valueTD = document.createElement("td"); + contextTR.appendChild(valueTD); + var selectDiv = dropdownList("editPolicyFormContextValue" + "_" + stateName + "_" + random_suffix, contextAlbums, + contextreference, disabled, null); + valueTD.appendChild(selectDiv); +} + +function editPolicyForm_State_addPolicyTask(parentTBody, disabled, isdefault, state, stateName, taskreference, + taskSelected, taskOptions) { + var random_suffix = formUtils_generateUUID(); + var taskTR = parentTBody.insertRow(parentTBody.rows.length - 1); + taskTR.setAttribute("task_id", random_suffix); + taskTR.setAttribute("class", "field-policytask-tr"); + if (taskreference && taskSelected == null && !disabled) { + taskTR.setAttribute("class", "field-policytask-tr.new"); + } + // delete + var deleteTD = document.createElement("td"); + taskTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(taskTR).hide("fast", function() { + taskTR.parentNode.removeChild(taskTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + // default + var defaulttaskTD = document.createElement("td"); + taskTR.appendChild(defaulttaskTD); + var defaulttaskInput = document.createElement("input"); + defaulttaskTD.appendChild(defaulttaskInput); + defaulttaskInput.setAttribute("id", "editPolicyFormTaskIsDefault" + "_" + stateName + "_" + random_suffix); + defaulttaskInput.setAttribute("value", "editPolicyFormTaskIsDefault" + "_" + stateName + "_" + random_suffix); + defaulttaskInput.setAttribute("type", "radio"); + defaulttaskInput.setAttribute("name", "editPolicyFormTaskIsDefault" + "_" + stateName); // group + // name + defaulttaskInput.setAttribute("class", "field-policy-taskisdefault"); + if (taskreference == null && taskSelected == null && !disabled) { + defaulttaskInput.setAttribute("class", "field-policy-taskisdefault.new"); + } + defaulttaskInput.checked = isdefault; + defaulttaskInput.readOnly = disabled; + // localname + var localnameTD = document.createElement("td"); + taskTR.appendChild(localnameTD); + var localnameInput = document.createElement("input"); + localnameTD.appendChild(localnameInput); + localnameInput.setAttribute("id", "editPolicyFormTaskLocalNameValue" + "_" + stateName + "_" + random_suffix); + localnameInput.setAttribute("type", "text"); + localnameInput.setAttribute("name", "editPolicyFormTaskLocalNameValue" + "_" + stateName + "_" + random_suffix); + localnameInput.setAttribute("class", "field-policy-tasklocalname ebInput ebInput_width_xLong"); + if (taskreference == null && taskSelected == null && !disabled) { + localnameInput.setAttribute("class", "field-policy-tasklocalname.new ebInput ebInput_width_xLong"); + } + localnameInput.setAttribute("placeholder", "Task's Local Name"); + if (taskreference != null && taskreference.key != null && taskreference.key.localName != null) { + localnameInput.value = taskreference.key.localName; + } + localnameInput.readOnly = disabled; + // task + var valueTD = document.createElement("td"); + taskTR.appendChild(valueTD); + var selectDiv = dropdownList("editPolicyFormTaskValue" + "_" + stateName + "_" + random_suffix, taskOptions, + taskSelected, disabled, null); + valueTD.appendChild(selectDiv); + // output type + var outputTypeDirectTD = document.createElement("td"); + taskTR.appendChild(outputTypeDirectTD); + var outputTypeDirectLabel = document.createElement("label"); + outputTypeDirectTD.appendChild(outputTypeDirectLabel); + outputTypeDirectLabel.setAttribute("for", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix + + "_DIRECT"); + outputTypeDirectLabel.setAttribute("class", "label-policy-taskoutputtype"); + outputTypeDirectLabel.innerHTML = " DIRECT"; + var outputTypeDirectInput = document.createElement("input"); + outputTypeDirectLabel.appendChild(outputTypeDirectInput); + outputTypeDirectInput.setAttribute("id", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix + + "_DIRECT"); + outputTypeDirectInput.setAttribute("value", "DIRECT"); + outputTypeDirectInput.setAttribute("type", "radio"); + outputTypeDirectInput.setAttribute("name", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix); // group + // name + outputTypeDirectInput.setAttribute("class", "field-policy-taskoutputtype"); + if (taskreference == null && taskSelected == null && !disabled) { + outputTypeDirectInput.setAttribute("class", "field-policy-taskoutputtype.new"); + } + if (taskreference != null && taskreference.outputType != null && taskreference.outputType.toUpperCase() == "DIRECT") { + outputTypeDirectInput.checked = true; + } + outputTypeDirectInput.readOnly = disabled; + var outputTypeLogicTD = document.createElement("td"); + taskTR.appendChild(outputTypeLogicTD); + var outputTypeLogicLabel = document.createElement("label"); + outputTypeLogicTD.appendChild(outputTypeLogicLabel); + outputTypeLogicLabel.setAttribute("for", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix + + "_LOGIC"); + outputTypeLogicLabel.setAttribute("class", "label-policy-taskoutputtype"); + outputTypeLogicLabel.innerHTML = " LOGIC"; + var outputTypeLogicInput = document.createElement("input"); + outputTypeLogicLabel.appendChild(outputTypeLogicInput); + outputTypeLogicInput.setAttribute("id", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix + + "_LOGIC"); + outputTypeLogicInput.setAttribute("value", "LOGIC"); + outputTypeLogicInput.setAttribute("type", "radio"); + outputTypeLogicInput.setAttribute("name", "editPolicyFormTaskOutputType" + "_" + stateName + "_" + random_suffix); // group + // name + outputTypeLogicInput.setAttribute("class", "field-policy-taskoutputtype"); + if (taskreference && taskSelected == null && !disabled) { + outputTypeLogicInput.setAttribute("class", "field-policy-taskoutputtype.new"); + } + if (taskreference != null && taskreference.outputType != null && taskreference.outputType.toUpperCase() == "LOGIC") { + outputTypeLogicInput.checked = true; + } + outputTypeLogicInput.readOnly = disabled; + // output selected + var outputSelectionTD = document.createElement("td"); + taskTR.appendChild(outputSelectionTD); + var dir_outputselected = null; + var logic_outputselected = null; + if (taskreference != null && taskreference.output != null && taskreference.output.localName != null + && taskreference.outputType != null && taskreference.outputType.toUpperCase() == "DIRECT") { + dir_outputselected = { + "name" : taskreference.output.localName, + "displaytext" : taskreference.output.localName + }; + } else if (taskreference != null && taskreference.output != null && taskreference.output.localName != null + && taskreference.outputType != null && taskreference.outputType.toUpperCase() == "LOGIC") { + logic_outputselected = { + "name" : taskreference.output.localName, + "displaytext" : taskreference.output.localName + }; + } + var dir_outputOptions = new Array(); + if (state != null && state.stateOutputs != null && $.isArray(state.stateOutputs.entry)) { + for (let value of state.stateOutputs.entry) { + var outputEntry = value.key; + dir_outputOptions.push({ + "name" : outputEntry, + "displaytext" : outputEntry + }); + } + } + var logic_outputOptions = new Array(); + if (state != null && state.stateFinalizerLogicMap != null && $.isArray(state.stateFinalizerLogicMap.entry)) { + for (let value of state.stateFinalizerLogicMap.entry) { + outputEntry = value.key; + logic_outputOptions.push({ + "name" : outputEntry, + "displaytext" : outputEntry + }); + } + } + var dir_selectDiv = document.createElement("div"); + dir_selectDiv.appendChild(new dropdownList("editPolicyFormTaskDirectOutputSelection" + "_" + stateName + "_" + + random_suffix, dir_outputOptions, dir_outputselected, disabled, null, function() { + return editPolicyForm_State_getDirectOutputMappingOptions(stateName); + })); + outputSelectionTD.appendChild(dir_selectDiv); + var logic_selectDiv = document.createElement("div"); + logic_selectDiv.appendChild(dropdownList("editPolicyFormTaskLogicOutputSelection" + "_" + stateName + "_" + + random_suffix, logic_outputOptions, logic_outputselected, disabled, null, function() { + return editPolicyForm_State_getLogicOutputMappingOptions(stateName); + })); + outputSelectionTD.appendChild(logic_selectDiv); + if (outputTypeLogicInput.checked) { + dir_selectDiv.style.display = "none"; + logic_selectDiv.style.display = "inline"; + } else if (outputTypeDirectInput.checked) { + dir_selectDiv.style.display = "inline"; + logic_selectDiv.style.display = "none"; + } else { + dir_selectDiv.style.display = "none"; + logic_selectDiv.style.display = "none"; + } + outputTypeDirectInput.onclick = function() { + if (this.checked) { + dir_selectDiv.style.display = "inline"; + logic_selectDiv.style.display = "none"; + } else { + dir_selectDiv.style.display = "none"; + logic_selectDiv.style.display = "inline"; + } + }; + outputTypeLogicInput.onclick = function() { + if (this.checked) { + dir_selectDiv.style.display = "none"; + logic_selectDiv.style.display = "inline"; + } else { + dir_selectDiv.style.display = "inline"; + logic_selectDiv.style.display = "none"; + } + }; +} + +function editPolicyForm_State_getLogicOutputMappingOptions(statename) { + var outputoptions = new Array(); + var finalizerstablerows = document.getElementById("editPolicyFormLogicOutputsTable_" + statename).rows; + + if (finalizerstablerows && finalizerstablerows.length > 2) { // has head + // so just + // ignore + // (2) top + // row and + // bottom + // row + for (var i = 1; i < finalizerstablerows.length - 1; i++) { + var finalizerTR = finalizerstablerows[i]; + if (finalizerTR && finalizerTR.getAttribute("finalizer_id")) { + var finalizer_id = finalizerTR.getAttribute("finalizer_id"); + var finalizerlocalname = document.getElementById("editPolicyFormLogicOutputNameValue_" + statename + + "_" + finalizer_id).value; + if (finalizerlocalname != null && finalizerlocalname != "") { + outputoptions.push({ + "name" : finalizerlocalname, + "displaytext" : finalizerlocalname + }); + } + } + } + } + return outputoptions; +} + +function editPolicyForm_State_getDirectOutputMappingOptions(statename) { + var outputoptions = new Array(); + var outputstablerows = document.getElementById("editPolicyFormDirOutputsTable_" + statename).rows; + if (outputstablerows && outputstablerows.length > 2) { // has head so just + // ignore (2) top + // row and bottom + // row + for (var i = 1; i < outputstablerows.length - 1; i++) { + var outputTR = outputstablerows[i]; + if (outputTR && outputTR.getAttribute("output_id")) { + var output_id = outputTR.getAttribute("output_id"); + var outputlocalname = document.getElementById("editPolicyFormDirectOutputNameValue_" + statename + "_" + + output_id).value; + if (outputlocalname != null && outputlocalname != "") { + outputoptions.push({ + "name" : outputlocalname, + "displaytext" : outputlocalname + }); + } + } + } + } + return outputoptions; +} + +function editPolicyForm_State_getStateBean(statename) { + if (statename == null || statename == "") { + console.error("Request for '" + statename + "' state!"); + alert("Request for '" + statename + "' state!"); + return null; + } + var div = document.getElementById("editPolicyFormStateDiv_" + statename); + + if (div == null) { + console.error("State information requested for state " + statename + ", but that state does not exist!") + alert("State information requested for state " + statename + ", but that state does not exist!"); + return null; + } + var ret = new Object(); + // name + ret["name"] = statename; + // trigger + var triggervalue = document.getElementById("editPolicyFormTrigger_" + statename + "_dropdownList").selectedOption; + ret["trigger"] = null; + if (triggervalue != null && triggervalue.event != null) { + ret.trigger = { + "name" : triggervalue.event.key.name, + "version" : triggervalue.event.key.version + }; + } + // context + var statebean_context = new Array(); + var contextstablerows = document.getElementById("editPolicyFormContextsTable_" + statename).rows; + if (contextstablerows && contextstablerows.length > 1) { // no head so + // just ignore + // (1) bottom + // row + for (var i = 0; i < contextstablerows.length - 1; i++) { + var contextTR = contextstablerows[i]; + if (contextTR && contextTR.getAttribute("context_id")) { + var context_id = contextTR.getAttribute("context_id"); + var contextvalue = document.getElementById("editPolicyFormContextValue_" + statename + "_" + context_id + + "_dropdownList").selectedOption; + if (contextvalue != null && contextvalue.album != null) { + statebean_context.push({ + "name" : contextvalue.album.key.name, + "version" : contextvalue.album.key.version + }); + } + } + } + } + ret["contexts"] = statebean_context; + // outputs + var statebean_outputs = new Object(); + var outputstablerows = document.getElementById("editPolicyFormDirOutputsTable_" + statename).rows; + if (outputstablerows && outputstablerows.length > 2) { // has head so just + // ignore (2) top + // row and bottom + // row + for (var k = 1; k < outputstablerows.length - 1; k++) { + var outputTR = outputstablerows[k]; + if (outputTR && outputTR.getAttribute("output_id")) { + var output_id = outputTR.getAttribute("output_id"); + var outputlocalname = document.getElementById("editPolicyFormDirectOutputNameValue_" + statename + "_" + + output_id).value; + if (outputlocalname == null || outputlocalname == "") { + console.error("No Local Name entered for Direct Output Mapping #" + k + " for state " + statename); + alert("No Local Name entered for Direct Output Mapping #" + k + " for state " + statename); + return null; + } + var nextstatevalue = document.getElementById("editPolicyFormOutputNextStateValue_" + statename + "_" + + output_id + "_dropdownList").selectedOption; + var nextstatename; + if (nextstatevalue == null) { + console.error("An option must be selected for Next State for Direct Output Mapping " + + outputlocalname + " for state " + statename); + alert("An option must be selected for Next State for Direct Output Mapping " + outputlocalname + + " for state " + statename); + return null; + } else if (nextstatevalue.name.toUpperCase() == "NULL") { + nextstatename = null; + } else { + nextstatename = nextstatevalue.name; + } + + var nexteventvalue = document.getElementById("editPolicyFormOutputEventValue_" + statename + "_" + + output_id + "_dropdownList").selectedOption; + if (nexteventvalue == null || nexteventvalue.event == null || nexteventvalue.event.key == null) { + console.error("No Output Event selected for Direct Output Mapping " + outputlocalname + + " for state " + statename); + alert("No Output Event selected for Direct Output Mapping " + outputlocalname + " for state " + + statename); + return null; + } + var nextevent = { + "name" : nexteventvalue.event.key.name, + "version" : nexteventvalue.event.key.version + }; + statebean_outputs[outputlocalname] = { + "event" : nextevent, + "nextState" : nextstatename + }; + } + } + } + ret["stateOutputs"] = statebean_outputs; + // finalizers + var statebean_finalizers = new Object(); + var finalizerstablerows = document.getElementById("editPolicyFormLogicOutputsTable_" + statename).rows; + if (finalizerstablerows && finalizerstablerows.length > 2) { // has head + // so just + // ignore + // (2) top + // row and + // bottom + // row + for (var g = 1; g < finalizerstablerows.length - 1; g++) { + var finalizerTR = finalizerstablerows[g]; + if (finalizerTR && finalizerTR.getAttribute("finalizer_id")) { + var finalizer_id = finalizerTR.getAttribute("finalizer_id"); + var finalizerlocalname = document.getElementById("editPolicyFormLogicOutputNameValue_" + statename + + "_" + finalizer_id).value; + if (finalizerlocalname == null || finalizerlocalname == "") { + console.error("No Local Name entered for Logic-based Output Mapping #" + g + " for state " + + statename); + alert("No Local Name entered for Logic-based Output Mapping #" + g + " for state " + statename); + return null; + } + + var finalizerlogicvalue = document.getElementById("editEventFormfinalizerLogicInput_" + statename + "_" + + finalizer_id + "_textarea").value; + if (finalizerlogicvalue == null || finalizerlogicvalue == "") { + console.error("No Logic is specified for Logic-based Output Mapping " + finalizerlocalname + + " for state " + statename); + alert("No Logic is specified for Logic-based Output Mapping " + finalizerlocalname + " for state " + + statename); + return null; + } + + var finalizerlogictypevalue = document.getElementById("editPolicyFormFinalizerLogicTypeInput_" + + statename + "_" + finalizer_id).value; + if (finalizerlogictypevalue == null || finalizerlogictypevalue == "") { + console.error("No Logic Type is specified for Logic-based Output Mapping " + finalizerlocalname + + " for state " + statename); + alert("No Logic Type is specified for Logic-based Output Mapping " + finalizerlocalname + + " for state " + statename); + return null; + } + statebean_finalizers[finalizerlocalname] = { + "logic" : finalizerlogicvalue, + "logicFlavour" : finalizerlogictypevalue + }; + } + } + } + ret["finalizers"] = statebean_finalizers; + // tasks & defaulttask + var statebean_tasks = new Object(); + var statebean_defaultTask = null; + var taskstablerows = document.getElementById("editPolicyFormTasksTable_" + statename).rows; + if (taskstablerows == null || taskstablerows.length <= 2) { + alert("No tasks selected for state " + statename); + console.error("No tasks selected for state " + statename); + return null; + } else { // has head so just ignore (2) top row and bottom row + for (var h = 1; h < taskstablerows.length - 1; h++) { + var taskTR = taskstablerows[h]; + if (taskTR && taskTR.getAttribute("task_id")) { + var task_id = taskTR.getAttribute("task_id"); + var tasklocalname = document.getElementById("editPolicyFormTaskLocalNameValue_" + statename + "_" + + task_id).value; + if (tasklocalname == "") { + console.error("No Local Name entered for task #" + h + " for state " + statename); + alert("No Local Name entered for task #" + h + " for state " + statename); + return null; + } + if (statebean_tasks[tasklocalname] != null) { + console.error("There cannot be more than one task called " + tasklocalname + " for state " + + statename); + alert("There cannot be more than one task called " + tasklocalname + " for state " + statename); + return null; + } + var taskvalue = document.getElementById("editPolicyFormTaskValue_" + statename + "_" + task_id + + "_dropdownList").selectedOption; + if (taskvalue == null || taskvalue.task == null) { + console.error("No Task selected for task " + tasklocalname + " for state " + statename); + alert("No Task selected for task " + tasklocalname + " for state " + statename); + return null; + } + var task = taskvalue.task; + var r = document.querySelector('input[name="editPolicyFormTaskOutputType_' + statename + '_' + task_id + + '"]:checked'); + if (r == null) { + console.error("No Output Mapping type selected for task " + tasklocalname + " for state " + + statename); + alert("No Output Mapping type selected for task " + tasklocalname + " for state " + statename); + return null; + } + var outputtype = r.value; + var outputname = null; + if (outputtype == "DIRECT") { + var diroutput = document.getElementById("editPolicyFormTaskDirectOutputSelection_" + statename + + "_" + task_id + "_dropdownList").selectedOption; + if (diroutput == null) {// } || diroutput.output == null){ + console.error("No DIRECT Output Mapping selected for task " + tasklocalname + " for state " + + statename); + alert("No DIRECT Output Mapping selected for task " + tasklocalname + " for state " + statename); + } + outputname = diroutput.name; + } else if (outputtype == "LOGIC") { + var logoutput = document.getElementById("editPolicyFormTaskLogicOutputSelection_" + statename + "_" + + task_id + "_dropdownList").selectedOption; + if (logoutput == null || logoutput.name == null) { + console.error("No LOGIC Output Mapping selected for task " + tasklocalname + " for state " + + statename); + alert("No LOGIC Output Mapping selected for task " + tasklocalname + " for state " + statename); + } + outputname = logoutput.name; + } else { + console.error("Unknown Output Mapping type ('" + outputtype + "') selected for task " + + tasklocalname + " for state " + statename); + alert("Unknown Output Mapping type ('" + outputtype + "') selected for task " + tasklocalname + + " for state " + statename); + return null; + } + statebean_tasks[tasklocalname] = { + "task" : { + "name" : task.key.name, + "version" : task.key.version + }, + "outputType" : outputtype, + "outputName" : outputname + }; + + var r2 = document.getElementById("editPolicyFormTaskIsDefault_" + statename + "_" + task_id); + if (taskstablerows.length <= 3 || (r2 != null && r2.checked)) { // default + // is + // checked + // or + // there + // is + // only + // one + // task + statebean_defaultTask = { + "name" : task.key.name, + "version" : task.key.version + }; + } + + } + } + } + ret["tasks"] = statebean_tasks; + ret["defaultTask"] = statebean_defaultTask; + // tasksellogic + var tsl = document.getElementById("editEventFormTaskSelLogicInput_" + statename + "_textarea").value; + var tsl_type = document.getElementById("editPolicyFormTaskSelLogicTypeInput_" + statename).value; + if (tsl == null || tsl == "" || tsl_type == null || tsl_type == "") { + if (statebean_tasks != null && taskstablerows.length > 3) { // there is + // more than + // 1 task + console + .error("State " + + statename + + " has more than one task reference so Task Selection Logic and Task Selection Logic type must be specified"); + alert("State " + + statename + + " has more than one task reference so Task Selection Logic and Task Selection Logic type must be specified"); + return null; + } + } else if ((tsl == null || tsl == "") && (tsl_type == null || tsl_type == "")) { + ret["taskSelectionLogic"] = null; + } else { + ret["taskSelectionLogic"] = { + "logic" : tsl, + "logicFlavour" : tsl_type + }; + } + + return ret; + +} + +export { + editPolicyForm_State_generateStateDiv, + editPolicyForm_State_addPolicyContext, + editPolicyForm_State_addPolicyTask, + editPolicyForm_State_addStateDirectOutput, + editPolicyForm_State_addStateLogicOutput, + editPolicyForm_State_getDirectOutputMappingOptions, + editPolicyForm_State_getStateBean, + editPolicyForm_State_getLogicOutputMappingOptions +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js new file mode 100644 index 0000000..2aa96e4 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js @@ -0,0 +1,226 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {rightClickMenu_scopePreserver} from "./contextMenu"; +import {createTable} from "./ApexTable"; +import {ajax_get} from "./ApexAjax"; +import {apexUtils_removeElement} from "./ApexUtils"; + +function policyTab_reset() { + policyTab_deactivate(); + policyTab_activate(); +} + +function policyTab_activate() { + policyTab_create(); + + var requestURL = window.restRootURL + "/Policy/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#policyTableBody").find("tr:gt(0)").remove(); + + for (let value of data.messages.message) { + var policy = JSON.parse(value).apexPolicy; + + var policyRow_tr = document.createElement("tr"); + var policyid = policy.policyKey.name + ":" + policy.policyKey.version; + + var policyTableRow = + "" + + policyid + + "" + + "" + + policy.template + + "" + + "" + + policy.firstState + + ""; + + policyTableRow += ""; + policyTableRow += ""; + + var states = policy.state.entry; + for(var s in states) { + var state = states[s]; + if(state.key == policy.firstState) { + states.splice(s, 1); + states.unshift(state); + break; + } + } + + for (let entry of policy.state.entry) { + var stateName = entry.key; + state = entry.value; + + policyTableRow += + "" + + ""; + + policyTableRow += ""; + + policyTableRow += + "" + + ""; + + policyTableRow += ""; + + policyTableRow += ""; + + + policyTableRow += ""; + + policyTableRow += ""; + } + + policyTableRow += "
StateTriggerReferenced TasksDefault TaskTSLState OutputsState Finsalizer LogicContext Album References
" + + stateName + + "" + + state.trigger.name + ":" + state.trigger.version + + ""; + for (let taskEntry of state.taskReferences.entry) { + var taskKey = taskEntry.key; + var taskRef = taskEntry.value; + + policyTableRow += + "" + + "" + + ""; + } + policyTableRow += "
Task ReferenceOutput TypeOutput
" + + taskKey.name + ":" + taskKey.version + + "" + + taskRef.outputType + + "" + + taskRef.output.localName + + "
" + + state.defaultTask.name + ":" + state.defaultTask.version + + "" + + state.taskSelectionLogic.logicFlavour + + ""; + for (let outputEntry of state.stateOutputs.entry) { + + policyTableRow += + "" + + "" + + ""; + } + policyTableRow += "
NameNext StateEvent
" + + outputEntry.key + + "" + + outputEntry.value.nextState.localName + + "" + + outputEntry.value.outgoingEvent.name + ":" + outputEntry.value.outgoingEvent.version + + "
"; + for (let sflEntry of state.stateFinalizerLogicMap.entry) { + + policyTableRow += + "" + + ""; + } + policyTableRow += "
NameType
" + + sflEntry.key + + "" + + sflEntry.value.logicFlavour + + "
"; + for (let contextAlbumReference of state.contextAlbumReference) { + + policyTableRow += + ""; + } + policyTableRow += "
" + + contextAlbumReference.name + ":" + contextAlbumReference.version + + "
"; + + + policyRow_tr.innerHTML = policyTableRow; + policyRow_tr.addEventListener('contextmenu', rightClickMenu_scopePreserver("policyTabContent", "Policy", policy.policyKey.name, policy.policyKey.version)); + + $("#policyTableBody").append(policyRow_tr); + } + }); +} + +function policyTab_deactivate() { + apexUtils_removeElement("policyTabContent"); +} + +function policyTab_create() { + var policyTab = document.getElementById("policiesTab"); + + //Testing purposes + if(policyTab === null) { + policyTab = document.createElement("policiesTab"); + } + + var policyTabContent = document.getElementById("policyTabContent"); + if (policyTabContent != null) { + return + } + + policyTabContent = document.createElement("policyTabContent"); + policyTab.appendChild(policyTabContent); + policyTabContent.setAttribute("id", "policyTabContent"); + policyTabContent.addEventListener('contextmenu', rightClickMenu_scopePreserver("policyTabContent", "Policy", null, null)); + + var policyTable = createTable("policyTable"); + policyTabContent.appendChild(policyTable); + + var policyTableHeader = document.createElement("thead"); + policyTable.appendChild(policyTableHeader); + policyTableHeader.setAttribute("id", "policyTableHeader"); + + var policyTableHeaderRow = document.createElement("tr"); + policyTableHeader.appendChild(policyTableHeaderRow); + policyTableHeaderRow.setAttribute("id", "policyTableHeaderRow"); + + var policyTableKeyHeader = document.createElement("th"); + policyTableHeaderRow.appendChild(policyTableKeyHeader); + policyTableKeyHeader.setAttribute("id", "policyTableKeyHeader"); + policyTableKeyHeader.appendChild(document.createTextNode("Policy")); + + var policyTableTemplateHeader = document.createElement("th"); + policyTableHeaderRow.appendChild(policyTableTemplateHeader); + policyTableTemplateHeader.setAttribute("id", "policyTableTemplateHeader"); + policyTableTemplateHeader.appendChild(document.createTextNode("Template")); + + var policyTableFirstStateHeader = document.createElement("th"); + policyTableHeaderRow.appendChild(policyTableFirstStateHeader); + policyTableFirstStateHeader.setAttribute("id", "policyTableFirstStateHeader"); + policyTableFirstStateHeader.appendChild(document.createTextNode("First State")); + + var policyTableStatesHeader = document.createElement("th"); + policyTableHeaderRow.appendChild(policyTableStatesHeader); + policyTableStatesHeader.setAttribute("id", "policyTableStatesHeader"); + policyTableStatesHeader.appendChild(document.createTextNode("States")); + + var policyTableBody = document.createElement("tbody"); + policyTable.appendChild(policyTableBody); + policyTable.setAttribute("id", "policyTableBody"); +} + +export { + policyTab_activate, + policyTab_create, + policyTab_deactivate, + policyTab_reset +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexResultForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexResultForm.js new file mode 100644 index 0000000..0838ce8 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexResultForm.js @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {apexUtils_removeElement} from "./ApexUtils"; + +function resultForm_activate(formParent, formHeading, formText) { + apexUtils_removeElement("newModelDivBackground"); + + var contentelement = document.createElement("resultFormDiv"); + var formDiv = document.createElement("div"); + var backgroundDiv = document.createElement("div"); + backgroundDiv.setAttribute("id", "newModelDivBackground"); + backgroundDiv.setAttribute("class", "newModelDivBackground"); + + backgroundDiv.appendChild(formDiv); + contentelement.appendChild(backgroundDiv); + formParent.appendChild(contentelement); + + formDiv.setAttribute("id", "resultFormDiv"); + formDiv.setAttribute("class", "resultFormDiv"); + + var headingSpan = document.createElement("span"); + formDiv.appendChild(headingSpan); + + headingSpan.setAttribute("class", "headingSpan"); + headingSpan.innerHTML = formHeading; + + var form = document.createElement("resultForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "resultForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + + var ul = document.createElement("ul"); + form.appendChild(ul); + + var resultTextLI = document.createElement("li"); + form.appendChild(resultTextLI); + + var resultTextLabel = document.createElement("label"); + resultTextLI.appendChild(resultTextLabel); + resultTextLabel.setAttribute("for", "resultFormTextArea"); + resultTextLabel.innerHTML = "resultText: "; + + var resultTextArea = document.createElement("textarea"); + resultTextLI.appendChild(resultTextArea); + + resultTextArea.setAttribute("id", "resultFormTextArea"); + resultTextArea.setAttribute("resultText", "resultFormTextArea"); + resultTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full eb_scrollbar"); + resultTextArea.setAttribute("readonly", "readonly"); + resultTextArea.style.cursor = "text"; + + resultTextArea.value = formText; + + var inputLI = document.createElement("li"); + form.appendChild(inputLI); + + var okInput = document.createElement("input"); + inputLI.appendChild(okInput); + + okInput.setAttribute("id", "generateDescription"); + okInput.setAttribute("class", "okButton ebBtn"); + okInput.setAttribute("type", "submit"); + okInput.setAttribute("value", "OK"); + + okInput.onclick = resultForm_okPressed; +} + +function resultForm_okPressed() { + apexUtils_removeElement("newModelDivBackground"); +} + +export { + resultForm_activate, resultForm_okPressed +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTable.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTable.js new file mode 100644 index 0000000..0283fb7 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTable.js @@ -0,0 +1,39 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function createTable(id) { + var table = document.createElement("table"); + table.setAttribute("id", id); + table.setAttribute("class", "apexTable ebTable elTablelib-Table-table ebTable_striped"); + return table; +} + +function setRowHover(rowElement) { + rowElement.className = "ebTableRow"; + rowElement.onmouseover = function() { + this.className = "ebTableRow ebTableRow_hover"; + }; + rowElement.onmouseout = function() { + this.className = "ebTableRow"; + }; +} + +export { createTable, setRowHover }; \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js new file mode 100644 index 0000000..4932de6 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js @@ -0,0 +1,1024 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {taskTab_reset} from "./ApexTaskTab"; +import {dropdownList} from "./dropdownList"; +import { ajax_delete, ajax_getWithKeyInfo, ajax_post, ajax_put, ajax_get } from "./ApexAjax"; +import { formUtils_generateDescription, formUtils_generateUUID } from "./ApexFormUtils"; +import { apexUtils_removeElement, apexUtils_emptyElement, apexUtils_areYouSure, createAddFormButton, scrollToTop } from "./ApexUtils"; +import { showHideTextarea } from "./showhideTextarea"; +import {keyInformationTab_reset} from "./ApexKeyInformationTab"; + +function editTaskForm_createTask(formParent) { + // Get all contextSchemas too for task input/outputfields + var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + var dt = { + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }; + contextSchemas.push(dt); + } + // Get all contextAlbums too for task context album references + requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; + var contextAlbums = new Array(); + ajax_get(requestURL, function(data3) { + for (let value of data3.messages.message) { + var contextAlbum = JSON.parse(value).apexContextAlbum; + var ca = { + "name" : contextAlbum.key.name, + "version" : contextAlbum.key.version, + "displaytext" : contextAlbum.key.name + ":" + contextAlbum.key.version, + "contextAlbum" : contextAlbum + }; + contextAlbums.push(ca); + } + editTaskForm_activate(formParent, "CREATE", null, contextSchemas, contextAlbums); + }); + }); +} + +function editTaskForm_deleteTask(parent, name, version) { + var message = "Are you sure you want to delete Task \"" + name + ":" + version + "\"?"; + if (apexUtils_areYouSure(message)) { + var requestURL = window.restRootURL + "/Task/Delete?name=" + name + "&version=" + version; + ajax_delete(requestURL, function(data) { + apexUtils_removeElement("editTaskFormDiv"); + taskTab_reset(); + keyInformationTab_reset() + }); + } +} + +function editTaskForm_viewTask(formParent, name, version) { + editTaskForm_editTask_inner(formParent, name, version, "VIEW"); +} + +function editTaskForm_editTask(formParent, name, version) { + editTaskForm_editTask_inner(formParent, name, version, "EDIT"); +} + +function editTaskForm_editTask_inner(formParent, name, version, viewOrEdit) { + var requestURL = window.restRootURL + "/Task/Get?name=" + name + "&version=" + version; + ajax_getWithKeyInfo(requestURL, "apexTask", function(task) { + // Get all contextSchemas too for task inputfields + requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; + var contextSchemas = new Array(); + ajax_get(requestURL, function(data2) { + for (let value of data2.messages.message) { + var contextSchema = JSON.parse(value).apexContextSchema; + contextSchemas.push({ + "name" : contextSchema.key.name, + "version" : contextSchema.key.version, + "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version, + "contextSchema" : contextSchema + }); + } + // Get all contextAlbums too for task context album references + requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; + var contextAlbums = new Array(); + ajax_get(requestURL, function(data3) { + for (let value of data3.messages.message) { + var contextAlbum = JSON.parse(value).apexContextAlbum; + var ca = { + "name" : contextAlbum.key.name, + "version" : contextAlbum.key.version, + "displaytext" : contextAlbum.key.name + ":" + contextAlbum.key.version, + "contextAlbum" : contextAlbum + }; + contextAlbums.push(ca); + } + editTaskForm_activate(formParent, viewOrEdit, task, contextSchemas, contextAlbums); + }); + }); + }); +} + +function editTaskForm_activate(parent, operation, task, contextSchemas, contextAlbums) { + apexUtils_removeElement("editTaskFormDiv"); + var formParent = document.getElementById(parent); + + //Testing purposes + if(formParent === null) { + formParent = document.createElement('testFormParent'); + } + apexUtils_emptyElement(parent); + + var createEditOrView = ""; + + if (!operation) { + console.warn("No operation specified for TaskForm form") + } else { + createEditOrView = operation.toUpperCase(); + } + + if (createEditOrView == "EDIT" || createEditOrView == "VIEW") { + + if (!task) { + console.warn("Invalid value (\"" + task + "\") passed as a value for \"task\" for TaskForm form."); + } else { + if (!task.key || !task.key.name || task.key.name == "") { + console.warn("Invalid value (\"" + task.key.name + + "\") passed as a value for \"name\" for TaskForm form."); + } + if (!task.key || !task.key.version || task.key.version == "") { + console.warn("Invalid value (\"" + task.key.version + + "\") passed as a value for \"version\" for TaskForm form."); + } + if (!task.uuid || task.uuid == "") { + console.warn("Invalid value (\"" + task.uuid + "\") passed as a value for \"uuid\" for TaskForm form."); + } + } + } else { + console.warn("Invalid operation (\"" + operation + + "\") specified for TaskForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported"); + } + + var contentelement = document.createElement("editTaskFormDiv"); + var formDiv = document.createElement("div"); + contentelement.appendChild(formDiv); + formDiv.setAttribute("id", "editTaskFormDiv"); + formDiv.setAttribute("class", "editTaskFormDiv"); + + var headingSpan = document.createElement("h2"); + formDiv.appendChild(headingSpan); + headingSpan.innerHTML = "Task Editor"; + + var form = document.createElement("editTaskForm"); + formDiv.appendChild(form); + + form.setAttribute("id", "editTaskForm"); + form.setAttribute("class", "form-style-1"); + form.setAttribute("method", "post"); + form.setAttribute("createEditOrView", createEditOrView); + + var formul = document.createElement("ul"); + form.appendChild(formul); + + var nameLI = document.createElement("li"); + formul.appendChild(nameLI); + var nameLabel = document.createElement("label"); + nameLI.appendChild(nameLabel); + nameLabel.setAttribute("for", "editTaskFormNameInput"); + nameLabel.innerHTML = "Name: "; + var nameLabelSpan = document.createElement("span"); + nameLabel.appendChild(nameLabelSpan); + nameLabelSpan.setAttribute("class", "required"); + nameLabelSpan.innerHTML = "*"; + var nameInput = document.createElement("input"); + nameLI.appendChild(nameInput); + nameInput.setAttribute("id", "editTaskFormNameInput"); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editTaskFormNameInput"); + nameInput.setAttribute("class", "field ebInput"); + nameInput.setAttribute("placeholder", "name"); + if (task && task.key && task.key.name) { + nameInput.value = task.key.name; + } + if (createEditOrView != "CREATE") { + nameInput.readOnly = true; + } + + var versionLI = document.createElement("li"); + formul.appendChild(versionLI); + var versionLabel = document.createElement("label"); + versionLI.appendChild(versionLabel); + versionLabel.setAttribute("for", "editTaskFormVersionInput"); + versionLabel.innerHTML = "Version: "; + var versionInput = document.createElement("input"); + versionLI.appendChild(versionInput); + versionInput.setAttribute("id", "editTaskFormVersionInput"); + versionInput.setAttribute("type", "text"); + versionInput.setAttribute("name", "editTaskFormVersionInput"); + versionInput.setAttribute("class", "field ebInput"); + versionInput.setAttribute("placeholder", "0.0.1"); + if (task && task.key && task.key.version) { + versionInput.value = task.key.version; + } + if (createEditOrView != "CREATE") { + versionInput.readOnly = true; + } + + var uuidLI = document.createElement("li"); + formul.appendChild(uuidLI); + var uuidLabel = document.createElement("label"); + uuidLI.appendChild(uuidLabel); + uuidLabel.setAttribute("for", "editTaskFormUuidInput"); + uuidLabel.innerHTML = "UUID: "; + var uuidInput = document.createElement("input"); + uuidLI.appendChild(uuidInput); + uuidInput.setAttribute("id", "editTaskFormUuidInput"); + uuidInput.setAttribute("type", "text"); + uuidInput.setAttribute("name", "editTaskFormUuidInput"); + uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full"); + uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + if (task && task.uuid) { + uuidInput.value = task.uuid; + } + if (createEditOrView != "CREATE") { + uuidInput.readOnly = true; + } + + var edit_disabled = (createEditOrView != "CREATE" && createEditOrView != "EDIT"); + + // description + var descriptionLI = document.createElement("li"); + formul.appendChild(descriptionLI); + var descriptionLabel = document.createElement("label"); + descriptionLI.appendChild(descriptionLabel); + descriptionLabel.setAttribute("for", "editTaskFormDescriptionTextArea"); + descriptionLabel.innerHTML = "Description: "; + var descriptionTextArea = document.createElement("textarea"); + descriptionLI.appendChild(descriptionTextArea); + descriptionTextArea.setAttribute("id", "editTaskFormDescriptionTextArea"); + descriptionTextArea.setAttribute("name", "editTaskFormDescriptionTextArea"); + descriptionTextArea.setAttribute("class", "field-long field-textarea ebTextArea ebTextArea_width_full"); + if (task && task.description) { + descriptionTextArea.value = task.description; + } + descriptionTextArea.readOnly = edit_disabled; + + // input fields + var inputfieldsLI = document.createElement("li"); + formul.appendChild(inputfieldsLI); + var inputfieldsLabel = document.createElement("label"); + inputfieldsLI.appendChild(inputfieldsLabel); + inputfieldsLabel.setAttribute("for", "editTaskFormInputFieldsTable"); + inputfieldsLabel.innerHTML = "Task Input Fields: "; + var inputfieldstable = document.createElement("table"); + inputfieldstable.setAttribute("id", "editTaskFormInputFieldsTable"); + inputfieldstable.setAttribute("name", "editTaskFormInputFieldsTable"); + inputfieldstable.setAttribute("class", "table-taskinputfield"); + inputfieldsLI.appendChild(inputfieldstable); + var inputfieldstable_head = document.createElement("thead"); + inputfieldstable.appendChild(inputfieldstable_head); + var inputfieldstable_head_tr = document.createElement("tr"); + inputfieldstable_head.appendChild(inputfieldstable_head_tr); + inputfieldstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var inputfieldstable_head_th = document.createElement("th"); + inputfieldstable_head_tr.appendChild(inputfieldstable_head_th); + inputfieldstable_head_th.innerHTML = "Input Field Name: "; + inputfieldstable_head_th.setAttribute("class", "table-taskinputfield-heading form-heading"); + inputfieldstable_head_th = document.createElement("th"); + inputfieldstable_head_tr.appendChild(inputfieldstable_head_th); + inputfieldstable_head_th.innerHTML = "Input Field Type/Schema: "; + inputfieldstable_head_th.setAttribute("class", "table-taskinputfield-heading form-heading"); + inputfieldstable_head_th = document.createElement("th"); + inputfieldstable_head_tr.appendChild(inputfieldstable_head_th); + inputfieldstable_head_th.innerHTML = "Optional: "; + inputfieldstable_head_th.setAttribute("class", "table-eventparam-heading form-heading"); + var inputfieldstable_body = document.createElement("tbody"); + inputfieldstable.appendChild(inputfieldstable_body); + // Add the inputfields + if (task && task.inputFields && task.inputFields.entry) { + for (let inputfieldEntry of task.inputFields.entry) { + var contextSchema = inputfieldEntry.value.fieldSchemaKey; + contextSchema["displaytext"] = contextSchema.name + ":" + contextSchema.version; + editTaskForm_addTaskInputField(inputfieldstable_body, (createEditOrView == "VIEW"), inputfieldEntry.key, + inputfieldEntry.value.optional, contextSchema, contextSchemas); + } + } + // add the New Input Field button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputfieldTR = document.createElement("tr"); + inputfieldTR.setAttribute("class", "field-taskinputfield-tr.new"); + inputfieldstable_body.appendChild(inputfieldTR); + var inputfieldTD = document.createElement("td"); + inputfieldTD.setAttribute("colspan", "3"); + inputfieldTR.appendChild(inputfieldTD); + var addInputFieldInput = createAddFormButton(); + inputfieldTD.appendChild(addInputFieldInput); + addInputFieldInput.onclick = function() { + editTaskForm_addTaskInputField(inputfieldstable_body, false, null, false, null, contextSchemas); + }; + } + + // output fields + var outputfieldsLI = document.createElement("li"); + formul.appendChild(outputfieldsLI); + var outputfieldsLabel = document.createElement("label"); + outputfieldsLI.appendChild(outputfieldsLabel); + outputfieldsLabel.setAttribute("for", "editTaskFormOutputFieldsTable"); + outputfieldsLabel.innerHTML = "Task Output Fields: "; + var outputfieldstable = document.createElement("table"); + outputfieldstable.setAttribute("id", "editTaskFormOutputFieldsTable"); + outputfieldstable.setAttribute("name", "editTaskFormOutputFieldsTable"); + outputfieldstable.setAttribute("class", "table-taskoutputfield"); + outputfieldsLI.appendChild(outputfieldstable); + var outputfieldstable_head = document.createElement("thead"); + outputfieldstable.appendChild(outputfieldstable_head); + var outputfieldstable_head_tr = document.createElement("tr"); + outputfieldstable_head.appendChild(outputfieldstable_head_tr); + outputfieldstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var outputfieldstable_head_th = document.createElement("th"); + outputfieldstable_head_tr.appendChild(outputfieldstable_head_th); + outputfieldstable_head_th.innerHTML = "Output Field Name: "; + outputfieldstable_head_th.setAttribute("class", "table-taskoutputfield-heading form-heading"); + outputfieldstable_head_th = document.createElement("th"); + outputfieldstable_head_tr.appendChild(outputfieldstable_head_th); + outputfieldstable_head_th.innerHTML = "Output Field Type/Schema: "; + outputfieldstable_head_th.setAttribute("class", "table-taskoutputfield-heading form-heading"); + outputfieldstable_head_th = document.createElement("th"); + outputfieldstable_head_tr.appendChild(outputfieldstable_head_th); + outputfieldstable_head_th.innerHTML = "Optional: "; + outputfieldstable_head_th.setAttribute("class", "table-eventparam-heading form-heading"); + var outputfieldstable_body = document.createElement("tbody"); + outputfieldstable.appendChild(outputfieldstable_body); + // Add the outputfields + if (task && task.outputFields && task.outputFields.entry) { + for (let outputfieldEntry of task.outputFields.entry) { + contextSchema = outputfieldEntry.value.fieldSchemaKey; + contextSchema["displaytext"] = contextSchema.name + ":" + contextSchema.version; + editTaskForm_addTaskOutputField(outputfieldstable_body, (createEditOrView == "VIEW"), outputfieldEntry.key, + outputfieldEntry.value.optional, contextSchema, contextSchemas); + } + } + // add the New Output Field button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var outputfieldTR = document.createElement("tr"); + outputfieldTR.setAttribute("class", "field-taskoutputfield-tr.new"); + outputfieldstable_body.appendChild(outputfieldTR); + var outputfieldTD = document.createElement("td"); + outputfieldTD.setAttribute("colspan", "3"); + outputfieldTR.appendChild(outputfieldTD); + var addOutputFieldInput = createAddFormButton(); + outputfieldTD.appendChild(addOutputFieldInput); + addOutputFieldInput.onclick = function() { + editTaskForm_addTaskOutputField(outputfieldstable_body, false, null, false, null, contextSchemas); + }; + } + + // tasklogic + var tasklogicLI = document.createElement("li"); + formul.appendChild(tasklogicLI); + var tasklogicLabel = document.createElement("label"); + tasklogicLI.appendChild(tasklogicLabel); + tasklogicLabel.setAttribute("for", "editTaskFormTaskLogicTextArea"); + tasklogicLabel.innerHTML = "Task Logic: "; + var tlogic = null; + if (task && task.taskLogic && task.taskLogic.logic) { + tlogic = task.taskLogic.logic; + } + // showHideTextarea(id_prefix, content, initialshow, editable, disabled) + var textarea = showHideTextarea("editTaskFormTaskLogicTextArea", tlogic, false, !edit_disabled, false); + + tasklogicLI.appendChild(textarea); + + // tasklogic type + var taskLogicTypeLI = document.createElement("li"); + formul.appendChild(taskLogicTypeLI); + var taskLogicTypeLabel = document.createElement("label"); + taskLogicTypeLI.appendChild(taskLogicTypeLabel); + taskLogicTypeLabel.setAttribute("for", "editTaskFormTaskLogicTypeInput"); + taskLogicTypeLabel.innerHTML = "Task Logic Type / Flavour: "; + var taskLogicTypeInput = document.createElement("input"); + taskLogicTypeLI.appendChild(taskLogicTypeInput); + taskLogicTypeInput.setAttribute("id", "editTaskFormTaskLogicTypeInput"); + taskLogicTypeInput.setAttribute("type", "text"); + taskLogicTypeInput.setAttribute("name", "editTaskFormTaskLogicTypeInput"); + taskLogicTypeInput.setAttribute("class", "field-taskLogicType ebInput"); + taskLogicTypeInput.setAttribute("placeholder", "MVEL"); + if (task && task.taskLogic && task.taskLogic.logicFlavour) { + taskLogicTypeInput.value = task.taskLogic.logicFlavour; + } + if (createEditOrView != "CREATE" && createEditOrView != "EDIT") { + taskLogicTypeInput.readOnly = true; + } + + // parameters + var paramsLI = document.createElement("li"); + formul.appendChild(paramsLI); + var paramsLabel = document.createElement("label"); + paramsLI.appendChild(paramsLabel); + paramsLabel.setAttribute("for", "editTaskFormParamsTable"); + paramsLabel.innerHTML = "Task Parameters: "; + var paramstable = document.createElement("table"); + paramstable.setAttribute("id", "editTaskFormParamsTable"); + paramstable.setAttribute("name", "editTaskFormParamsTable"); + paramstable.setAttribute("class", "table-taskparam"); + paramsLI.appendChild(paramstable); + var paramstable_head = document.createElement("thead"); + paramstable.appendChild(paramstable_head); + var paramstable_head_tr = document.createElement("tr"); + paramstable_head.appendChild(paramstable_head_tr); + paramstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var paramstable_head_th = document.createElement("th"); + paramstable_head_tr.appendChild(paramstable_head_th); + paramstable_head_th.innerHTML = "Task Parameter Name: "; + paramstable_head_th.setAttribute("class", "table-taskparam-heading form-heading"); + paramstable_head_th = document.createElement("th"); + paramstable_head_tr.appendChild(paramstable_head_th); + paramstable_head_th.innerHTML = "Task Parameter Value: "; + paramstable_head_th.setAttribute("class", "table-taskparam-heading form-heading"); + var paramstable_body = document.createElement("tbody"); + paramstable.appendChild(paramstable_body); + // Add the params + if (task && task.taskParameters && task.taskParameters.entry) { + for (let paramEntry of task.taskParameters.entry) { + var paramName = paramEntry.key; + var paramValue = paramEntry.value.defaultValue; + editTaskForm_addTaskParameter(paramstable_body, (createEditOrView == "VIEW"), paramName, paramValue); + } + } + // add the Task Parameter button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var paramTR = document.createElement("tr"); + paramTR.setAttribute("class", "field-taskparam-tr.new"); + paramstable_body.appendChild(paramTR); + var paramTD = document.createElement("td"); + paramTD.setAttribute("colspan", "3"); + paramTR.appendChild(paramTD); + var addParamInput = createAddFormButton(); + paramTD.appendChild(addParamInput); + addParamInput.onclick = function() { + editTaskForm_addTaskParameter(paramstable_body, false, null, null); + }; + } + + // Context Albums references + var contextsLI = document.createElement("li"); + formul.appendChild(contextsLI); + var contextsLabel = document.createElement("label"); + contextsLI.appendChild(contextsLabel); + contextsLabel.setAttribute("for", "editTaskFormContextsTable"); + contextsLabel.innerHTML = "Context Albums used in Task Logic: "; + var contextstable = document.createElement("table"); + contextstable.setAttribute("id", "editTaskFormContextsTable"); + contextstable.setAttribute("name", "editTaskFormContextsTable"); + contextstable.setAttribute("class", "table-taskcontext"); + contextsLI.appendChild(contextstable); + var contextstable_head = document.createElement("thead"); + contextstable.appendChild(contextstable_head); + var contextstable_head_tr = document.createElement("tr"); + contextstable_head.appendChild(contextstable_head_tr); + contextstable_head_tr.appendChild(document.createElement("th")); // empty, + // for + // delete + // button + var contextstable_head_th = document.createElement("th"); + contextstable_head_tr.appendChild(contextstable_head_th); + contextstable_head_th.innerHTML = "Context Album: "; + contextstable_head_th.setAttribute("class", "table-taskcontext-heading form-heading"); + var contextstable_body = document.createElement("tbody"); + contextstable.appendChild(contextstable_body); + // Add the contexts + if (task && task.contextAlbumReference && $.isArray(task.contextAlbumReference)) { + for (let contextEntry of task.contextAlbumReference) { + var contextName = contextEntry.name + ":" + contextEntry.version; + var ce = { + "name" : contextEntry.name, + "version" : contextEntry.version, + "displaytext" : contextName + }; + editTaskForm_addTaskContext(contextstable_body, (createEditOrView == "VIEW"), contextName, ce, + contextAlbums); + } + } + // add the Task Context button + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var contextTR = document.createElement("tr"); + contextTR.setAttribute("class", "field-taskcontext-tr.new"); + contextstable_body.appendChild(contextTR); + var contextTD = document.createElement("td"); + contextTD.setAttribute("colspan", "2"); + contextTR.appendChild(contextTD); + var addContextInput = createAddFormButton(); + contextTD.appendChild(addContextInput); + addContextInput.onclick = function() { + editTaskForm_addTaskContext(contextstable_body, false, null, null, contextAlbums); + }; + } + + // buttons + var inputLI = document.createElement("li"); + formul.appendChild(inputLI); + if (createEditOrView == "CREATE") { + var generateUUIDInput = document.createElement("button"); + inputLI.appendChild(generateUUIDInput); + generateUUIDInput.setAttribute("id", "generateUUID"); + generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large"); + generateUUIDInput.setAttribute("type", "submit"); + generateUUIDInput.setAttribute("value", "Generate UUID"); + generateUUIDInput.onclick = editTaskForm_generateUUIDPressed; + generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value"); + var inputSpan0 = document.createElement("span"); + inputLI.appendChild(inputSpan0); + inputSpan0.setAttribute("class", "required"); + inputSpan0.innerHTML = " "; + + var generateDescriptionInput = document.createElement("button"); + inputLI.appendChild(generateDescriptionInput); + generateDescriptionInput.setAttribute("id", "generateDescription"); + generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large"); + generateDescriptionInput.setAttribute("type", "submit"); + generateDescriptionInput.setAttribute("value", "Generate Description"); + generateDescriptionInput.onclick = editTaskForm_generateDescriptionPressed; + generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value"); + var inputSpan1 = document.createElement("span"); + inputLI.appendChild(inputSpan1); + inputSpan1.setAttribute("class", "required"); + inputSpan1.innerHTML = " "; + } + + var cancelInput = document.createElement("button"); + inputLI.appendChild(cancelInput); + cancelInput.setAttribute("id", "cancel"); + cancelInput.setAttribute("class", "ebBtn ebBtn_large"); + cancelInput.setAttribute("type", "submit"); + cancelInput.setAttribute("value", "Cancel"); + cancelInput.onclick = editTaskForm_cancelPressed; + cancelInput.innerHTML = cancelInput.getAttribute("value"); + + if (createEditOrView == "CREATE" || createEditOrView == "EDIT") { + var inputSpan2 = document.createElement("span"); + inputLI.appendChild(inputSpan2); + inputSpan2.setAttribute("class", "required"); + inputSpan2.innerHTML = " "; + var submitInput = document.createElement("button"); + inputLI.appendChild(submitInput); + submitInput.setAttribute("id", "submit"); + submitInput.setAttribute("class", "ebBtn ebBtn_large"); + submitInput.setAttribute("type", "submit"); + submitInput.setAttribute("value", "Submit"); + submitInput.onclick = editTaskForm_submitPressed; + submitInput.innerHTML = submitInput.getAttribute("value"); + } + + formParent.appendChild(contentelement); + scrollToTop(); +} + +function editTaskForm_addTaskInputField(parentTBody, disabled, name, optional, contextSchema, contextSchemas) { + var random_suffix = formUtils_generateUUID(); + + var inputfieldTR = parentTBody.insertRow(parentTBody.rows.length - 1); + inputfieldTR.setAttribute("inputfield_id", random_suffix); + inputfieldTR.setAttribute("class", "field-taskinputfield-tr"); + if (name == null && contextSchema == null && !disabled) { + inputfieldTR.setAttribute("class", "field-taskinputfield-tr.new field-add-new"); + $(inputfieldTR).show("fast"); + } + + var deleteTD = document.createElement("td"); + inputfieldTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(inputfieldTR).hide("fast", function() { + inputfieldTR.parentNode.removeChild(inputfieldTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + var nameTD = document.createElement("td"); + inputfieldTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editTaskFormInputFieldName" + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editTaskFormInputFieldName" + "_" + random_suffix); + nameInput.setAttribute("class", "field-taskinputfield-name ebInput ebInput_width_xLong"); + if (name == null && contextSchema == null && !disabled) { + nameInput.setAttribute("class", "field-taskinputfield-name.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "Input Field Name"); + if (name) { + nameInput.value = name; + } + nameInput.readOnly = disabled; + + var contextSchemaTD = document.createElement("td"); + inputfieldTR.appendChild(contextSchemaTD); + + var selectDiv = dropdownList("editTaskFormInputFieldContextSchema" + "_" + random_suffix, contextSchemas, + contextSchema, disabled, null) + contextSchemaTD.appendChild(selectDiv); + + var inputOptionalTD = document.createElement("td"); + inputOptionalTD.setAttribute("class", "field-checkbox-center"); + inputfieldTR.appendChild(inputOptionalTD); + var inputOptional = document.createElement("input"); + inputOptional.setAttribute("type", "checkbox"); + inputOptional.setAttribute("id", "editTaskFormInputFieldOptional" + "_" + random_suffix); + inputOptional.setAttribute("name", "editTaskFormInputFieldOptional" + "_" + random_suffix); + inputOptional.setAttribute("class", "field-eventparam-optional"); + if (name == null && contextSchema == null && !disabled) { + inputOptional.setAttribute("class", "field-eventparam-optional.new"); + } + if (optional) { + inputOptional.checked = true; + } else { + inputOptional.checked = false; + } + inputOptional.disabled = disabled; + inputOptionalTD.appendChild(inputOptional); +} + +function editTaskForm_addTaskOutputField(parentTBody, disabled, name, optional, contextSchema, contextSchemas) { + var random_suffix = formUtils_generateUUID(); + + var outputfieldTR = parentTBody.insertRow(parentTBody.rows.length - 1); + outputfieldTR.setAttribute("outputfield_id", random_suffix); + outputfieldTR.setAttribute("class", "field-taskoutputfield-tr"); + if (name == null && contextSchema == null && !disabled) { + outputfieldTR.setAttribute("class", "field-taskoutputfield-tr.new field-add-new"); + $(outputfieldTR).show("fast"); + } + + var deleteTD = document.createElement("td"); + outputfieldTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(outputfieldTR).hide("fast", function() { + outputfieldTR.parentNode.removeChild(outputfieldTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon ebIcon_disabled"); + } + var nameTD = document.createElement("td"); + outputfieldTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editTaskFormOutputFieldName" + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editTaskFormOutputFieldName" + "_" + random_suffix); + nameInput.setAttribute("class", "field-taskoutputfield-name ebInput ebInput_width_xLong"); + if (name == null && contextSchema == null && !disabled) { + nameInput.setAttribute("class", "field-taskoutputfield-name.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "Output Field Name"); + if (name) { + nameInput.value = name; + } + nameInput.readOnly = disabled; + + var contextSchemaTD = document.createElement("td"); + outputfieldTR.appendChild(contextSchemaTD); + + var selectDiv = dropdownList("editTaskFormOutputFieldContextSchema" + "_" + random_suffix, contextSchemas, + contextSchema, disabled, null) + contextSchemaTD.appendChild(selectDiv); + + var outputOptionalTD = document.createElement("td"); + outputOptionalTD.setAttribute("class", "field-checkbox-center"); + outputfieldTR.appendChild(outputOptionalTD); + var outputOptional = document.createElement("input"); + outputOptional.setAttribute("type", "checkbox"); + outputOptional.setAttribute("id", "editTaskFormOutputFieldOptional" + "_" + random_suffix); + outputOptional.setAttribute("name", "editTaskFormOutputFieldOptional" + "_" + random_suffix); + outputOptional.setAttribute("class", "field-eventparam-optional"); + if (name == null && contextSchema == null && !disabled) { + outputOptional.setAttribute("class", "field-eventparam-optional.new"); + } + if (optional) { + outputOptional.checked = true; + } else { + outputOptional.checked = false; + } + outputOptional.disabled = disabled; + outputOptionalTD.appendChild(outputOptional); +} + +function editTaskForm_addTaskParameter(parentTBody, disabled, name, value) { + var random_suffix = formUtils_generateUUID(); + + var paramTR = parentTBody.insertRow(parentTBody.rows.length - 1); + paramTR.setAttribute("param_id", random_suffix); + paramTR.setAttribute("class", "field-taskparam-tr"); + if (name == null && value == null && !disabled) { + paramTR.setAttribute("class", "field-taskparam-tr.new field-add-new"); + $(paramTR).show("fast"); + } + + var deleteTD = document.createElement("td"); + paramTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(paramTR).hide("fast", function() { + paramTR.parentNode.removeChild(paramTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + var nameTD = document.createElement("td"); + paramTR.appendChild(nameTD); + var nameInput = document.createElement("input"); + nameTD.appendChild(nameInput); + nameInput.setAttribute("id", "editTaskFormParamName" + "_" + random_suffix); + nameInput.setAttribute("type", "text"); + nameInput.setAttribute("name", "editTaskFormParamName" + "_" + random_suffix); + nameInput.setAttribute("class", "field-taskparam-name ebInput ebInput_width_xLong"); + if (name == null && value == null && !disabled) { + nameInput.setAttribute("class", "field-taskparam-name.new ebInput ebInput_width_xLong"); + } + nameInput.setAttribute("placeholder", "Task Parameter Name"); + if (name) { + nameInput.value = name; + } + nameInput.readOnly = disabled; + + var valueTD = document.createElement("td"); + paramTR.appendChild(valueTD); + var paramInput = document.createElement("input"); + valueTD.appendChild(paramInput); + paramInput.setAttribute("id", "editTaskFormParamValue" + "_" + random_suffix); + paramInput.setAttribute("type", "text"); + paramInput.setAttribute("name", "editTaskFormParamValue" + "_" + random_suffix); + paramInput.setAttribute("class", "field-taskparam-value ebInput ebInput_width_xLong"); + if (name == null && value == null && !disabled) { + paramInput.setAttribute("class", "field-taskparam-value.new ebInput ebInput_width_xLong"); + } + paramInput.setAttribute("placeholder", "Task Parameter Value"); + if (value) { + paramInput.value = value; + } + paramInput.readOnly = disabled; +} + +function editTaskForm_addTaskContext(parentTBody, disabled, name, albumreference, contextAlbums) { + var random_suffix = formUtils_generateUUID(); + + var contextTR = parentTBody.insertRow(parentTBody.rows.length - 1); + contextTR.setAttribute("context_id", random_suffix); + contextTR.setAttribute("class", "field-taskcontext-tr"); + if (name == null && albumreference == null && !disabled) { + contextTR.setAttribute("class", "field-taskcontext-tr.new field-add-new"); + $(contextTR).show("fast"); + } + + var deleteTD = document.createElement("td"); + contextTR.appendChild(deleteTD); + var deleteDiv = document.createElement("div"); + deleteTD.appendChild(deleteDiv); + if (!disabled) { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete"); + deleteDiv.onclick = function(event) { + $(contextTR).hide("fast", function() { + contextTR.parentNode.removeChild(contextTR); + }); + } + } else { + deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled"); + } + var valueTD = document.createElement("td"); + contextTR.appendChild(valueTD); + + var selectDiv = dropdownList("editTaskFormContextValue" + "_" + random_suffix, contextAlbums, albumreference, + disabled, null); + valueTD.appendChild(selectDiv); +} + +function editTaskForm_generateUUIDPressed() { + document.getElementById("editTaskFormUuidInput").value = formUtils_generateUUID(); +} + +function editTaskForm_generateDescriptionPressed() { + document.getElementById("editTaskFormDescriptionTextArea").value = formUtils_generateDescription(document + .getElementById("editTaskFormNameInput").value, document.getElementById("editTaskFormVersionInput").value, + document.getElementById("editTaskFormUuidInput").value); +} + +function editTaskForm_cancelPressed() { + apexUtils_removeElement("editTaskFormDiv"); + taskTab_reset(); +} + +function editTaskForm_submitPressed() { + var createEditOrView = document.getElementById("editTaskForm").getAttribute("createEditOrView"); + if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) { + console.error("Invalid operation \"" + createEditOrView + + "\" passed to editTaskForm_submitPressed function. Edit failed"); + apexUtils_removeElement("editTaskFormDiv"); + taskTab_reset(); + return; + } + + var name = document.getElementById('editTaskFormNameInput').value; + var version = document.getElementById('editTaskFormVersionInput').value; + + // get the task inputfields + var taskbean_inputfields = null; + var inputfieldstablerows = document.getElementById("editTaskFormInputFieldsTable").rows; + if (inputfieldstablerows && inputfieldstablerows.length > 2) { + taskbean_inputfields = new Object(); + for (var i = 1; i < inputfieldstablerows.length - 1; i++) { + var inputfieldTR = inputfieldstablerows[i]; + if (inputfieldTR && inputfieldTR.getAttribute("inputfield_id")) { + var inputfield_id = inputfieldTR.getAttribute("inputfield_id"); + var inputfieldname = document.getElementById("editTaskFormInputFieldName" + "_" + inputfield_id).value; + var inputfield_optional = document.getElementById("editTaskFormInputFieldOptional" + "_" + + inputfield_id).checked; + var inputfield_dt = document.getElementById("editTaskFormInputFieldContextSchema" + "_" + inputfield_id + + "_dropdownList").selectedOption; + if (taskbean_inputfields[inputfieldname]) { + alert("Task \"" + name + "\" contains more than one Input Field called \"" + inputfieldname + "\""); + return false; + } + if (inputfield_dt == null) { + alert("Task \"" + name + "\" has no selected Context Item Schema for the Input Field called \"" + + inputfieldname + "\""); + return false; + } + var inputfield_dt_name = inputfield_dt.name; + var inputfield_dt_version = inputfield_dt.version; + taskbean_inputfields[inputfieldname] = { + "localName" : inputfieldname, + "name" : inputfield_dt_name, + "version" : inputfield_dt_version, + "optional" : inputfield_optional + }; + } + } + } + // get the task outputfields + var taskbean_outputfields = null; + var outputfieldstablerows = document.getElementById("editTaskFormOutputFieldsTable").rows; + if (outputfieldstablerows && outputfieldstablerows.length > 2) { + taskbean_outputfields = new Object(); + for (var g = 1; g < outputfieldstablerows.length - 1; g++) { + var outputfieldTR = outputfieldstablerows[g]; + if (outputfieldTR && outputfieldTR.getAttribute("outputfield_id")) { + var outputfield_id = outputfieldTR.getAttribute("outputfield_id"); + var outputfieldname = document.getElementById("editTaskFormOutputFieldName" + "_" + outputfield_id).value; + var outputfield_optional = document.getElementById("editTaskFormOutputFieldOptional" + "_" + + outputfield_id).checked; + var outputfield_dt = document.getElementById("editTaskFormOutputFieldContextSchema" + "_" + + outputfield_id + "_dropdownList").selectedOption; + if (taskbean_outputfields[outputfieldname]) { + alert("Task \"" + name + "\" contains more than one Output Field called \"" + outputfieldname + + "\""); + return false; + } + if (outputfield_dt == null) { + alert("Task \"" + name + "\" has no selected Context Item Schema for the Output Field called \"" + + outputfieldname + "\""); + return false; + } + var outputfield_dt_name = outputfield_dt.name; + var outputfield_dt_version = outputfield_dt.version; + taskbean_outputfields[outputfieldname] = { + "localName" : outputfieldname, + "name" : outputfield_dt_name, + "version" : outputfield_dt_version, + "optional" : outputfield_optional + }; + } + } + } + // get the logic fields + var logicfield = document.getElementById("editTaskFormTaskLogicTextArea_textarea").value; + var logictype = document.getElementById("editTaskFormTaskLogicTypeInput").value; + if (logictype == null || logictype == "") { + alert("Task \"" + name + "\" has no Task Logic Type"); + return false; + } + var tasklogic = { + "logic" : logicfield, + "logicFlavour" : logictype + }; + // get the task parameters + var taskbean_parameters = null; + var paramstablerows = document.getElementById("editTaskFormParamsTable").rows; + if (paramstablerows && paramstablerows.length > 2) { + taskbean_parameters = new Object(); + for (var h = 1; h < paramstablerows.length - 1; h++) { + var paramTR = paramstablerows[h]; + if (paramTR && paramTR.getAttribute("param_id")) { + var param_id = paramTR.getAttribute("param_id"); + var paramname = document.getElementById("editTaskFormParamName" + "_" + param_id).value; + var paramvalue = document.getElementById("editTaskFormParamValue" + "_" + param_id).value; + if (taskbean_parameters[paramname]) { + alert("Task \"" + name + "\" contains more than one Task Parameters called \"" + paramname + "\""); + return false; + } + taskbean_parameters[paramname] = { + "parameterName" : paramname, + "defaultValue" : paramvalue + }; + } + } + } + // get the context album references + var taskbean_context = null; + var contextstablerows = document.getElementById("editTaskFormContextsTable").rows; + if (contextstablerows && contextstablerows.length > 2) { + taskbean_context = new Array(); + for (var s = 1; s < contextstablerows.length - 1; s++) { + var contextTR = contextstablerows[s]; + if (contextTR && contextTR.getAttribute("context_id")) { + var context_id = contextTR.getAttribute("context_id"); + var contextalbumvalue = document.getElementById("editTaskFormContextValue" + "_" + context_id + + "_dropdownList").selectedOption; + if (contextalbumvalue == null) { + alert("Task \"" + name + "\" has Context Album reference, but no Context Album is selected"); + return false; + } + var contextalbumname = contextalbumvalue.displaytext; + for (let value of taskbean_context) { + if (value != null && value.name == contextalbumvalue.name + && value.version == contextalbumvalue.version) { + alert("Task \"" + name + "\" references Context Album \"" + contextalbumname + + "\" more than once"); + return false; + } + } + taskbean_context.push({ + "name" : contextalbumvalue.name, + "version" : contextalbumvalue.version + }); + } + } + } + + // generate an task bean to json-ify and send in rest request + var taskbean = { + "name" : name, + "version" : version, + "uuid" : document.getElementById('editTaskFormUuidInput').value, + "description" : document.getElementById('editTaskFormDescriptionTextArea').value, + "taskLogic" : tasklogic, + "inputFields" : taskbean_inputfields, + "outputFields" : taskbean_outputfields, + "parameters" : taskbean_parameters, + "contexts" : taskbean_context + } + var jsonString = JSON.stringify(taskbean); + + if (createEditOrView == "CREATE") { + var requestURL = window.restRootURL + "/Task/Create"; + ajax_post(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editTaskFormDiv"); + taskTab_reset(); + keyInformationTab_reset() + }); + } else if (createEditOrView == "EDIT") { + requestURL = window.restRootURL + "/Task/Update"; + ajax_put(requestURL, jsonString, function(resultData) { + apexUtils_removeElement("editTaskFormDiv"); + taskTab_reset(); + keyInformationTab_reset() + }); + } + +} + +export { + editTaskForm_activate, + editTaskForm_addTaskContext, + editTaskForm_addTaskInputField, + editTaskForm_addTaskOutputField, + editTaskForm_addTaskParameter, + editTaskForm_cancelPressed, + editTaskForm_createTask, + editTaskForm_deleteTask, + editTaskForm_editTask, + editTaskForm_editTask_inner, + editTaskForm_generateDescriptionPressed, + editTaskForm_generateUUIDPressed, + editTaskForm_submitPressed, + editTaskForm_viewTask +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js new file mode 100644 index 0000000..9c79ad4 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js @@ -0,0 +1,189 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +import {createTable} from "./ApexTable"; +import {ajax_get} from "./ApexAjax"; +import {rightClickMenu_scopePreserver} from "./contextMenu"; +import {apexUtils_removeElement} from "./ApexUtils"; + +function taskTab_reset() { + taskTab_deactivate(); + taskTab_activate(); +} + +function taskTab_activate() { + taskTab_create(); + + const requestURL = window.restRootURL + "/Task/Get?name=&version="; + + ajax_get(requestURL, function(data) { + $("#taskTableBody").find("tr:gt(0)").remove(); + + for (let value of data.messages.message) { + const task = JSON.parse(value).apexTask; + + const taskRow_tr = document.createElement("tr"); + + var taskTableRow = + "" + + task.key.name + ":" + task.key.version + + "" + + "" + + task.taskLogic.logicFlavour + + ""; + + taskTableRow += ""; + for (let fieldEntry of task.inputFields.entry) { + + taskTableRow += + "" + + ""; + } + taskTableRow += "
Field NameField Type/SchemaOptional
" + + fieldEntry.key + + "" + + fieldEntry.value.fieldSchemaKey.name + ":" + fieldEntry.value.fieldSchemaKey.version + + "" + + fieldEntry.value.optional + + "
"; + + taskTableRow += ""; + for (let fieldEntry of task.outputFields.entry) { + + taskTableRow += + "" + + ""; + } + taskTableRow += "
Field NameField Type/SchemaOptional
" + + fieldEntry.key + + "" + + fieldEntry.value.fieldSchemaKey.name + ":" + fieldEntry.value.fieldSchemaKey.version + + "" + + fieldEntry.value.optional + + "
"; + + taskTableRow += ""; + for (let parameterEntry of task.taskParameters.entry) { + + taskTableRow += + "" + + ""; + } + taskTableRow += "
Parameter NameDefault Value
" + + parameterEntry.key + + "" + + parameterEntry.value.defaultValue + + "
"; + + taskTableRow += ""; + for (let contextAlbumReference of task.contextAlbumReference) { + + taskTableRow += + ""; + } + taskTableRow += "
" + + contextAlbumReference.name + ":" + contextAlbumReference.version + + "
"; + + taskRow_tr.innerHTML = taskTableRow; + taskRow_tr.addEventListener('contextmenu', rightClickMenu_scopePreserver("taskTabContent", "Task", task.key.name, task.key.version)); + + $("#taskTableBody").append(taskRow_tr); + + } + }); +} + +function taskTab_deactivate() { + apexUtils_removeElement("taskTabContent"); +} + +function taskTab_create() { + var taskTab = document.getElementById("tasksTab"); + + //Testing purposes + if(taskTab === null) { + taskTab = document.createElement("tasksTab"); + } + + var taskTabContent = document.getElementById("taskTabContent"); + if (taskTabContent != null) { + return + } + + taskTabContent = document.createElement("taskTabContent"); + taskTab.appendChild(taskTabContent); + taskTabContent.setAttribute("id", "taskTabContent"); + taskTabContent.addEventListener('contextmenu', rightClickMenu_scopePreserver("taskTabContent", "Task", null, null)); + + var taskTable = createTable("taskTable"); + taskTabContent.appendChild(taskTable); + + var taskTableHeader = document.createElement("thead"); + taskTable.appendChild(taskTableHeader); + taskTableHeader.setAttribute("id", "taskTableHeader"); + + var taskTableHeaderRow = document.createElement("tr"); + taskTableHeader.appendChild(taskTableHeaderRow); + taskTableHeaderRow.setAttribute("id", "taskTableHeaderRow"); + + var taskTableKeyHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableKeyHeader); + taskTableKeyHeader.setAttribute("id", "taskTableKeyHeader"); + taskTableKeyHeader.appendChild(document.createTextNode("Task")); + + var taskTableLogicFlavourHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableLogicFlavourHeader); + taskTableLogicFlavourHeader.setAttribute("id", "taskTableLogicFlavourHeader"); + taskTableLogicFlavourHeader.appendChild(document.createTextNode("Logic Flavour")); + + var taskTableInputFieldHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableInputFieldHeader); + taskTableInputFieldHeader.setAttribute("id", "taskTableInputFieldHeader"); + taskTableInputFieldHeader.appendChild(document.createTextNode("Input Fields")); + + var taskTableOutputFieldHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableOutputFieldHeader); + taskTableOutputFieldHeader.setAttribute("id", "taskTableOutputFieldHeader"); + taskTableOutputFieldHeader.appendChild(document.createTextNode("Output Fields")); + + var taskTableParameterHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableParameterHeader); + taskTableParameterHeader.setAttribute("id", "taskTableParameterHeader"); + taskTableParameterHeader.appendChild(document.createTextNode("Parameters")); + + var taskTableContextReferenceHeader = document.createElement("th"); + taskTableHeaderRow.appendChild(taskTableContextReferenceHeader); + taskTableContextReferenceHeader.setAttribute("id", "taskTableContextReferenceHeader"); + taskTableContextReferenceHeader.appendChild(document.createTextNode("Context Album References")); + + var taskTableBody = document.createElement("tbody"); + taskTable.appendChild(taskTableBody); + taskTable.setAttribute("id", "taskTableBody"); +} + +export { + taskTab_create, + taskTab_reset, + taskTab_activate, + taskTab_deactivate +}; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexUtils.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexUtils.js new file mode 100644 index 0000000..2b18559 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexUtils.js @@ -0,0 +1,140 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function apexUtils_areYouSure(message) { + return confirm(message); +} + +function apexUtils_emptyElement(elementname) { + var element = document.getElementById(elementname); + if (element != null) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + } +} + +function apexUtils_removeElement(elementname) { + var element = document.getElementById(elementname); + if (element != null) { + element.parentNode.removeChild(element); + } +} + +var _entityMap = { + '&' : '&', + '<' : '<', + '>' : '>', + '"' : '"', + "'" : ''', + '/' : '/', + '`' : '`', + '=' : '=', + '\n' : '
', + '\t' : '    ', + ' ' : ' ', +}; + +function apexUtils_escapeHtml(string) { + return String(string).replace(/[&<>"'\/\t\n ]/g, function(s) { + return _entityMap[s]; + }); +} + +function apexUtils_deleteTableRow(tablename, tablerowindex) { + document.getElementById(tablename).deleteRow(tablerowindex) +} + +function createAddFormButton(_text) { + var text = _text ? _text : "Add"; + var element = document.createElement("div"); + element.setAttribute("class", "add-field") + var addIcon = document.createElement("i"); + addIcon.setAttribute("class", "form-add-icon ebIcon ebIcon_add"); + var addText = document.createElement("span"); + addText.setAttribute("class", "form-add-text"); + addText.innerHTML = text; + element.appendChild(addIcon); + element.appendChild(addText); + return element; +} + +function createEditArea(id, options, callback) { + options = options ? options : {}; + var syntax = options.syntax ? options.syntax : "java"; + var start_highlight = options.start_highlight ? options.start_highlight : true; + var min_height = options.min_height ? options.min_height : 400; + var font_size = options.font_size ? options.font_size : 12 + var is_editable = options.hasOwnProperty("is_editable") ? options.is_editable : true; + var toolbar = options.toolbar ? options.toolbar : "select_font, |, highlight, reset_highlight"; + + setTimeout(function() { + editAreaLoader.init({ + id : id, + is_editable : is_editable, + syntax : syntax, + start_highlight : start_highlight, + min_height : min_height, + font_size : font_size, + toolbar : toolbar, + change_callback : "onEditAreaChange" + }); + }, 100); + +} + +function onEditAreaChange(id) { + $("#" + id).val(editAreaLoader.getValue(id)); +} + +function isFirefox() { + return (navigator.userAgent.indexOf("Firefox") != -1); +} + +function scrollToTop(element) { + element = element ? element : "html, body"; + $(element).animate({ + scrollTop : 0 + }, 'fast'); +} + +function getHomepageURL() { + var homepageURL = location.protocol + + "//" + + window.location.hostname + + (location.port ? ':' + location.port : '') + + (location.pathname.endsWith("/editor/") ? location.pathname.substring(0, location.pathname + .indexOf("editor/")) : location.pathname); + location.href = homepageURL; +} + +export { + apexUtils_removeElement, + apexUtils_emptyElement, + scrollToTop, + apexUtils_areYouSure, + createAddFormButton, + apexUtils_escapeHtml, + apexUtils_deleteTableRow, + createEditArea, + isFirefox, + getHomepageURL +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js new file mode 100644 index 0000000..dadbaa0 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js @@ -0,0 +1,207 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexAjax'); + +const requestURL = "http://localhost:7979"; +let data = {}; + +beforeEach(() => { + data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: '' + }, + content: ['01', '02'], + result: 'ok', + ok: true + }; +}); + +test('Test ajax_get error', () => { + const callback = jest.fn(); + $.ajax = jest.fn().mockImplementation((args) => { + args.error(data, null, null); + }); + const mock_get_error = jest.fn(mod.ajax_get(requestURL, callback)); + mock_get_error(); + expect(mock_get_error).toHaveBeenCalled(); +}); + +test('Test ajax_get success', (done) => { + const callback = jest.fn((actualData) => { + expect(actualData).toEqual(data); + done(); + }); + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_get(requestURL, callback); +}); + +test('Test ajax_getWithKeyInfo success', (done) => { + const myCallback = jest.fn((actual) => { + expect(actual).toEqual({ + key: { + name: "name1", + version: "version1" + }, + uuid: "UUID1", + description: "description1" + }); + done(); + }); + data.messages = { + message: [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + + ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' + ] + }; + const jqXHR = {status: 200, responseText: ""}; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_getWithKeyInfo("requestUrl", "objectType", myCallback, undefined); +}); + +test('Test ajax_getWithKeyInfo with custom key success', (done) => { + const myCallback = jest.fn((actual) => { + expect(actual).toEqual({ + customKey: { + name: "name1", + version: "version1" + }, + uuid: "UUID1", + description: "description1" + }); + done(); + }); + data.messages = { + message: [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1",' + + ' "version": "version1"}}, "objectType": {"customKey": {"name": "name1", "version": "version1"}}}' + ] + }; + const jqXHR = {status: 200, responseText: ""}; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_getWithKeyInfo("requestUrl", "objectType", myCallback, "customKey"); +}); + +test('Test ajax_delete error', () => { + const callback = jest.fn(); + const jqXHR = { status: 500, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.error(jqXHR, null, null); + }); + const mock_delete_error = jest.fn(mod.ajax_delete(requestURL, callback)); + mock_delete_error(); + expect(mock_delete_error).toHaveBeenCalled(); +}); + +test('Test ajax_delete success', (done) => { + const callback = jest.fn((actualData) => { + expect(actualData).toEqual(data); + done(); + }); + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_delete(requestURL, callback); +}); + +test('Test ajax_post error', () => { + const callback = jest.fn(); + const jqXHR = { status: 500, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.error(jqXHR, null, null); + }); + const mock_post_error = jest.fn(mod.ajax_post(requestURL, data, callback)); + mock_post_error(); + expect(mock_post_error).toHaveBeenCalled(); +}); + +test('Test ajax_post success', (done) => { + const callback = jest.fn((actualData) => { + expect(actualData).toEqual(data); + done(); + }); + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_post(requestURL, data, callback); +}); + +test('Test ajax_put error', () => { + const callback = jest.fn(); + const jqXHR = { status: 500, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.error(jqXHR, null, null); + }); + const mock_put_error = jest.fn(mod.ajax_put(requestURL, callback)); + mock_put_error(); + expect(mock_put_error).toHaveBeenCalled(); +}); + +test('Test ajax_put success', (done) => { + const callback = jest.fn((actualData) => { + expect(actualData).toEqual(data); + done(); + }); + const jqXHR = { status: 200, responseText: "" }; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_put(requestURL, data, callback); +}); + +test('Test ajax_getOKOrFail error', () => { + const callback = jest.fn(); + const jqXHR = { status: 500, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.error(jqXHR, null, null); + }); + const mock_getOKOrFail_error = jest.fn(mod.ajax_getOKOrFail(requestURL, callback)); + mock_getOKOrFail_error(); + expect(mock_getOKOrFail_error).toHaveBeenCalled(); +}); + +test('Test ajax_getOKOrFail success', (done) => { + const callback = jest.fn((actualData) => { + expect(actualData).toEqual(data); + done(); + }); + const jqXHR = { status: 200, responseText: "" }; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + mod.ajax_getOKOrFail(requestURL, callback); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js new file mode 100644 index 0000000..8bc3ed0 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js @@ -0,0 +1,144 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexContextAlbumEditForm'); +const apexUtils = require('../ApexUtils'); +const contextAlbumTab_reset = require('../ApexContextAlbumTab'); +const keyInformationTab_reset = require('../ApexKeyInformationTab'); +const formUtils_generateDescription = require('../ApexFormUtils'); + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + +test('Test mock_editContextAlbumForm_activate', () => { + const mock_editContextAlbumForm_activate = jest.fn(mod.editContextAlbumForm_activate); + + const contextAlbum = { + name: 'testName', + version: '0.0.1', + scope: 'test', + uuid: 'testUUID', + description: 'testDesc', + writeable: true + }; + const contextSchema = { + name: 'testName', + version: '0.0.1', + schemaFlavour: 'testFlav', + schemaDefinition: 'testDef', + uuid: 'testUUID', + description: 'testDesc' + } + + mock_editContextAlbumForm_activate('parentTest', 'CREATE', contextAlbum, contextSchema); + expect(mock_editContextAlbumForm_activate).toHaveBeenCalledTimes(1); +}); + +test('Test Create Context Album', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editContextAlbumForm_createContextAlbum); + mock_activate('parentTest'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Delete Context Album', () => { + global.confirm = () => true + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(contextAlbumTab_reset, 'contextAlbumTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextAlbumForm_deleteContextAlbum); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test View Context Album', () => { + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editContextAlbumForm_viewContextAlbum); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Context Album', () => { + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editContextAlbumForm_editContextAlbum); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Submit Pressed', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(contextAlbumTab_reset, 'contextAlbumTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextAlbumForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Generate UUID Pressed', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextAlbumFormUuidInput"); + elementMock.value = 'one' + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editContextAlbumForm_generateUUIDPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Generate Description Pressed', () => { + jest.spyOn(formUtils_generateDescription, 'formUtils_generateDescription').mockReturnValueOnce(null); + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextAlbumFormDescriptionTextArea"); + elementMock.value = 'one' + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editContextAlbumForm_generateDescriptionPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test editContextAlbumForm_cancelPressed', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValue(null); + jest.spyOn(document, 'getElementById').mockReturnValue(null); + jest.spyOn(contextAlbumTab_reset, 'contextAlbumTab_reset').mockReturnValue(null); + const mock_activate = jest.fn(mod.editContextAlbumForm_cancelPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumTab.test.js new file mode 100644 index 0000000..e109174 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumTab.test.js @@ -0,0 +1,27 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexContextAlbumTab'); +const utils = require('../ApexUtils'); + +test('Test contextAlbumTab_create', () => { + const mock_activate = jest.fn(mod.contextAlbumTab_activate); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js new file mode 100644 index 0000000..87b4f82 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexContextSchemaEditForm'); +const apexUtils = require('../ApexUtils'); +const apexContextSchemaTab = require('../ApexContextSchemaTab'); +const keyInformationTab_reset = require('../ApexKeyInformationTab'); +const apexAjax = require('../ApexAjax'); +const formUtils_generateDescription = require('../ApexFormUtils'); + +let data = { + messages: { + message: [] + }, + ok: true +}; +const contextSchema = { + name: 'testName', + version: '0.0.1', + schemaFlavour: 'testFlav', + schemaDefinition: 'testDef', + uuid: 'testUUID', + description: 'testDesc' +} + +test('Test editContextSchemaForm_createContextSchema', () => { + const mock_editContextSchemaForm_createContextSchema = jest.fn(mod.editContextSchemaForm_createContextSchema); + mock_editContextSchemaForm_createContextSchema('parentTest', 'CREATE', contextSchema); + expect(mock_editContextSchemaForm_createContextSchema).toBeCalled(); +}); + +test('Test Delete Context Schema', () => { + global.confirm = () => true + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextSchemaForm_deleteContextSchema); + mock_activate('parent', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test View Context Schema', () => { + jest.spyOn(apexAjax, 'ajax_getWithKeyInfo').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextSchemaForm_viewContextSchema); + mock_activate('parent', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Activate Context Schema', () => { + const mock_activate = jest.fn(mod.editContextSchemaForm_activate); + mock_activate('parent', 'operation', contextSchema); + expect(mock_activate).toBeCalled(); +}); + +test('Test Generate UUID Pressed', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextSchemaFormUuidInput"); + elementMock.value = 'one' + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editContextSchemaForm_generateUUIDPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Generate Description Pressed', () => { + jest.spyOn(formUtils_generateDescription, 'formUtils_generateDescription').mockReturnValueOnce(null); + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextSchemaFormDescriptionTextArea"); + elementMock.value = 'one' + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editContextSchemaForm_generateDescriptionPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Cancel Pressed', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextSchemaForm_cancelPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Submit Pressed', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editContextSchemaForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js new file mode 100644 index 0000000..3883bd5 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexContextSchemaTab'); + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + +test('Test activateContextSchema', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.contextSchemaTab_activate); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test deactivate', () => { + const mock_deactivate = jest.fn(mod.contextSchemaTab_deactivate); + mock_deactivate(); + expect(mock_deactivate).toBeCalledWith(); +}); + +test('Test reset', () => { + const mock_deactivate = jest.fn(mod.contextSchemaTab_reset); + mock_deactivate(); + expect(mock_deactivate).toBeCalledWith(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js new file mode 100644 index 0000000..48573e8 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js @@ -0,0 +1,193 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexEventEditForm'); +const eventTab_reset = require('../ApexEventTab'); +const apexUtils = require('../ApexUtils'); +const formUtils_generateDescription = require('../ApexFormUtils'); +const keyInformationTab_reset = require('../ApexKeyInformationTab'); + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + +const contextSchema = { + name: 'testName', + version: '0.0.1', + schemaFlavour: 'testFlav', + schemaDefinition: 'testDef', + uuid: 'testUUID', + description: 'testDesc' +} + +const parentTBody = document.createElement('table'); + +test('Test Activate', () => { + const mock_activate = jest.fn(mod.editEventForm_activate); + mock_activate(null, 'CREATE', null, contextSchema); + expect(mock_activate).toBeCalled(); +}); + +test('Test Activate Edit', () => { + + const event = { + key: { + name: 'testName', + version: '0.0.1', + }, + nameSpace: 'test', + source: 'test', + target: 'test', + uuid: 'test', + description: 'test', + } + + const mock_activate = jest.fn(mod.editEventForm_activate); + mock_activate(null, 'EDIT', event, contextSchema); + expect(mock_activate).toBeCalled(); +}); + +test('Test Activate !=Create/Edit', () => { + + const event = { + key: { + name: 'testName', + version: '0.0.1', + }, + nameSpace: 'test', + source: 'test', + target: 'test', + uuid: 'test', + description: 'test', + } + + const mock_activate = jest.fn(mod.editEventForm_activate); + mock_activate(null, 'TEST', event, contextSchema); + expect(mock_activate).toBeCalled(); +}); + +test('Test Delete Event', () => { + global.confirm = () => true + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(eventTab_reset, 'eventTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editEventForm_deleteEvent); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Event Edit Form Inner', () => { + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_emptyElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editEventForm_editEvent_inner); + mock_activate('parentTest', 'name', 'version', 'edit'); + expect(mock_activate).toBeCalled(); +}); + +test('Test View Event', () => { + const mock_activate = jest.fn(mod.editEventForm_viewEvent); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Event', () => { + const mock_activate = jest.fn(mod.editEventForm_editEvent); + mock_activate('parentTest', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Create Event', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editEventForm_createEvent); + mock_activate('parentTest'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editEventForm_addEventParam', () => { + let contextSchemas = new Array(); + contextSchemas.push(contextSchema); + const mock_activate = jest.fn(mod.editEventForm_addEventParam); + mock_activate(parentTBody, false, 'name', null, contextSchema, contextSchemas); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Event Generate UUID Pressed', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextSchemaFormDescriptionTextArea"); + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editEventForm_generateUUIDPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Event Generate Description Pressed', () => { + jest.spyOn(formUtils_generateDescription, 'formUtils_generateDescription').mockReturnValueOnce(null); + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editContextSchemaFormDescriptionTextArea"); + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editEventForm_generateDescriptionPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); +test('Test editEventForm_cancelPressed', () => { + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(eventTab_reset, 'eventTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editEventForm_cancelPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_submitPressed', () => { + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(eventTab_reset, 'eventTab_reset').mockReturnValueOnce(null); + + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editEventForm"); + elementMock.setAttribute("createEditOrView", "CREATE"); + elementMock.value = 'name_version' + elementMock.rows = 2 + documentSpy.mockReturnValue(elementMock); + + const mock_activate = jest.fn(mod.editEventForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js new file mode 100644 index 0000000..16042af --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js @@ -0,0 +1,119 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexEventTab'); +const ApexUtils = require('../ApexUtils'); + +afterEach(() => { + document.body.innerHTML = ''; +}); + +test('Test activate', () => { + document.body.innerHTML = '
'; + + const data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: [ + '{"apexEvent" : {"key": {"name": "name1", "version":"version1"}, "nameSpace":"nameSpace1",' + + ' "source":"source1", "target":"target1", "parameter": ' + + '{"entry": [{"key": "key1", "value": {"optional":"optional", "fieldSchemaKey": ' + + '{"name": "name2", "version":"version2"}}}]}}}' + ] + }, + content: ['01', '02'], + result: 'ok', + ok: true + }; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, null); + }); + + const expected = '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
EventName SpaceSourceTargetParameters
name1:version1nameSpace1source1target1' + + '' + + '
ParameterParameter Type/SchemaOptional
key1name2:version2optional
'; + + mod.eventTab_activate(); + expect(document.body.innerHTML).toBe(expected); +}); + +test('Test deactivate', (done) => { + ApexUtils.apexUtils_removeElement = jest.fn(id => { + expect(id).toBe('eventTabContent'); + done() + }); + mod.eventTab_deactivate(); +}); + + +test('Test create eventTabContent exists', () => { + document.body.innerHTML = '
'; + mod.eventTab_create(); + expect(document.body.innerHTML).toBe('
'); +}); + +test('Test create eventsTab does not exist', () => { + document.body.innerHTML = '
'; + mod.eventTab_create(); + expect(document.body.innerHTML).toBe('
'); +}); + +test('Test create', () => { + document.body.innerHTML = '
'; + + const expected = '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
EventName SpaceSourceTargetParameters
' + + '
'; + + mod.eventTab_create(); + expect(document.body.innerHTML).toBe(expected); +}); + + +// These are being tested indirectly +// But could be tested individually here if needed +test.todo('Test reset'); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js new file mode 100644 index 0000000..f5be3cc --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js @@ -0,0 +1,57 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexFiles'); +const resultForm_activate = require('../ApexResultForm'); + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true + }; + +test('test files_open', () => { + const open = jest.fn(mod.files_fileOpen); + open(); + expect(open).toBeCalledTimes(1); +}); + +test('test files_download', () => { + const download = jest.fn(mod.files_fileDownload); + download(); + expect(download).toHaveBeenCalledTimes(1); +}); + +test('Test files_upload', () => { + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(resultForm_activate, 'resultForm_activate').mockReturnValueOnce(null); + const upload = jest.fn(mod.files_fileUpload); + upload(); + expect(upload).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFormUtils.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFormUtils.test.js new file mode 100644 index 0000000..0df839d --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFormUtils.test.js @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexFormUtils'); + +test('test generate', () => { + const mock = jest.fn(mod.formUtils_generateUUID); + mock(); + expect(mock).toBeCalledTimes(1); +}) + +test('test edit', () => { + const mock = jest.fn(mod.formUtils_generateDescription); + mock(); + expect(mock(null, null, null)).toBe("Generated description for a concept called \"null\" with version \"null\" and UUID \"null\""); + expect(mock).toBeCalledTimes(2); + + +}) \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js new file mode 100644 index 0000000..2dcc7c2 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js @@ -0,0 +1,76 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const ApexUtils = require("../ApexUtils"); +const ApexKeyInformationTab = require("../ApexKeyInformationTab"); + +test("Test keyInformationTab_activate", () => { + document.body.innerHTML = '
'; + const data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + + ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' + ] + }, + content: ['01', '02'], + result: 'ok', + ok: true + }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, null); + }); + ApexKeyInformationTab.keyInformationTab_activate(); + + const actual = document.getElementById("keyInformationTabContent"); + const expected = /name1:version1<\/td>UUID1<\/uuid><\/td>description1<\/desc><\/td>/; + expect(actual.innerHTML).toMatch(expected); +}); + +test("Test keyInformationTab_deactivate", (done) => { + ApexUtils.apexUtils_removeElement = jest.fn((id) => { + expect(id).toBe("keyInformationTabContent"); + done(); + }); + ApexKeyInformationTab.keyInformationTab_deactivate() +}) + +test("Test keyInformationTab_create, key information tab exists", () => { + document.body.innerHTML = '
'; + + ApexKeyInformationTab.keyInformationTab_create(); + const actual = document.getElementById("keyInformationTab"); + expect(actual).toBeNull(); +}); + +test("Test keyInformationTab_create, ", () => { + document.body.innerHTML = '
'; + + ApexKeyInformationTab.keyInformationTab_create(); + const actual = document.getElementById("keyInformationTabContent"); + const expected = '
Key InformationUUIDDescription
' + expect(actual.innerHTML).toBe(expected); +}); + + diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js new file mode 100644 index 0000000..13fd658 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js @@ -0,0 +1,103 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexMain'); +const $ = require('jquery'); +const apexPageControl = require('../ApexPageControl'); +const apexContextSchemaTab = require('../ApexContextSchemaTab'); +const apexEventTab = require('../ApexEventTab'); +const apexAlbumTab = require('../ApexContextAlbumTab'); +const apexTaskTab = require('../ApexTaskTab'); +const apexPolicyTab = require('../ApexPolicyTab'); +const keyInformationTab = require('../ApexKeyInformationTab'); + +require('../../dist/js/jquery-ui-1.12.1/jquery-ui.js'); + +const data = { + messages: { + message: [ + '{' + + ' "apexArtifactKey": {' + + ' "key": {' + + ' "name": "name1",' + + ' "version": "version1"' + + ' }' + + ' }' + + '}' + ] + }, + content: ['01', '02'], + result: 'ok', + ok: true +}; + +const jqXHR = { status: 200, responseText: "" }; + +test('Test main_getRestRootURL', () => { + document.documentElement.innerHTML = '' + + '' + + ''; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(window.localStorage.__proto__, 'getItem'); + window.localStorage.__proto__.getItem = jest.fn(() => true); + jest.spyOn(apexPageControl, 'pageControl_modelMode').mockReturnValueOnce(null); + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexEventTab, 'eventTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexAlbumTab, 'contextAlbumTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexTaskTab, 'taskTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_activate').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab, 'keyInformationTab_activate').mockReturnValueOnce(null); + const mock_main_getRestRootURL = jest.fn(mod.main_getRestRootURL); + mock_main_getRestRootURL(); + const expected = ''+ + '
' + expect(mock_main_getRestRootURL).toBeCalled(); + expect(document.documentElement.innerHTML).toEqual(expected); +}); + +test('Test main_getRestRootURL false', () => { + document.documentElement.innerHTML = '
'; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(window.localStorage.__proto__, 'getItem'); + window.localStorage.__proto__.getItem = jest.fn(() => false); + const mock_main_getRestRootURL = jest.fn(mod.main_getRestRootURL); + mock_main_getRestRootURL(); + expect(mock_main_getRestRootURL).toBeCalled(); + expect(document.documentElement.innerHTML).toEqual('
REST root URL set to: http://localhost/apexservices/editor/false
'); +}); + +test('Test clearLocalStorage', () => { + const mock_clearLocalStorage = jest.fn(mod.clearLocalStorage); + mock_clearLocalStorage(); + expect(mock_clearLocalStorage).toBeCalled(); +}); + +test('test ready', () => { + document.documentElement.innerHTML = ''; + window.$ = $; + $("#menu li").click(); + let h1 = document.querySelector('ul'); + expect(h1.textContent).toEqual('menuFileNew'); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js new file mode 100644 index 0000000..2144506 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js @@ -0,0 +1,96 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexModelHandling'); +const ApexResultForm = require("../ApexResultForm"); + +afterEach(() => { + document.body.innerHTML = ''; +}); + +test('Test modelHandling_analyse', (done) => { + const data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: [ + '{"apexKeyInfo": null}' + ] + }, + content: ['01'], + result: 'ok', + ok: true + }; + const expectedMessage = '{"apexKeyInfo": null}'; + document.body.innerHTML = '
'; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, null); + }); + + ApexResultForm.resultForm_activate = jest.fn((element, heading, message) => { + expect(element).not.toBeNull(); + expect(heading).toBe('Model Analysis Result'); + expect(message).toBe(expectedMessage); + done(); + }); + + mod.modelHandling_analyse(); +}); + +test('Test modelHandling_validate', (done) => { + const data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: [ + '{"apexKeyInfo": null}', + '{"apexPolicy": null}', + '{"apexEvent": null}' + ] + }, + content: ['01'], + result: 'ok', + ok: true + }; + + const expectedMessage = '{"apexPolicy": null}\n{"apexEvent": null}\n'; + + document.body.innerHTML = '
'; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, null); + }); + + ApexResultForm.resultForm_activate = jest.fn((element, heading, message) => { + expect(element).not.toBeNull(); + expect(heading).toBe('Model Validation Result'); + expect(message).toBe(expectedMessage); + done(); + }); + + mod.modelHandling_validate(); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexNewModelForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexNewModelForm.test.js new file mode 100644 index 0000000..5088988 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexNewModelForm.test.js @@ -0,0 +1,46 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexNewModelForm'); + +test('test activate', () => { + document.innerHTML = + '
' + + '
' + + '
' + + '
'; + + const mock_activate = jest.fn(mod.newModelForm_activate); + mock_activate(document.createElement("elementTest")); + expect(mock_activate).toBeCalled(); +}); + +test('Test generateUUIDPressed', () => { + document.innerHTML = + '
'; + + const mock_generateUuid = jest.fn(mod.newModelForm_generateUUIDPressed); + mock_generateUuid.mockImplementation(() => { + document.createElement("newModelFormUuidInput"); + document.getElementsByTagName("newModelFormUuidInput").value = 'test'; + }); + mock_generateUuid(); + expect(mock_generateUuid).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js new file mode 100644 index 0000000..b414bb1 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js @@ -0,0 +1,116 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexPageControl'); +const apexContextSchemaTab = require('../ApexContextSchemaTab'); +const apexEventTab = require('../ApexEventTab'); +const apexAlbumTab = require('../ApexContextAlbumTab'); +const apexTaskTab = require('../ApexTaskTab'); +const apexPolicyTab = require('../ApexPolicyTab'); +const keyInformationTab = require('../ApexKeyInformationTab'); + +test('Test showPlaceholder show', () => { + const mock_activate = jest.fn(mod.showPlaceholder); + mock_activate('show'); + expect(mock_activate).toBeCalled(); +}); + +test('Test showPlaceholder hide', () => { + const mock_activate = jest.fn(mod.showPlaceholder); + mock_activate(''); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_status', () => { + let data = { + messages: { + message: [] + }, + ok: true + }; + const mock_activate = jest.fn(mod.pageControl_status); + mock_activate(data); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_status when data is not present', () => { + let data = { + messages: { + message: [] + } + }; + const mock_activate = jest.fn(mod.pageControl_status); + mock_activate(data); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_restError', () => { + const mock_activate = jest.fn(mod.pageControl_restError); + mock_activate('', '', '', ''); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_modelMode', () => { + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexEventTab, 'eventTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexAlbumTab, 'contextAlbumTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexTaskTab, 'taskTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_activate').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab, 'keyInformationTab_activate').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.pageControl_modelMode); + mock_activate('name', 'version', 'fileName'); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_noModelMode', () => { + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexEventTab, 'eventTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexAlbumTab, 'contextAlbumTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexTaskTab, 'taskTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_activate').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab, 'keyInformationTab_activate').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.pageControl_noModelMode); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_busyMode', () => { + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexEventTab, 'eventTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexAlbumTab, 'contextAlbumTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexTaskTab, 'taskTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_activate').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab, 'keyInformationTab_activate').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.pageControl_busyMode); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test pageControl_readyMode', () => { + jest.spyOn(apexContextSchemaTab, 'contextSchemaTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexEventTab, 'eventTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexAlbumTab, 'contextAlbumTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexTaskTab, 'taskTab_activate').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_activate').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab, 'keyInformationTab_activate').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.pageControl_readyMode); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js new file mode 100644 index 0000000..b3153a9 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +const apexUtils = require('../ApexUtils'); +const apexPageControl = require('../ApexPageControl'); +const apexPolicyTab = require('../ApexPolicyTab'); +const keyInformationTab_reset = require('../ApexKeyInformationTab'); +const mod = require('../ApexPolicyEditForm'); +const policy = { + policyKey: { + name: 'testName', + version: 'testVersion', + uuid: 'testUUID' + }, + uuid: 'testUUID' +} +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + +test('Test Create Policy', () => { + const mock_activate = jest.fn(mod.editPolicyForm_createPolicy); + mock_activate('test'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Delete Policy', () => { + global.confirm = () => true + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(apexPageControl, 'pageControl_successStatus').mockReturnValueOnce(policy); + jest.spyOn(apexPolicyTab, 'policyTab_reset').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_deletePolicy); + mock_activate('test', policy.policyKey.name, policy.policyKey.version); + expect(mock_activate).toBeCalled(); +}); + +test('Test View Policy', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(apexPageControl, 'pageControl_successStatus').mockReturnValueOnce(policy); + const mock_activate = jest.fn(mod.editPolicyForm_viewPolicy); + mock_activate('test', policy.policyKey.name, policy.policyKey.version); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Policy', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editPolicyForm_editPolicy); + mock_activate('test', policy.policyKey.name, policy.policyKey.version); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Policy Inner', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(apexPageControl, 'pageControl_successStatus').mockReturnValueOnce(policy); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_editPolicy_inner); + mock_activate('test', policy, 'view'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Add New State Policy', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editEventFormNewStateInput"); + elementMock.value = 'one' + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editPolicyForm_addNewState); + const node = document.body.parentNode; + mock_activate(node, 'New State', policy, 'tasks', 'events', 'contextS', 'contextI'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Add State Policy', () => { + const mock_activate = jest.fn(mod.editPolicyForm_addState); + mock_activate('state','test', 'CREATE', policy, 'tasks', 'events', 'contextS', 'contextI'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Generate Description', () => { + const mock_activate = jest.fn(mod.editPolicyForm_generateDescriptionPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Submit Pressed', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + jest.spyOn(apexPolicyTab, 'policyTab_reset').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Submit Pressed When createEditOrView is CREATE', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let editPolicyFormElementMock = document.createElement("editPolicyForm"); + editPolicyFormElementMock.setAttribute("createEditOrView", "CREATE") + documentSpy.mockReturnValue(editPolicyFormElementMock) + const mock_activate = jest.fn(mod.editPolicyForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test Update Trigger Event', () => { + const mock_activate = jest.fn(mod.editPolicyForm_updateTriggerEventOptions); + mock_activate('events'); + expect(mock_activate).toBeCalled(); +}); + +test('Test activate CREATE', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_activate); + + mock_activate('test', 'CREATE', policy, 'tasks', 'events', 'contextS', 'contextI'); + expect(mock_activate).toBeCalled(); +}); + +test('Test activate EDIT', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_activate); + + mock_activate('test', 'EDIT', policy, 'tasks', 'events', 'contextS', 'contextI'); + expect(mock_activate).toBeCalled(); +}); + +test('Test activate !CREATE/EDIT', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editPolicyForm_activate); + + mock_activate('test', 'TEST', policy, 'tasks', 'events', 'contextS', 'contextI'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editPolicyForm_editPolicy_inner', () => { + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_editPolicyForm_editPolicy_inner = jest.fn(mod.editPolicyForm_editPolicy_inner); + mock_editPolicyForm_editPolicy_inner('formParent', policy, 'VIEW'); + expect(mock_editPolicyForm_editPolicy_inner).toBeCalled(); +}) \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm_State.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm_State.test.js new file mode 100644 index 0000000..8b73319 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm_State.test.js @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexPolicyEditForm_State'); + +const contextAlbum = { + name: 'testName', + version: '0.0.1', + scope: 'test', + uuid: 'testUUID', + description: 'testDesc', + writeable: true +}; +const contextSchema = { + name: 'testName', + version: '0.0.1', + schemaFlavour: 'testFlav', + schemaDefinition: 'testDef', + uuid: 'testUUID', + description: 'testDesc' +} + +const task = { + key: { + name: 'testName', + version: 'testVersion' + }, + uuid: 'testUUID' +}; + +const event = { + key: { + name: 'testName', + version: '0.0.1', + }, + nameSpace: 'test', + source: 'test', + target: 'test', + uuid: 'test', + description: 'test', +} + +const policy = { + policyKey: { + name: 'testName', + version: 'testVersion', + uuid: 'testUUID' + }, + uuid: 'testUUID' +} + +const state = { + trigger: { + name: 'testName', + version: '0.0.1', + } +} + +const parentTBody = document.createElement('table'); + +test('Test editPolicyForm_State_generateStateDiv CREATE', () => { + const mock_editPolicyForm_State_generateStateDiv = jest.fn(mod.editPolicyForm_State_generateStateDiv); + mock_editPolicyForm_State_generateStateDiv('CREATE', policy, 'stateName', state, task, event, contextAlbum, contextSchema); + expect(mock_editPolicyForm_State_generateStateDiv).toBeCalledWith('CREATE', policy, 'stateName', state, task, event, contextAlbum, contextSchema); +}); + +test('Test editPolicyForm_State_generateStateDiv VIEW', () => { + const mock_editPolicyForm_State_generateStateDiv = jest.fn(mod.editPolicyForm_State_generateStateDiv); + mock_editPolicyForm_State_generateStateDiv('VIEW', policy, 'stateName', state, task, event, contextAlbum, contextSchema); + expect(mock_editPolicyForm_State_generateStateDiv).toBeCalledWith('VIEW', policy, 'stateName', state, task, event, contextAlbum, contextSchema); +}); + +test('Test editPolicyForm_State_generateStateDiv EDIT', () => { + const mock_editPolicyForm_State_generateStateDiv = jest.fn(mod.editPolicyForm_State_generateStateDiv); + mock_editPolicyForm_State_generateStateDiv('EDIT', policy, 'stateName', state, task, event, contextAlbum, contextSchema); + expect(mock_editPolicyForm_State_generateStateDiv).toBeCalledWith('EDIT', policy, 'stateName', state, task, event, contextAlbum, contextSchema); +}); + +test('Test editPolicyForm_State_addStateLogicOutput', () => { + const mock_editPolicyForm_State_addStateLogicOutput = jest.fn(mod.editPolicyForm_State_addStateLogicOutput); + mock_editPolicyForm_State_addStateLogicOutput(parentTBody, false, 'stateName', state, 'outputName', 'logic', 'flavour'); + expect(mock_editPolicyForm_State_addStateLogicOutput).toBeCalledWith(parentTBody, false, 'stateName', state, 'outputName', 'logic', 'flavour'); +}); + +test('Test editPolicyForm_State_addStateDirectOutput', () => { + const mock_editPolicyForm_State_addStateDirectOutput = jest.fn(mod.editPolicyForm_State_addStateDirectOutput); + mock_editPolicyForm_State_addStateDirectOutput(parentTBody, false, 'stateName', state, 'outputName', state, event, 'options', event); + expect(mock_editPolicyForm_State_addStateDirectOutput).toBeCalledWith(parentTBody, false, 'stateName', state, 'outputName', state, event, 'options', event); +}); + +test('Test editPolicyForm_State_addPolicyContext', () => { + const mock_editPolicyForm_State_addPolicyContext = jest.fn(mod.editPolicyForm_State_addPolicyContext); + mock_editPolicyForm_State_addPolicyContext(parentTBody, false, 'stateName', 'contextName', 'ref', contextAlbum); + expect(mock_editPolicyForm_State_addPolicyContext).toBeCalledWith(parentTBody, false, 'stateName', 'contextName', 'ref', contextAlbum); +}); + +test('Test editPolicyForm_State_addPolicyTask', () => { + const mock_editPolicyForm_State_addPolicyTask = jest.fn(mod.editPolicyForm_State_addPolicyTask); + mock_editPolicyForm_State_addPolicyTask(parentTBody, false, false, state, 'stateName', 'ref', task, 'options'); + expect(mock_editPolicyForm_State_addPolicyTask).toBeCalledWith(parentTBody, false, false, state, 'stateName', 'ref', task, 'options'); + +}); + +test('Test editPolicyForm_State_getStateBean StateName is Null', () => { + jest.spyOn(global.console, 'error').mockImplementation(() => {}); + mod.editPolicyForm_State_getStateBean(null); + expect(console.error).toHaveBeenCalledTimes(2); + mod.editPolicyForm_State_getStateBean('FakeState'); + expect(console.error).toHaveBeenCalledTimes(4); + global.console.error.mockRestore(); +}); + +test('Test editPolicyForm_State_getLogicOutputMappingOptions with page', () => { + document.documentElement.innerHTML = '' + + '' + + '' + + '' + + '' + + '
cell 1cell 2
cell 3cell4
cell 5cell6
' + + ''; + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editPolicyFormLogicOutputsTable_stateName"); + elementMock.value = "localName"; + elementMock.rows = document.getElementById("editPolicyFormLogicOutputsTable_stateName").rows; + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editPolicyForm_State_getLogicOutputMappingOptions); + mock_activate('stateName'); + expect(mock_activate).toBeCalledWith('stateName'); +}); + +test('Test editPolicyForm_State_getStateBean with page', () => { + document.documentElement.innerHTML = '' + + '
' + + '
' + + '' + + '' + + '' + + '' + + '
cell 1cell 2
cell 3cell4
cell 5cell6
' + + '
' + + ''; + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editPolicyFormDirOutputsTable_stateName"); + elementMock.setAttribute("context_id", "a0"); + elementMock.setAttribute("task_id", "d0"); + elementMock.rows = document.getElementById("editPolicyFormContextsTable_stateName").rows; + elementMock.key = {"name": "name1", "version": "version1"}; + elementMock.selectedOption = + {"name": "name1", "version": "version1", + "album": { "key": { "name": 'testAlbumName', "version": '0.0.1'}}, + "event": { "key": { "name": 'testEventName', "version": '0.1.1'}}, + "task": { "key": { "name": 'tname', "version": '1.0.0'}}}; + elementMock.value = "localName"; + documentSpy.mockReturnValue(elementMock); + const mock_activate = jest.fn(mod.editPolicyForm_State_getStateBean); + mock_activate('stateName'); + expect(mock_activate).toBeCalledWith('stateName'); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js new file mode 100644 index 0000000..4136fd6 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js @@ -0,0 +1,305 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexPolicyTab'); +const ApexUtils = require('../ApexUtils'); + +afterEach(() => { + document.body.innerHTML = ''; +}); + +test('Test policyTab_activate', () => { + document.body.innerHTML = '
'; + + const data = { + useHttps: 'useHttps', + hostname: 'hostname', + port: 'port', + username: 'username', + password: 'password', + messages: { + message: [ + '{' + + ' "apexPolicy": {' + + ' "policyKey": {' + + ' "name": "name1",' + + ' "version": "version1"' + + ' },' + + ' "template": "template1",' + + ' "firstState": "key11",' + + ' "state": {' + + ' "entry": [' + + ' {' + + ' "key": "key1",' + + ' "value": {' + + ' "trigger": {' + + ' "name": "name2",' + + ' "version": "version2"' + + ' },' + + ' "taskReferences": {' + + ' "entry": [' + + ' {' + + ' "key": {' + + ' "name": "name3",' + + ' "version": "version3"' + + ' },' + + ' "version": "version2",' + + ' "value": {' + + ' "outputType": "outputType1",' + + ' "output": {' + + ' "localName": "localName1"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "defaultTask": {' + + ' "name": "name4",' + + ' "version": "version4"' + + ' },' + + ' "taskSelectionLogic": {' + + ' "logicFlavour": "logicFlavour1"' + + ' },' + + ' "stateOutputs": {' + + ' "entry": [' + + ' {' + + ' "key": "key2",' + + ' "value": {' + + ' "nextState": {' + + ' "localName": "localName2"' + + ' },' + + ' "outgoingEvent": {' + + ' "name": "name4",' + + ' "version": "version4"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "stateFinalizerLogicMap": {' + + ' "entry": [' + + ' {' + + ' "key": "key3",' + + ' "value": {' + + ' "logicFlavour": "logicFlavour2"' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "contextAlbumReference": [' + + ' {' + + ' "name": "name5",' + + ' "version": "version5"' + + ' }' + + ' ]' + + ' }' + + ' },' + + ' {' + + ' "key": "key11",' + + ' "value": {' + + ' "trigger": {' + + ' "name": "name12",' + + ' "version": "version12"' + + ' },' + + ' "taskReferences": {' + + ' "entry": [' + + ' {' + + ' "key": {' + + ' "name": "name13",' + + ' "version": "version13"' + + ' },' + + ' "version": "version12",' + + ' "value": {' + + ' "outputType": "outputType11",' + + ' "output": {' + + ' "localName": "localName11"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "defaultTask": {' + + ' "name": "name14",' + + ' "version": "version14"' + + ' },' + + ' "taskSelectionLogic": {' + + ' "logicFlavour": "logicFlavour11"' + + ' },' + + ' "stateOutputs": {' + + ' "entry": [' + + ' {' + + ' "key": "key12",' + + ' "value": {' + + ' "nextState": {' + + ' "localName": "localName12"' + + ' },' + + ' "outgoingEvent": {' + + ' "name": "name14",' + + ' "version": "version14"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "stateFinalizerLogicMap": {' + + ' "entry": [' + + ' {' + + ' "key": "key13",' + + ' "value": {' + + ' "logicFlavour": "logicFlavour12"' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "contextAlbumReference": [' + + ' {' + + ' "name": "name15",' + + ' "version": "version15"' + + ' }' + + ' ]' + + ' }' + + ' }' + + ' ]' + + ' }' + + ' }' + + '}' + ] + }, + content: ['01', '02'], + result: 'ok', + ok: true + }; + + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, null); + }); + + const expected = '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
PolicyTemplateFirst StateStates
name1:version1template1key11' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
StateTriggerReferenced TasksDefault TaskTSLState OutputsState Finsalizer LogicContext Album References
key11name12:version12' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
Task ReferenceOutput TypeOutput
name13:version13outputType11localName11
name14:version14logicFlavour11' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
NameNext StateEvent
key12localName12name14:version14
' + + '
NameType
key13logicFlavour12
name15:version15
key1name2:version2' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
Task ReferenceOutput TypeOutput
name3:version3outputType1localName1
name4:version4logicFlavour1' + + '' + + '' + + '' + + '' + + '
NameNext StateEvent
key2localName2name4:version4
' + + '
NameType
key3logicFlavour2
name5:version5
'; + + mod.policyTab_activate(); + expect(document.body.innerHTML).toBe(expected); +}); + +test('Test policyTab_deactivate', (done) => { + ApexUtils.apexUtils_removeElement = jest.fn(id => { + expect(id).toBe('policyTabContent'); + done(); + }); + + mod.policyTab_deactivate(); +}); + +test('Test policyTab_create policyTabContent exists', () => { + document.body.innerHTML = '
'; + + mod.policyTab_create(); + expect(document.body.innerHTML).toBe('
'); +}); + +test('Test policyTab_create policiesTab does not exists', () => { + document.body.innerHTML = '
'; + + mod.policyTab_create(); + expect(document.body.innerHTML).toBe('
'); +}); + +test('Test policyTab_create', () => { + document.body.innerHTML = '
'; + + const expected = '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '
PolicyTemplateFirst StateStates
'; + + mod.policyTab_create(); + expect(document.body.innerHTML).toBe(expected); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexResultForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexResultForm.test.js new file mode 100644 index 0000000..a219ac9 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexResultForm.test.js @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexResultForm'); + +test('resultForm test', () => { + document.innerHTML = + '
' + + '
' + + '
' + + '
'; + + const content = document.getElementById("elementTest"); + const mock_activate = jest.fn(mod.resultForm_activate); + mock_activate(document.createElement("elementTest"), 'heading', 'text'); + expect(mock_activate).toBeCalled(); + + const mock_pressedOK = jest.fn(mod.resultForm_okPressed); + mock_pressedOK(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTable.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTable.test.js new file mode 100644 index 0000000..864b0c9 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTable.test.js @@ -0,0 +1,43 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const ApexTable = require("../ApexTable"); + +test("Test createTable", () => { + const expected = document.createElement("table"); + expected.id = "my-id"; + expected.className = "apexTable ebTable elTablelib-Table-table ebTable_striped"; + + const actual = ApexTable.createTable(expected.id); + expect(actual).toEqual(expected); +}); + +test("Test setRowHover", () => { + const element = { + className: null, + onmouseover: null, + onmouseout: null + }; + + ApexTable.setRowHover(element); + + expect(element.className).toBe("ebTableRow"); + expect(typeof element.onmouseover).toBe("function"); + expect(typeof element.onmouseout).toBe("function"); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js new file mode 100644 index 0000000..b9982f5 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js @@ -0,0 +1,179 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexTaskEditForm'); +const apexUtils = require('../ApexUtils'); +const apexTaskTab = require('../ApexTaskTab'); +const keyInformationTab_reset = require('../ApexKeyInformationTab'); + +const contextSchema = { + name: 'testName', + version: '0.0.1', + schemaFlavour: 'testFlav', + schemaDefinition: 'testDef', + uuid: 'testUUID', + description: 'testDesc' +}; + +const task = { + key: { + name: 'testName', + version: 'testVersion' + }, + uuid: 'testUUID' +}; + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + + let contextAlbumReference = { + "name" : "TestAlbum", + "version" : "0.0.1" +}; + +const parentTBody = document.createElement('table'); + +test('Test editTaskForm_activate CREATE', () => { + const mock_activate = jest.fn(mod.editTaskForm_activate); + mock_activate('test', 'CREATE', 'task', contextSchema, 'album'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_activate EDIT', () => { + const mock_activate = jest.fn(mod.editTaskForm_activate); + mock_activate('test', 'EDIT', task, contextSchema, 'album'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Create Task', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editTaskForm_createTask); + mock_activate('test'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Delete Task', () => { + global.confirm = () => true + global.window.restRootURL = () => 'http://localhost' + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + jest.spyOn(apexTaskTab, 'taskTab_reset').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editTaskForm_deleteTask); + mock_activate('test'); + expect(mock_activate).toBeCalled(); +}); + +test('Test Edit Task Inner', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const mock_activate = jest.fn(mod.editTaskForm_editTask_inner); + mock_activate('test', 'name', 'version', 'Edit'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_addTaskInputField', () => { + const mock_activate = jest.fn(mod.editTaskForm_addTaskInputField); + let contextSchemas = new Array(); + contextSchemas.push(contextSchema); + mock_activate(parentTBody, true, 'name', null, contextSchema, contextSchemas); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_addTaskOutputField', () => { + const mock_activate = jest.fn(mod.editTaskForm_addTaskOutputField); + let contextSchemas = new Array(); + contextSchemas.push(contextSchema); + mock_activate(parentTBody, true, 'name', null, contextSchema, contextSchemas); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_addTaskParameter', () => { + const mock_activate = jest.fn(mod.editTaskForm_addTaskParameter); + mock_activate(parentTBody, true, 'name', null); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_addTaskContext', () => { + const mock_activate = jest.fn(mod.editTaskForm_addTaskContext); + let contextAlbums = new Array(); + contextAlbums.push(contextAlbumReference); + mock_activate(parentTBody, true, 'name', null, contextAlbumReference, contextAlbums); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_generateUUIDPressed', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let editTaskFormUuidInput = document.createElement("editTaskFormUuidInput"); + documentSpy.mockReturnValue(editTaskFormUuidInput); + const mock_activate = jest.fn(mod.editTaskForm_generateUUIDPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_generateDescriptionPressed', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let editTaskFormDescriptionTextArea = document.createElement("editTaskFormDescriptionTextArea"); + documentSpy.mockReturnValue(editTaskFormDescriptionTextArea); + const mock_activate = jest.fn(mod.editTaskForm_generateDescriptionPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_cancelPressed', () => { + jest.spyOn(apexTaskTab, 'taskTab_reset').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.editTaskForm_cancelPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_submitPressed', () => { + jest.spyOn(apexTaskTab, 'taskTab_reset').mockReturnValueOnce(null); + jest.spyOn(keyInformationTab_reset, 'keyInformationTab_reset').mockReturnValueOnce(null); + jest.spyOn(apexUtils, 'apexUtils_removeElement').mockReturnValueOnce(null); + + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("editTaskForm"); + elementMock.setAttribute("createEditOrView", "CREATE"); + elementMock.value = 'logictype' + documentSpy.mockReturnValue(elementMock); + + const mock_activate = jest.fn(mod.editTaskForm_submitPressed); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js new file mode 100644 index 0000000..f593bd8 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../ApexTaskTab'); + +let data = { + messages: { + message: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"},' + + '"taskLogic":{"logicFlavour":"logicFlavour"},"inputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + + '"outputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + + '"taskParameters":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},'+ + '"contextAlbumReference":[{"name":"name", "version":"version"}]},'+ + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ] + }, + ok: true +}; + +test('test dom : taskTab_activate', () => { + const jqXHR = { status: 200, responseText: "" }; + $.ajax = jest.fn().mockImplementation((args) => { + args.success(data, null, jqXHR); + }); + const activate_mock = jest.fn(mod.taskTab_activate); + activate_mock(); + expect(activate_mock).toBeCalled(); +}); + +test('test reset', () => { + const reset_mock = jest.fn(mod.taskTab_reset); + reset_mock(); + expect(reset_mock).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexUtils.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexUtils.test.js new file mode 100644 index 0000000..d00327e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexUtils.test.js @@ -0,0 +1,116 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021-2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const ApexUtils = require('../ApexUtils'); + +afterEach(() => { + delete global.confirm; + + document.body.innerHTML = ''; +}); + +test('test apexUtils_areYouSure', () => { + const errorMsg = 'My message'; + const returned = {}; + global.confirm = jest + .fn() + .mockImplementation((message) => { + expect(message).toBe(errorMsg); + return returned; + }); + + const actual = ApexUtils.apexUtils_areYouSure(errorMsg); + expect(actual).toBe(returned); +}); + +test('apexUtils_emptyElement found', () => { + document.body.innerHTML = + '
' + + ' ' + + ' ' + + '
'; + + ApexUtils.apexUtils_emptyElement('tested'); + + expect(document.body.innerHTML).toBe('
') +}); + +test('apexUtils_emptyElement found', () => { + const text = + '
' + + ' ' + + ' ' + + '
'; + document.body.innerHTML = text; + ApexUtils.apexUtils_emptyElement('tested'); + + expect(document.body.innerHTML).toBe(text) +}); + +test('apexUtils_removeElement not found', () => { + const expected = /
\s*' + + '
'; + + ApexUtils.apexUtils_removeElement('tested'); + expect(document.body.innerHTML).toMatch(expected); +}); + +test('apexUtils_escapeHtml', () => { + const actual = ApexUtils.apexUtils_escapeHtml('&"\'/`=\n\t d'); + expect(actual).toBe('&<ab>"'/`=
     d') +}); + +test('createAddFormButton no text', () => { + const expected = document.createElement('div'); + expected.setAttribute('class','add-field'); + expected.innerHTML = 'Add'; + const actual = ApexUtils.createAddFormButton(); + expect(actual).toEqual(expected); +}); + +test('createAddFormButton with text', () => { + const expected = document.createElement('div'); + expected.setAttribute('class','add-field'); + expected.innerHTML = 'My_text'; + const actual = ApexUtils.createAddFormButton('My_text'); + expect(actual).toEqual(expected); +}); + +test('test EMPTY createEditArea', () => { + const mock_activate = jest.fn(ApexUtils.createEditArea); + mock_activate('id', 'options', ''); + expect(mock_activate).toBeCalled(); +}); + +test('test getHomepageURL', () => { + const mock_activate = jest.fn(ApexUtils.getHomepageURL); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); + +test('test isFirefox', () => { + const mock_activate = jest.fn(ApexUtils.isFirefox); + mock_activate(); + expect(mock_activate).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/contextMenu.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/contextMenu.test.js new file mode 100644 index 0000000..d804b6d --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/contextMenu.test.js @@ -0,0 +1,118 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../contextMenu'); +const apexContextEdit = require('../ApexContextSchemaEditForm'); +const apexEventEdit = require('../ApexEventEditForm'); +const apexTaskEdit = require('../ApexTaskEditForm'); +const apexPolicyEdit = require('../ApexPolicyEditForm'); +const apexContextAlbumEdit = require('../ApexContextAlbumEditForm'); + +test('Test rightClickMenu', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("rightClickMenu"); + documentSpy.mockReturnValue(elementMock); + const event = new MouseEvent('click'); + const mock_activate = jest.fn(mod.rightClickMenu); + mock_activate(event, 'type', 'name', 'version'); + expect(mock_activate).toBeCalled(); +}); + +test('Test rightClickMenuCreate when Type is CONTEXTSCHEMA', () => { + global.confirm = () => true + jest.spyOn(apexContextEdit, 'editContextSchemaForm_createContextSchema').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.rightClickMenuCreate); + mock_activate('parent', 'CONTEXTSCHEMA'); + expect(mock_activate).toBeCalled(); +}); + +test('Test rightClickMenuCreate when Type is EVENT or TASK or POLICY or CONTEXTALBUM or EMPTY', () => { + global.confirm = () => true + jest.spyOn(apexEventEdit, 'editEventForm_createEvent').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.rightClickMenuCreate); + mock_activate('parent', 'EVENT'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'TASK'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'POLICY'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'CONTEXTALBUM'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', ''); + expect(mock_activate).toBeCalled(); + +}); + +test('Test rightClickMenuView when Type is CONTEXTSCHEMA or EVENT or TASK or POLICY or CONTEXTALBUM or EMPTY', () => { + global.confirm = () => true + jest.spyOn(apexContextEdit, 'editContextSchemaForm_viewContextSchema').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.rightClickMenuView); + mock_activate('parent', 'CONTEXTSCHEMA'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'EVENT'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'TASK'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'POLICY'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'CONTEXTALBUM'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', ''); + expect(mock_activate).toBeCalled(); +}); + +test('Test rightClickMenuEdit when Type is CONTEXTSCHEMA or EVENT or TASK or POLICY or CONTEXTALBUM or EMPTY', () => { + global.confirm = () => true + jest.spyOn(apexContextEdit, 'editContextSchemaForm_viewContextSchema').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.rightClickMenuEdit); + mock_activate('parent', 'CONTEXTSCHEMA'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'EVENT'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'TASK'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'POLICY'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'CONTEXTALBUM'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', ''); + expect(mock_activate).toBeCalled(); +}); + +test('Test rightClickMenuDelete when Type is CONTEXTSCHEMA or EVENT or TASK or POLICY or CONTEXTALBUM or EMPTY', () => { + jest.spyOn(apexContextEdit, 'editContextSchemaForm_deleteContextSchema').mockReturnValueOnce(null); + jest.spyOn(apexEventEdit, 'editEventForm_deleteEvent').mockReturnValueOnce(null); + jest.spyOn(apexTaskEdit, 'editTaskForm_deleteTask').mockReturnValueOnce(null); + jest.spyOn(apexPolicyEdit, 'editPolicyForm_deletePolicy').mockReturnValueOnce(null); + jest.spyOn(apexContextAlbumEdit, 'editContextAlbumForm_deleteContextAlbum').mockReturnValueOnce(null); + const mock_activate = jest.fn(mod.rightClickMenuDelete); + mock_activate('parent', 'CONTEXTSCHEMA'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'EVENT'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'TASK'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'POLICY'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', 'CONTEXTALBUM'); + expect(mock_activate).toBeCalled(); + mock_activate('parent', ''); + expect(mock_activate).toBeCalled(); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/dropdownList.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/dropdownList.test.js new file mode 100644 index 0000000..1c314af --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/dropdownList.test.js @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../dropdownList'); + +let selectedOption = { + displaytext : 'displaytext' +}; + +const page = '' + +'' + +'' + +'
' + +''; + +test('test dropdownList option select', () => { + document.documentElement.innerHTML = page; + mod.dropdownList_option_select('divName',selectedOption, false); + let expected = '' + + '
displaytext
' + + '' + + '
' + + ''; + expect(document.documentElement.innerHTML).toBe(expected); +}); + +test('test dropdownList display click', () => { + document.documentElement.innerHTML = page; + mod.dropdownList_display_click('divName',selectedOption, false, false); + const expected = '' + + '' + + '' + + '
'; + expect(document.documentElement.innerHTML).toBe(expected); + mod.dropdownList_display_click('divName',selectedOption, true, false); +}); + +test('test dropdownList filter', () => { + document.documentElement.innerHTML = '' + + '' + + '
  • test
  • ' + + ''; + let documentSpy = jest.spyOn(document, 'getElementById'); + let elementMock = document.createElement("optionDiv_search"); + elementMock.value = '1' + elementMock.id = 'divName' + documentSpy.mockReturnValue(elementMock); + mod.dropdownList_filter('optionDiv','optionUl'); + const expected = '

    tosearch

  • test
  • '; + expect(document.documentElement.innerHTML).toBe(expected); +}); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/fileMenu.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/fileMenu.test.js new file mode 100644 index 0000000..ffc9e2c --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/fileMenu.test.js @@ -0,0 +1,31 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../fileMenu'); + +test('test hideMenu', () => { + document.documentElement.innerHTML = ''; + $ = require('jquery'); + window.$ = $; + $('#menu').fileMenu(); + $('#menu').click(); + let h1 = document.querySelector('ul'); + expect(h1.textContent).toEqual('Hello world!'); +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideElement.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideElement.test.js new file mode 100644 index 0000000..6b2bfa5 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideElement.test.js @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021-2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../showhideElement'); + +test('Test editTaskForm_activate CREATE', () => { + const mock_activate = jest.fn(mod.showHideElement_display); + let documentSpy = jest.spyOn(document, 'getElementById'); + mock_activate(documentSpy, 'element', 'style', 'hidestyle', 'buttonshowStyle','buttonhideStyle'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm_activate NO CHECKBOX', () => { + const mock_activate = jest.fn(mod.showHideElement_display); + spyOn($.fn, "find").and.returnValue(false); + const mockedElementDOM = { classList: { contains: jest.fn(), remove: jest.fn(), add: jest.fn() } }; + mockedElementDOM.classList.contains.mockReturnValueOnce(true); + mockedElementDOM.classList.remove.mockReturnValueOnce(true); + mock_activate(mockedElementDOM, 'element', 'style', 'hidestyle', 'buttonshowStyle','buttonhideStyle'); + expect(mock_activate).toBeCalled(); +}); + +test('Test editTaskForm', () => { + const mock_activate = jest.fn(mod.showHideElement); + var element = document.createElement("div"); + mock_activate("id_prefix", element, true, "showText", "hideText", "style", "hidestyle", "buttonshowStyle", "buttonhideStyle"); + expect(mock_activate).toBeCalled(); +}); + + + + diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideTextArea.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideTextArea.test.js new file mode 100644 index 0000000..3a72037 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/showhideTextArea.test.js @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +const mod = require('../showhideTextarea'); + +test('Test showHideTextarea_display_hide', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let element_text = document.createElement("text_textarea"); + let element_showHide = document.createElement("text_showhide"); + documentSpy.mockReturnValue(element_text); + documentSpy.mockReturnValue(element_showHide); + const mock_activate = jest.fn(mod.showHideTextarea_display_hide); + mock_activate('text'); + expect(mock_activate).toBeCalled(); +}); + +test('Test showHideTextarea_display_show', () => { + let documentSpy = jest.spyOn(document, 'getElementById'); + let element_text = document.createElement("text_textarea"); + let element_showHide = document.createElement("text_showhide"); + documentSpy.mockReturnValue(element_text); + documentSpy.mockReturnValue(element_showHide); + const mock_activate = jest.fn(mod.showHideTextarea_display_show); + mock_activate('text'); + expect(mock_activate).toBeCalled(); +}); + + + + + diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/test-env.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/test-env.js new file mode 100644 index 0000000..8fd788a --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/test-env.js @@ -0,0 +1,2 @@ +import $ from 'jquery'; +global.$ = global.jQuery = $; \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/contextMenu.js b/gui-editors/gui-editor-apex/src/main/webapp/js/contextMenu.js new file mode 100644 index 0000000..8cd6a80 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/contextMenu.js @@ -0,0 +1,235 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +//hide the context menu, if it's shown, anytime the user clicks anywhere. +import {apexUtils_emptyElement} from "./ApexUtils"; +import { + editContextSchemaForm_createContextSchema, + editContextSchemaForm_deleteContextSchema, + editContextSchemaForm_editContextSchema, + editContextSchemaForm_viewContextSchema +} from "./ApexContextSchemaEditForm"; +import { + editEventForm_createEvent, + editEventForm_deleteEvent, + editEventForm_editEvent, + editEventForm_viewEvent +} from "./ApexEventEditForm"; +import { + editTaskForm_createTask, + editTaskForm_deleteTask, + editTaskForm_editTask, + editTaskForm_viewTask +} from "./ApexTaskEditForm"; +import { + editPolicyForm_createPolicy, + editPolicyForm_deletePolicy, + editPolicyForm_editPolicy, + editPolicyForm_viewPolicy +} from "./ApexPolicyEditForm"; +import { + editContextAlbumForm_createContextAlbum, + editContextAlbumForm_deleteContextAlbum, + editContextAlbumForm_editContextAlbum, + editContextAlbumForm_viewContextAlbum +} from "./ApexContextAlbumEditForm"; + +$(document).on("click", function(event) { + if (document.getElementById("rightClickMenu")) + document.getElementById("rightClickMenu").className = "ebContextMenu-body_visible_false"; +}); + +// Hack: need to maintain each passed parameter in a way it can be referenced by +// the onContextMenu handler function for +// each iteration inside a loop, after the passed parameter goes out of scope +// and changes. +// see +// http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example +function rightClickMenu_scopePreserver(parent, type, name, version) { + return function(clickevent) { + rightClickMenu(clickevent, parent, type, name, version); + } +} + +// Context menu when user right-clicks inside one of the display tabs +function rightClickMenu(event, parent, type, name, version) { + var rclickdiv = document.getElementById('rightClickMenu'); + if (rclickdiv == null) { + rclickdiv = document.createElement("div"); + document.body.appendChild(rclickdiv); + } + // clear the div + apexUtils_emptyElement('rightClickMenu'); + rclickdiv.setAttribute("id", "rightClickMenu"); + rclickdiv.setAttribute("title", type + " menu"); + rclickdiv.addEventListener("contextmenu", function(e) { + e.preventDefault(); + }, false); + + var ul = document.createElement("div"); + ul.setAttribute("class", "ebComponentList") + rclickdiv.appendChild(ul); + + var li1 = document.createElement("div"); + li1.setAttribute("class", "ebComponentList-item") + li1.onclick = function() { + return rightClickMenuCreate(parent, type); + }; + li1.innerHTML = "Create new " + type + ""; + if (type.toUpperCase() == "KEYINFORMATION") { + li1.setAttribute("class", "ebComponentList-item ebComponentList-item_disabled"); + } + ul.appendChild(li1); + + if (name) { + var value = name + ":" + version; + + var li4 = document.createElement("div"); + li4.setAttribute("class", "ebComponentList-item") + li4.onclick = function() { + return rightClickMenuView(parent, type, name, version); + }; + li4.innerHTML = "View " + type + " " + value + ""; + ul.appendChild(li4); + + var li2 = document.createElement("div"); + li2.setAttribute("class", "ebComponentList-item") + li2.onclick = function() { + return rightClickMenuEdit(parent, type, name, version); + }; + li2.innerHTML = "Edit " + type + " " + value + ""; + ul.appendChild(li2); + + var li3 = document.createElement("div"); + li3.setAttribute("class", "ebComponentList-item") + li3.onclick = function() { + return rightClickMenuDelete(parent, type, name, version); + }; + li3.innerHTML = "Delete " + type + " " + value + ""; + ul.appendChild(li3); + if (type.toUpperCase() == "KEYINFORMATION") { + li3.setAttribute("class", "ebComponentList-item ebComponentList-item_disabled"); + } + } + + // rclickdiv.setAttribute("class", "contextmenu_show"); ewatkmi: swapped + // with ebContextMenu + rclickdiv.setAttribute("class", + "ebContextMenu-body ebContextMenu-body_corner_default ebContextMenu-body_visible_true"); + rclickdiv.style.position = "absolute"; + rclickdiv.style.top = mouseY(event); + rclickdiv.style.left = mouseX(event); + + // prevent event bubbling up to parent elements for their on-click + event.stopPropagation(); + // prevent default context menu + event.returnValue = false; + event.preventDefault(); + return false; +} +function rightClickMenuCreate(parent, type) { + document.getElementById("rightClickMenu").className = "ebContextMenu-body_visible_false"; + if (type.toUpperCase() == "CONTEXTSCHEMA") { + editContextSchemaForm_createContextSchema(parent); + } else if (type.toUpperCase() == "EVENT") { + editEventForm_createEvent(parent); + } else if (type.toUpperCase() == "TASK") { + editTaskForm_createTask(parent); + } else if (type.toUpperCase() == "POLICY") { + editPolicyForm_createPolicy(parent); + } else if (type.toUpperCase() == "CONTEXTALBUM") { + editContextAlbumForm_createContextAlbum(parent); + } else { + alert("So you want to create a new " + type); + } +} +function rightClickMenuView(parent, type, value_name, value_version) { + document.getElementById("rightClickMenu").className = "ebContextMenu-body_visible_false"; + if (type.toUpperCase() == "CONTEXTSCHEMA") { + editContextSchemaForm_viewContextSchema(parent, value_name, value_version); + } else if (type.toUpperCase() == "EVENT") { + editEventForm_viewEvent(parent, value_name, value_version); + } else if (type.toUpperCase() == "TASK") { + editTaskForm_viewTask(parent, value_name, value_version); + } else if (type.toUpperCase() == "POLICY") { + editPolicyForm_viewPolicy(parent, value_name, value_version); + } else if (type.toUpperCase() == "CONTEXTALBUM") { + editContextAlbumForm_viewContextAlbum(parent, value_name, value_version); + } else { + alert("So you want to view " + type + " " + value_name + ":" + value_version); + } +} +function rightClickMenuEdit(parent, type, value_name, value_version) { + document.getElementById("rightClickMenu").className = "ebContextMenu-body_visible_false"; + if (type.toUpperCase() == "CONTEXTSCHEMA") { + editContextSchemaForm_editContextSchema(parent, value_name, value_version); + } else if (type.toUpperCase() == "EVENT") { + editEventForm_editEvent(parent, value_name, value_version); + } else if (type.toUpperCase() == "TASK") { + editTaskForm_editTask(parent, value_name, value_version); + } else if (type.toUpperCase() == "POLICY") { + editPolicyForm_editPolicy(parent, value_name, value_version); + } else if (type.toUpperCase() == "CONTEXTALBUM") { + editContextAlbumForm_editContextAlbum(parent, value_name, value_version); + } else { + alert("So you want to edit " + type + " " + value_name + ":" + value_version); + } +} +function rightClickMenuDelete(parent, type, value_name, value_version) { + document.getElementById("rightClickMenu").className = "ebContextMenu-body_visible_false"; + if (type.toUpperCase() == "CONTEXTSCHEMA") { + editContextSchemaForm_deleteContextSchema(parent, value_name, value_version); + } else if (type.toUpperCase() == "EVENT") { + editEventForm_deleteEvent(parent, value_name, value_version); + } else if (type.toUpperCase() == "TASK") { + editTaskForm_deleteTask(parent, value_name, value_version); + } else if (type.toUpperCase() == "POLICY") { + editPolicyForm_deletePolicy(parent, value_name, value_version); + } else if (type.toUpperCase() == "CONTEXTALBUM") { + editContextAlbumForm_deleteContextAlbum(parent, value_name, value_version); + } else { + alert("So you want to delete " + type + " " + value_name + ":" + value_version); + } +} +function mouseX(evt) { + if (evt.pageX) { + return evt.pageX; + } else if (evt.clientX) { + return evt.clientX + + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); + } else { + return null; + } +} +function mouseY(evt) { + if (evt.pageY) { + return evt.pageY; + } else if (evt.clientY) { + return evt.clientY + + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); + } else { + return null; + } +} + +export { + rightClickMenu_scopePreserver,rightClickMenu,rightClickMenuCreate,rightClickMenuView,rightClickMenuEdit,rightClickMenuDelete +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/dropdownList.js b/gui-editors/gui-editor-apex/src/main/webapp/js/dropdownList.js new file mode 100644 index 0000000..d18b38e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/dropdownList.js @@ -0,0 +1,213 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function dropdownList_option_select_scopePreserver(optionDiv, selectedOption, onselect) { + return function(event) { + dropdownList_option_select(optionDiv, selectedOption, onselect); + } +} +function dropdownList_filter_scopePreserver(optionDiv, optionUl) { + return function(event) { + dropdownList_filter(optionDiv, optionUl); + } +} +function dropdownList_option_select(divname, selectedOption, onselect) { + document.getElementById(divname + "_display").innerHTML = selectedOption.displaytext; + document.getElementById(divname)["selectedOption"] = selectedOption; + dropdownList_display_hide(divname); + if (onselect) { + onselect(selectedOption); + } +} +function dropdownList_display_click(divname, options, selected, disabled, getoptions) { + if (!document.getElementById(divname + "_options").classList.contains("dropdownList_show")) { + if (getoptions != null) { + var new_options = getoptions(); + dropdownList_ChangeOptions(document.getElementById(divname), new_options, selected, disabled, getoptions); + } + document.getElementById(divname + "_options").classList + .add("dropdownList_show", "dropdownList_display_clicked"); + } else { + document.getElementById(divname + "_options").classList.remove("dropdownList_show", + "dropdownList_display_clicked"); + } +} +function dropdownList_display_hide(optionDiv) { + document.getElementById(optionDiv + "_options").classList.remove("dropdownList_show"); +} +function dropdownList_filter(optionDiv, optionUl) { + var input, filter, ul; + input = document.getElementById(optionDiv + "_search"); + filter = input.value.toUpperCase(); + ul = document.getElementById(optionDiv + "_options_list_ul"); + var lis = ul.querySelectorAll("#" + ul.id + " > li"); // get li direct + // child elements + for (let value of lis) { + if (value.innerHTML.toUpperCase().indexOf(filter) > -1) { + value.style.display = ""; + } else { + value.style.display = "none"; + } + } +} + +/* + * Create a dropdown list, with a search function. + * + * Each dropdownList must have a unique "id_prefix" value as a unique identifier + * prefix "options" is an array of objects for options, where each object has a + * field called name. options[i].displaytext is a displayed text for the option + * "selected" is one of the options contained in list in the "options" + * parameter. "selected" must contain at least one field: selected.displaytext, + * where the value of selected.displaytext should be the same as + * options[i].displaytext for one of the values in options. "disabled" is a + * boolean, whether the drop down is enabled or disabled "onselect" is a + * function that is called when an option is selected, with a parameter that is + * the selected option from the passed "options" "getoptions" is a function that + * is called to dynamically retrieve options. It is called when the drop-down + * list is checked. If this is set the "options" parameter is ignored. + * + * Returns a DIV representing the dropdown list. The returned DIV will have a + * new field "selectedOption" containing one of the options in the "options" + * array, or null if no option is selected/ The returned DIV will have an id + * with value "id_prefix+'_dropdownList'", which should be unique. + */ +function dropdownList(id_prefix, options, selected, disabled, onselect, getoptions) { + var retdiv = document.createElement("div"); + var divname = id_prefix + "_dropdownList"; + retdiv.setAttribute("id", divname); + retdiv.setAttribute("class", "dropdownList"); + retdiv["_isDropDownList"] = true; + retdiv["_dropDownList_listener"] = onselect; + return dropdownList_ChangeOptions(retdiv, options, selected, disabled, getoptions); +} + +function dropdownList_ChangeOptions(dropdownListDIV, options, selected, disabled, getoptions) { + var retdiv = dropdownListDIV; + var divname = retdiv.getAttribute("id"); + if (!retdiv["_isDropDownList"]) { + console.error("Cannot provision dropdown list " + divname + " DIV because it is not a dropdown list"); + return null; + } + if (options == null && getoptions == null) { + console.error("Cannot provision dropdown list " + divname + + " DIV because it has no options and no function to get options"); + return null; + } + if (disabled && !selected) { + console.warn("Provisioning dropdown list " + divname + " that is disabled, but there is no value selected!") + } + var subdivs = retdiv.querySelectorAll("#" + divname + " > div, button"); // get + // direct + // children + // or + // retdiv + // that + // are + // divs + for (let value of subdivs) { + retdiv.removeChild(value); + } + var onselect = null; + if (retdiv["_dropDownList_listener"]) { + onselect = retdiv["_dropDownList_listener"]; + } + var display = document.createElement("div"); + retdiv.appendChild(display); + display.setAttribute("id", divname + "_display"); + retdiv["selectedOption"] = null; + + var button = document.createElement("button"); + button.setAttribute("class", "ebCombobox-helper"); + var iconHolder = document.createElement("span"); + iconHolder.setAttribute("class", "ebCombobox-iconHolder"); + var icon = document.createElement("i"); + var iconStyle = "ebIcon ebIcon_small ebIcon_downArrow_10px eb_noVertAlign"; + if (disabled) { + iconStyle += " ebIcon_disabled"; + } + icon.setAttribute("class", iconStyle); + iconHolder.appendChild(icon); + button.appendChild(iconHolder); + retdiv.appendChild(button); + + if (disabled) { + display.setAttribute("class", "dropdownList_display_disabled ebInput_width_xLong"); + } else { + display.setAttribute("class", "dropdownList_display ebInput_width_xLong"); + var onClickFunction = function(event) { + dropdownList_display_click(divname, options, selected, disabled, getoptions); + }; + display.onclick = onClickFunction; + button.onclick = onClickFunction; + } + var optionsDIV = document.createElement("div"); + retdiv.appendChild(optionsDIV); + optionsDIV.setAttribute("id", divname + "_options"); + optionsDIV.setAttribute("class", "dropdownList_options"); + var optionsSearch = document.createElement("input"); + optionsDIV.appendChild(optionsSearch); + optionsSearch.setAttribute("id", divname + "_search"); + optionsSearch.setAttribute("type", "input"); + optionsSearch.setAttribute("placeholder", "Search.."); + optionsSearch.setAttribute("class", "ebInput ebInput_width_full"); + optionsSearch.onkeyup = dropdownList_filter_scopePreserver(divname, divname + "_options_list"); + var optionsUL = document.createElement("ul"); + optionsUL.setAttribute("class", "dropdownList_options_body"); + optionsSearch.setAttribute("id", divname + "_search"); + optionsDIV.appendChild(optionsUL); + optionsUL.setAttribute("id", divname + "_options_list_ul"); + if (options) { + for (var i = 0; i < options.length; i++) { + var option = document.createElement("li"); + optionsUL.appendChild(option); + option.onclick = dropdownList_option_select_scopePreserver(divname, options[i], onselect); + option.innerHTML = options[i].displaytext; + if (selected && selected.displaytext && selected.displaytext == options[i].displaytext) { + retdiv["selectedOption"] = options[i]; + } + } + } else if (getoptions != null && selected != null) { + retdiv["selectedOption"] = selected; + } + + if (retdiv["selectedOption"] != null) { + display.innerHTML = retdiv["selectedOption"].displaytext; + display.title = display.innerHTML; + } else if (retdiv["selectedOption"] == null && !disabled) { + display.innerHTML = "Select an Option"; + } else if (retdiv["selectedOption"] == null && disabled) { + display.innerHTML = "No Option Selected"; + } + return retdiv; +} + +export { + dropdownList, + dropdownList_ChangeOptions, + dropdownList_display_click, + dropdownList_display_hide, + dropdownList_filter, + dropdownList_filter_scopePreserver, + dropdownList_option_select, + dropdownList_option_select_scopePreserver +} diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/fileMenu.js b/gui-editors/gui-editor-apex/src/main/webapp/js/fileMenu.js new file mode 100644 index 0000000..b917af1 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/fileMenu.js @@ -0,0 +1,146 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/*global define,jQuery,window */ + +(function(factory) { + + "use strict"; + + if (typeof (define) === 'function' && define.amd) { + define([ 'jquery' ], factory); + } else { + factory(jQuery); + } +}(function($) { + + "use strict"; + + $.fileMenu = function(el, options) { + + var base = this; + + base.$el = $(el); + base.el = el; + + base.options = $.extend({}, $.fileMenu.defaultOptions, options); + base.touch = false; + + base.$ = function(query) { + return base.$el.find(query); + }; + + base.hideMenu = function() { + base.$('.selected ul').slideUp(base.options.slideSpeed); + base.$('.selected').removeClass('selected'); + base.$el.removeClass('active'); + }; + + base.showMenu = function($this) { + var $parent = $this.parent(), $menu = $this.children('ul').first(), offsets = $this.offset(); + + $parent.addClass('active'); + + $this.addClass('selected'); + $menu.css({ + 'left' : offsets.left, + 'top' : offsets.top + $parent.height() + }); + $menu.slideDown(base.options.slideSpeed); + }; + + base.addListeners = function() { + base.$el.children('li').on('click', function(e) { + var $this = $(this); + + if ($this.hasClass('selected')) { + base.hideMenu(); + } else { + base.hideMenu(); + base.showMenu($this); + } + e.stopPropagation(); + }); + + base.$el.children('li').on('mouseenter', function() { + var $this = $(this); + if (!$this.parent().hasClass('active')) { + return; + } + if ($this.hasClass('selected')) { + return; + } + + base.hideMenu(); + base.showMenu($this); + }); + + /* Don't slide up if submenu, divider or disabled item is clicked */ + base.$('ul').on('click', function(e) { + var $this = $(e.target); + if ($this.get(0).tagName === 'LI' && !$this.hasClass('sub')) { + return; + } + e.stopPropagation(); + }); + + /* Handle toggle elements */ + base.$('ul').on('click', '.toggle', function(e) { + $(this).toggleClass('active'); + e.stopPropagation(); + }); + + /* Position sub menus */ + base.$el.on('mouseenter', 'ul li', function() { + var $this = $(this); + + $this.find('ul').first().css({ + 'left' : $this.parent().width(), + 'margin-top' : -$this.height() + }); + }); + + /* Hide menu on click outside the menu */ + $('html').on('click', function() { + base.hideMenu(); + }); + }; + + base.init = function() { + base.addListeners(); + base.$el.addClass('fileMenu'); + + }; + + base.init(); + }; + + $.fileMenu.defaultOptions = { + slideSpeed : 100 + }; + + $.fn.fileMenu = function(options) { + return this.each(function() { + new $.fileMenu(this, options); + }); + }; + +})); \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/showhideElement.js b/gui-editors/gui-editor-apex/src/main/webapp/js/showhideElement.js new file mode 100644 index 0000000..8d9afa8 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/showhideElement.js @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function showHideElement_display(showhide, element, _showstyle, _hidestyle, _buttonshowstyle, _buttonhidestyle) { + var checkbox = $(showhide).find('input:checkbox:first'); + if (checkbox) { + checkbox.change(function(event) { + $(element).toggle("fast"); + }); + } else { + if (_buttonshowstyle) { + showhide.classList.remove(_buttonshowstyle); + } + if (_buttonhidestyle) { + showhide.classList.add(_buttonhidestyle); + } + showhide.onclick = function(event) { + $(element).toggle("fast"); + }; + } +} + +function showHideElement(id_prefix, element, _initialhide, _showText, _hideText, _showstyle, _hidestyle, + _buttonshowstyle, _buttonhidestyle) { + var retdiv = document.createElement("div"); + var divname = id_prefix; + retdiv.setAttribute("id", divname); + retdiv.setAttribute("class", "showHideElement"); + var showhide = document.createElement("div"); + retdiv.appendChild(showhide); + showhide.setAttribute("id", divname + "_showhide"); + showhide.innerHTML = ''; + + retdiv.appendChild(element); + if (_initialhide != null && _initialhide === true) { + element.style.display = "none"; + } else { + element.style.display = "block"; + } + showHideElement_display(showhide, element, _showstyle, _hidestyle, undefined, undefined); + return retdiv; +} + +export { + showHideElement_display, + showHideElement +} + diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/showhideTextarea.js b/gui-editors/gui-editor-apex/src/main/webapp/js/showhideTextarea.js new file mode 100644 index 0000000..8c98d3f --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/showhideTextarea.js @@ -0,0 +1,133 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +function showHideTextarea_display_hide(showHideDivprefix) { + var ta = document.getElementById(showHideDivprefix + "_textarea"); + var sh = document.getElementById(showHideDivprefix + "_showhide"); + _showHideTextarea_display_hide(ta, sh) + if (sh["_clickable"]) { + sh.onclick = function(event) { + showHideTextarea_display_show(showHideDivprefix); + }; + } +} +function showHideTextarea_display_show(showHideDivprefix) { + var ta = document.getElementById(showHideDivprefix + "_textarea"); + var sh = document.getElementById(showHideDivprefix + "_showhide"); + _showHideTextarea_display_show(ta, sh) + if (sh["_clickable"]) { + sh.onclick = function(event) { + showHideTextarea_display_hide(showHideDivprefix); + }; + } +} + +function _showHideTextarea_display_hide(txtarea, showhide) { + txtarea.classList.remove("showHideTextarea_displayed"); + txtarea.classList.add("showHideTextarea_hidden"); + showhide.classList.remove("showHideTextarea_show"); + showhide.classList.add("showHideTextarea_hide"); + showhide.innerHTML = showhide["showText"]; +} +function _showHideTextarea_display_show(txtarea, showhide) { + txtarea.classList.add("showHideTextarea_displayed"); + txtarea.classList.remove("showHideTextarea_hidden"); + showhide.classList.add("showHideTextarea_show"); + showhide.classList.remove("showHideTextarea_hide"); + showhide.innerHTML = showhide["hideText"]; +} + +/* + * Create a hideable textarea, inside a div, with some text displayed in a + * clickable area to show the text area, and some other text displayed in the + * clickable area to hide the text area + * + * Each showHideTextarea must have a unique "id_prefix" vale as an identifier + * "content" is the text to be put into the text area "initialshow" is a + * boolean, if true the textarea will be shown initially, otherwise hidden + * "editable" is a boolean, if true the textarea will be editable, otherwise + * hidden "disabled" is a boolean, if true the textarea can be shown, otherwise + * it canot be shown "showText" is the text that is shown to be clicked to show + * the text area "hideText" is the text that is shown to be clicked to show the + * text area + * + * Returns a div representing the hideable textarea, with id 'id_prefix'. The + * returned div will a textarea called "id_prefix+'_textarea'", that can be + * queried to get the value of the textarea + */ + +function showHideTextarea(id_prefix, content, _initialshow, _editable, _disabled, _showText, _hideText) { + + var editable = (_editable != null ? _editable : true); + + var retdiv = document.createElement("div"); + var divname = id_prefix; + retdiv.setAttribute("id", divname); + retdiv.setAttribute("class", "showHideTextarea"); + var showhide = document.createElement("div"); + retdiv.appendChild(showhide); + showhide.setAttribute("id", divname + "_showhide"); + showhide.innerHTML = ''; + var parent = document.createElement("div"); + var textArea = document.createElement("textarea"); + parent.appendChild(textArea); + retdiv.appendChild(parent); + textArea.setAttribute("id", divname + "_textarea"); + textArea.setAttribute("name", divname + "_textarea"); + textArea.style.width = "100%"; + textArea.style.height = "400px"; + textArea.style.display = "none"; + if (content != null) { + textArea.value = content; + } + + if (!editable) { + textArea.readOnly = true; + textArea.style.cursor = "text"; + textArea.style["border-color"] = "#E3E3E3"; + textArea.style["background-color"] = "#F0F0F0"; + textArea.style.color = "#B2B2B2"; + } + + var shown = false; + var checkbox = $(showhide).find('input:checkbox:first'); + checkbox.change(function(event) { + if (!shown) { + createEditArea(textArea.getAttribute("id"), { + is_editable : editable + }); + shown = true; + } else { + $(parent).toggle("fast"); + } + }); + + return retdiv; +} + +export { + showHideTextarea, + showHideTextarea_display_hide, + showHideTextarea_display_show, + _showHideTextarea_display_hide, + _showHideTextarea_display_show +} -- cgit 1.2.3-korg