Merge changes from topic 'feature/new-csar-installer'
[clamp.git] / src / main / resources / META-INF / resources / designer / scripts / CldsModelService.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * 
22  */
23 app
24 .service(
25 'cldsModelService',
26 [
27     'alertService',
28     '$http',
29     '$q',
30     '$rootScope',
31     function(alertService, $http, $q, $rootScope) {
32
33             function checkIfElementType(name) {
34
35         //This will open the methods located in the app.js
36                           if (undefined == name) {
37                                   return;
38                           }else if (name.toLowerCase().indexOf("policy") >= 0){
39                                           PolicyWindow();
40                           } else {
41                                   $rootScope.selectedBoxName = name.toLowerCase();
42                                   ToscaModelWindow();
43                           }
44             }
45             function handleQueryToBackend(def, svcAction, svcUrl, svcPayload) {
46
47                     $http.put(svcUrl, svcPayload).success(
48                     function(data) {
49
50                             def.resolve(data);
51                             if (typeof data.statusCodeValue === 'undefined'
52                             || data.statusCodeValue === 200) {
53                                     alertService.alertMessage(
54                                     "Action Successful: " + svcAction, 1)
55                             } else {
56                                     if (typeof data.body !== 'undefined') {
57                                             alertService.alertMessage("Action Failure: "
58                                             + svcAction + ", " + data.body.errorMessageForUi, 2);
59                                     } else {
60                                             alertService.alertMessage("Action Failure: "
61                                             + svcAction, 2);
62                                     }
63                                     def.reject(svcAction + " not successful");
64                             }
65                     }).error(
66                     function(data) {
67
68                             def.resolve(data);
69                             if (typeof data.body !== 'undefined') {
70                                     alertService.alertMessage("Action Failure: " + svcAction
71                                     + ", " + data.body.errorMessageForUi, 2);
72                             } else {
73                                     alertService
74                                     .alertMessage("Action Failure: " + svcAction, 2);
75                             }
76                             def.reject(svcAction + " not successful");
77                     });
78             }
79             this.toggleDeploy = function(uiAction, modelName, controlNamePrefixIn,
80                                          bpmnTextIn, propTextIn, svgXmlIn,
81                                          templateName, typeID, controlNameUuid,
82                                          modelEventService, deploymentId) {
83
84                     var def = $q.defer();
85                     var sets = [];
86                     var action = uiAction.toLowerCase();
87                     var deployUrl = "/restservices/clds/v1/clds/" + action + "/"
88                     + modelName;
89                     var requestData = {
90                         name : modelName,
91                         controlNamePrefix : controlNamePrefixIn,
92                         bpmnText : bpmnTextIn,
93                         propText : propTextIn,
94                         imageText : svgXmlIn,
95                         templateName : templateName,
96                         typeId : typeID,
97                         controlNameUuid : controlNameUuid,
98                         event : modelEventService,
99                         deploymentId : deploymentId
100                     };
101                     handleQueryToBackend(def, action, deployUrl, requestData);
102                     return def.promise;
103             };
104             this.getModel = function(modelName) {
105                     var def = $q.defer();
106                     var sets = [];
107                     var svcUrl = "/restservices/clds/v2/loop/" + modelName;
108                     //var svcUrl = "/restservices/clds/v1/clds/model/" + modelName;
109                     $http.get(svcUrl).success(function(data) {
110                         //var clModel = '{"name": "ClosedLoopTest","lastComputedState":"DESIGN","svgRepresentation": "representation","globalPropertiesJson": [{"name":"service","value":["4cc5b45a-1f63-4194-8100-cd8e14248c92"]},{"name":"vf","value":["07e266fc-49ab-4cd7-8378-ca4676f1b9ec"]},{"name":"actionSet","value":["vnfRecipe"]},{"name":"location","value":["DC1"]},{"name":"deployParameters","value":{"location_id":"","service_id":"","policy_id":"AUTO_GENERATED_POLICY_ID_AT_SUBMIT"}}], "blueprint": "yaml","lastComputedState": "DESIGN","operationalPolicies": [ {"name": "OpPolicyTest", "configurationsJson": { "policy1": [{"name": "pname","value": "policy1"},{"name": "pid","value": "0"},{"name": "timeout","value": "345"},{"policyConfigurations": [[{"name": "recipe","value": ["restart"]},{"name": "maxRetries","value": ["3"]},{"name": "retryTimeLimit","value": ["180"]},{"name": "_id","value": ["6TtHGPq"]},{"name": "parentPolicy","value": [""]},{"name": "actor","value": ["APPC"]},{"name": "recipeInput","value": [""]},{"name": "recipeLevel","value": ["VM"]},{"name": "targetResourceId","value": ["07e266fc-49ab-4cd7-8378-ca4676f1b9ec"]},{"name": "targetResourceIdOther","value": [""]},{"name": "enableGuardPolicy","value": ["on"]},{"name": "guardPolicyType","value": ["GUARD_YAML"]},{"name": "guardTargets","value": [".*"]},{"name": "minGuard","value": ["1"]},{"name": "maxGuard","value": ["1"]},{"name": "limitGuard","value": ["1"]},{"name": "timeUnitsGuard","value": ["minute"]},{"name": "timeWindowGuard","value": ["10"]},{"name": "guardActiveStart","value": ["00:00:01-05:00"]},{"name": "guardActiveEnd","value": ["00:00:00-05:00"]}]]}]} }],"microServicePolicies": [{"name": "tca","properties": "", "shared": true,"policyTosca": "tosca","jsonRepresentation": {"schema":{"title":"DCAE TCA Config","type":"object","required":["name","eventName"],"properties":{"name":{"propertyOrder":101,"title":"Name","type":"string","default":"New_Set"},"eventName":{"propertyOrder":102,"title":"EventName","type":"string","enum":["event1","event2"]},"clSchemaType":{"propertyOrder":103,"title":"Control Loop Schema Type","type":"string","enum":["","type1","type2"]},"threshold":{"propertyOrder":104,"title":"Threshold","format":"tabs","type":"array","items":{"type":"object","title":"Threshold","required":["metric","operator"],"properties":{"metric":{"propertyOrder":1001,"title":"Metric","type":"string","enum":["metric1","metric2"]},"operator":{"propertyOrder":1003,"default":">","title":"Operator","type":"string","enum":[">","<","=","<=",">="]}, "clEventStatus":{"propertyOrder":1004,"title":"Closed Loop Event Status","type":"string","enum":["","ONSET","ABATED"]}}}}}}}}],"loopLogs": [{ } ] }';
111                         //cl_props = JSON.parse(clModel);
112                         cl_props = data;
113                             def.resolve(data);
114                     }).error(function(data) {
115
116                             def.reject("Open Model not successful");
117                     });
118                     return def.promise;
119             };
120             this.getSavedModel = function() {
121
122                     var def = $q.defer();
123                     var sets = [];
124                     //var svcUrl = "/restservices/clds/v1/clds/model-names";
125                     var svcUrl = "/restservices/clds/v2/loop/getAllNames";
126                     $http.get(svcUrl).success(function(data) {
127
128                             def.resolve(data);
129                     }).error(function(data) {
130
131                             def.reject("Open Model not successful");
132                     });
133                     return def.promise;
134             };
135             this.setModel = function(modelName, controlNamePrefixIn, bpmnTextIn,
136                                      propTextIn) {
137
138                     var def = $q.defer();
139                     var sets = [];
140                     var svcUrl = "/restservices/clds/v1/clds/model/" + modelName;
141                     var svcRequest = {
142                         name : modelName,
143                         controlNamePrefix : controlNamePrefixIn,
144                         bpmnText : bpmnTextIn,
145                         propText : propTextIn
146                     };
147                     $http.put(svcUrl, svcRequest).success(function(data) {
148
149                             def.resolve(data);
150                     }).error(function(data) {
151
152                             def.reject("Save Model not successful");
153                     });
154                     return def.promise;
155             };
156             this.processAction = function(uiAction, modelName, controlNamePrefixIn,
157                                           bpmnTextIn, propTextIn, svgXmlIn,
158                                           templateName, typeID, deploymentId) {
159
160                     var def = $q.defer();
161                     var sets = [];
162                     // console.log(svgXmlIn);
163                     var svcUrl = "/restservices/clds/v1/clds/";
164                     var svcAction = uiAction.toLowerCase();
165                     if (svcAction == "save" || svcAction == "refresh") {
166                             svcUrl = svcUrl + "model/" + modelName;
167                     } else if (svcAction == "test") {
168                             svcUrl = svcUrl + "action/submit/" + modelName + "?test=true";
169                     } else {
170                             svcUrl = svcUrl + "action/" + svcAction + "/" + modelName;
171                     }
172                     var svcRequest = {
173                         name : modelName,
174                         controlNamePrefix : controlNamePrefixIn,
175                         bpmnText : bpmnTextIn,
176                         propText : propTextIn,
177                         imageText : svgXmlIn,
178                         templateName : templateName,
179                         typeId : typeID,
180                         deploymentId : deploymentId
181                     };
182                     handleQueryToBackend(def, svcAction, svcUrl, svcRequest);
183                     return def.promise;
184             };
185             this.manageAction = function(modelName, typeId, typeName) {
186
187                     var def = $q.defer();
188                     var sets = [];
189                     var config = {
190                         url : "/restservices/clds/v1/clds/getDispatcherInfo",
191                         method : "GET",
192                         params : {
193                             model : modelName,
194                             typeId : typeId,
195                             typeName : typeName
196                         }
197                     };
198                     $http(config).success(function(data) {
199
200                             def.resolve(data);
201                     }).error(function(data) {
202
203                             def.reject("manage action not successful");
204                     });
205                     return def.promise;
206             };
207             this.processActionResponse = function(modelName) {
208
209                     // populate control name (prefix and uuid here)
210                     var headerText = "Closed Loop Modeler - " + modelName;
211                     setStatus();
212                     manageCLImage(modelName);
213                     enableDisableMenuOptions();
214             };
215             this.processRefresh = function(pars) {
216
217                     var newPars = pars;
218                     if (typeof pars.body !== 'undefined') {
219                             newPars = pars.body;
220                     }
221                     typeID = newPars.typeId;
222                     deploymentId = newPars.deploymentId;
223                     setStatus();
224                     enableDisableMenuOptions();
225             }
226             function setStatus() {
227
228                     var status = getStatus();
229                     // apply color to status
230                     var statusColor = 'white';
231                     if (status.trim() === "DESIGN") {
232                             statusColor = 'gray'
233                     } else if (status.trim() === "DISTRIBUTED") {
234                             statusColor = 'blue'
235                     } else if (status.trim() === "ACTIVE") {
236                             statusColor = 'green'
237                     } else if (status.trim() === "STOPPED") {
238                             statusColor = 'red'
239                     } else if (status.trim() === "DELETING") {
240                             statusColor = 'pink'
241                     } else if (status.trim() === "ERROR") {
242                             statusColor = 'orange'
243                     } else if (status.trim() === "UNKNOWN") {
244                             statusColor = 'blue'
245                     } else {
246                             statusColor = null;
247                     }
248                     var statusMsg = '<span style="background-color:'
249                     + statusColor
250                     + ';-moz-border-radius: 50px;  -webkit-border-radius: 50px;  border-radius: 50px;">&nbsp;&nbsp;&nbsp;'
251                     + status + '&nbsp;&nbsp;&nbsp;</span>';
252                     // display status
253                     if ($("#status_clds").length >= 1)
254                             $("#status_clds").remove();
255                     $("#activity_modeler")
256                     .append(
257                     '<span id="status_clds" style="position: absolute;  left: 61%;top: 151px; font-size:20px;">Status: '
258                     + statusMsg + '</span>');
259             }
260             function manageCLImage(modelName) {
261                 getModelImage(modelName).then(function(pars) {
262                         //var svg=' <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" color-interpolation="auto" color-rendering="auto" fill="black" fill-opacity="1" font-family="Dialog" font-size="12px" font-style="normal" font-weight="normal" image-rendering="auto" shape-rendering="auto" stroke="black" stroke-dasharray="none" stroke-dashoffset="0" stroke-linecap="square" stroke-linejoin="miter" stroke-miterlimit="10" stroke-opacity="1" stroke-width="1" text-rendering="auto"><!--Generated by the Batik Graphics2D SVG Generator--> <defs id="genericDefs"/> <g> <g stroke-width="2"> <circle cx="20" cy="21" fill="none" r="10"/> <line fill="none" x1="30" x2="91" y1="21" y2="21"/> <polygon fill="none" points=" 89 19 89 23 93 21"/> <polygon points=" 89 19 89 23 93 21" stroke="none"/>  <g class="djs-group" xmlns="http://www.w3.org/2000/svg"> <g class="djs-element djs-shape" data-element-id="VesCollector_1g9cmz0" transform="matrix(1,0,0,1,207,140)" style="display: block;"> <rect fill="none" class="djs-outline" x="-6" y="-6" width="132" height="92"></rect> <g > <rect x="0" y="0" width="120" height="80" rx="0" ry="0" style="stroke-width: 2;" stroke="#000000" fill="#ffffff"></rect> <polyline points="120,80 120,20 " style="stroke-width: 2;" fill="none" stroke="#000000"></polyline> <polyline points="20,0 20,80 " style="stroke-width: 2;" fill="none" stroke="#000000"></polyline> <text style="font-family: Arial,sans-serif; font-size: 12px;" class=" djs-label"> <tspan x="25.5" y="43.5">VesCollector</tspan> </text> </g>  <rect x="0" y="0" width="120" height="80" style="stroke-opacity: 0; stroke-width: 15;" fill="none" stroke="#ffffff" class="djs-hit"></rect> </g> </g>  <line fill="none" x1="105" x2="105" y1="1" y2="44"/> <line fill="none" x1="160" x2="221" y1="21" y2="21"/> <polygon fill="none" points=" 219 19 219 23 223 21"/> <polygon points=" 219 19 219 23 223 21" stroke="none"/>  <g class="djs-element djs-shape" data-element-id="tca"> <rect fill="none" class="djs-outline"  height="90" width="132" x="225"  y="1"/> <rect x="230" y="6" width="120" height="80" rx="0" ry="0" style="stroke-width: 2;" stroke="#000000" fill="#ffffff"></rect> <text font-family="sans-serif" stroke="none" x="228" xml:space="preserve" y="22"  >third_app</text> <line fill="none" x1="225" x2="290" y1="33" y2="33"/> <rect x="230" y="6" width="120" height="80"       style="stroke-opacity: 0; stroke-width: 15;" fill="none" stroke="#ffffff" class="djs-hit"></rect> </g>  <line fill="none" x1="290" x2="351" y1="21" y2="21"/> <polygon fill="none" points=" 349 19 349 23 353 21"/> <polygon points=" 349 19 349 23 353 21" stroke="none"/> <rect fill="none" height="43" id="first_app" width="65" x="355" y="1"/> <text font-family="sans-serif" stroke="none" x="360" xml:space="preserve" y="22" data-element-id="tca">first_app</text> <line fill="none" x1="355" x2="420" y1="33" y2="33"/> <line fill="none" x1="420" x2="481" y1="21" y2="21"/> <polygon fill="none" points=" 479 19 479 23 483 21"/> <polygon points=" 479 19 479 23 483 21" stroke="none"/> <rect fill="none" height="43" id="second_app" width="65" x="485" y="1"/> <text font-family="sans-serif" stroke="none" x="479" xml:space="preserve" y="22" data-element-id="tca">second_app</text> <line fill="none" x1="485" x2="550" y1="33" y2="33"/> <line fill="none" x1="550" x2="611" y1="21" y2="21"/> <polygon fill="none" points=" 609 19 609 23 613 21"/> <polygon points=" 609 19 609 23 613 21" stroke="none"/> <rect fill="none" height="43" id="policy" width="65" x="615" y="1"/> <text font-family="sans-serif" stroke="none" x="630" xml:space="preserve" y="22" data-element-id="policyc">Policy</text> <line fill="none" x1="615" x2="647" y1="22" y2="1"/> <line fill="none" x1="680" x2="741" y1="21" y2="21"/> <polygon fill="none" points=" 739 19 739 23 743 21"/> <polygon points=" 739 19 739 23 743 21" stroke="none"/> <circle cx="755" cy="21" fill="none" r="10" stroke-width="4"/> </g> </g> </svg>';
263                         var svg = pars;
264                             if ($("#svgContainer").length > 0)
265                                     $("#svgContainer").remove();
266                             $("#js-canvas").append(
267                             "<span id=\"svgContainer\">" + svg + "</span>");
268                             /* added code for height width viewBox */
269                             $("#svgContainer svg").removeAttr("height");
270                             $("#svgContainer svg").removeAttr('viewBox');
271                             $("#svgContainer svg").removeAttr('width');
272                             $("#svgContainer svg").attr('width', '100%');
273                             $("#svgContainer svg").attr('height', '100%');
274                             $("#svgContainer").click(
275                             function(event) {
276                                     console.log("svgContainer:" + $("#svgContainer svg"));
277                                     // console.log($(event.target).parent().html())
278                                     // console.log($($(event.target).parent()).attr("data-element-id"))
279                                     var name = $($(event.target).parent()).attr("data-element-id")
280                                     lastElementSelected = $($(event.target).parent()).attr(
281                                     "data-element-id")
282                                     checkIfElementType(name)
283                             });
284                         }, function(data) {
285                         });
286             }
287             enableDisableMenuOptions = function() {
288                     enableDefaultMenu();
289                     //var status = getStatus();
290                 //enableActionMenu(status);
291                 enableAllActionMenu();
292             }
293             getModelImage = function(modelName) {
294                     var def = $q.defer();
295                     var sets = [];
296                     var svcUrl = "/restservices/clds/v2/loop/svgRepresentation/" + modelName;
297                     $http.get(svcUrl).success(function(data) {
298                             def.resolve(data);
299                     }).error(function(data) {
300                             def.reject("Not able to get the model image");
301                     });
302                     return def.promise;
303             };
304     } ]);