Merge "JUnit additions for PAP-REST,REST,Utils"
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / DCAEMicroServicePolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
21     $("#dialog").hide();
22     
23     $scope.policyNavigator;
24     $scope.isCheck = false;
25     $scope.savebutton = true;
26     $scope.refreshCheck = false;
27     
28     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
29         $scope.temp.policy = {
30                         policyType : "Config",
31                         configPolicyType : "Micro Service"
32         }
33     };
34     
35     $scope.refresh = function(){
36         if($scope.refreshCheck){
37                 $scope.policyNavigator.refresh();
38         }
39         $scope.modal('createNewPolicy', true);
40         $scope.temp.policy = "";
41     };
42     
43     $scope.modal = function(id, hide) {
44         return $('#' + id).modal(hide ? 'hide' : 'show');
45     };
46     
47     $('#ttlDate').datepicker({
48         dateFormat: 'dd/mm/yy',
49         changeMonth: true,
50         changeYear: true,
51         onSelect: function(date) {
52                 angular.element($('#ttlDate')).triggerHandler('input');
53         }
54     });
55     
56         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
57                 if ($scope.temp.policy.configName == undefined){
58                         $scope.isCheck = false;
59                 }else{
60                         $scope.isCheck = true;
61                 }
62         }else {
63                 $scope.isCheck = false;
64         }
65                 
66         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
67                 var j = data;
68                 $scope.data = JSON.parse(j.data);
69                 console.log($scope.data);
70                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
71                 console.log($scope.onapNameDictionaryDatas);
72         }, function (error) {
73                 console.log("failed");
74         });
75
76         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
77                 var j = data;
78                 $scope.data = JSON.parse(j.data);
79                 console.log($scope.data);
80                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
81                 console.log($scope.priorityDatas);
82         }, function (error) {
83                 console.log("failed");
84         });
85
86         PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
87                 var j = data;
88                 $scope.data = JSON.parse(j.data);
89                 console.log($scope.data);
90                 $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
91                 console.log($scope.groupPolicyScopeListDatas);
92         }, function (error) {
93                 console.log("failed");
94         });
95
96         PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
97                 var j = data;
98                 $scope.data = JSON.parse(j.data);
99                 console.log($scope.data);
100                 $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceCongigNameDictionaryDatas);
101                 console.log($scope.microServiceCongigNameDictionaryDatas);
102         }, function (error) {
103                 console.log("failed");
104         });
105
106         PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
107                 var j = data;
108                 $scope.data = JSON.parse(j.data);
109                 console.log($scope.data);
110                 $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
111                 console.log($scope.microServiceLocationDictionaryDatas);
112         }, function (error) {
113                 console.log("failed");
114         });
115
116         PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
117                 var j = data;
118                 $scope.data = JSON.parse(j.data);
119                 console.log($scope.data);
120                 var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
121                 var unique = {};
122                 var uniqueList = [];
123                 for(var i = 0; i < inputModelList.length; i++){
124                         if(typeof unique[inputModelList[i]] == "undefined"){
125                                 unique[inputModelList[i]] = "";
126                                 uniqueList.push(inputModelList[i]);
127                         }
128                 }
129                 $scope.microServiceModelsDictionaryDatas = uniqueList;
130                 console.log($scope.microServiceModelsDictionaryDatas);
131         }, function (error) {
132                 console.log("failed");
133         });
134
135         PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
136                 var j = data;
137                 $scope.data = JSON.parse(j.data);
138                 console.log($scope.data);
139                 $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
140                 console.log($scope.dcaeUUIDDictionaryDatas);
141         }, function (error) {
142                 console.log("failed");
143         });
144
145         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
146                 var j = data;
147                 $scope.data = JSON.parse(j.data);
148                 console.log($scope.data);
149                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
150                 console.log($scope.riskTypeDictionaryDatas);
151         }, function (error) {
152                 console.log("failed");
153         });
154
155         PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
156                 var j = data;
157                 $scope.data = JSON.parse(j.data);
158                 console.log($scope.data);
159                 $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
160                 console.log($scope.microServiceAttributeDictionaryDatas);
161         }, function (error) {
162                 console.log("failed");
163         });
164             
165
166          $scope.choices = [];
167          $scope.attributeDatas = [{"attributes" : $scope.choices}];
168          $scope.isInitEditTemplate = true;  //just initially create the edit template, didn't click add button yet.
169          $scope.addNewChoice = function(value) {
170                  console.log(value);
171                  if(value != undefined){
172                         if (value.startsWith('div.')){
173                                 value = value.replace('div.','');
174                         }
175                         var parentElement = document.getElementById("div."+value);
176                         var div = document.getElementById(value+"@0");
177                         if(div != null){
178                                 var clone = div.cloneNode(true); 
179                                 var addElement = parentElement.childElementCount;
180                                 clone.id = ''+value+'@'+addElement;
181                                 clone.value = '';
182                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
183                                         if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){  // Only append child if its value found in ruleData or edit mode
184                                                 if($scope.temp.policy.ruleData[clone.id]){
185                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
186                                                 }
187                                                 clone.className += ' child_single'; //here cloned is single element
188                                                 document.getElementById("div."+value).appendChild(clone);
189                                                 plainAttributeKeys.push(''+value+'@'+addElement);
190                                         }
191                                 }else{ //not view or edit
192                                         clone.className += ' child_single'; //here cloned is single element
193                                         document.getElementById("div."+value).appendChild(clone);
194                                         plainAttributeKeys.push(''+value+'@'+addElement);
195                                 }
196                         }else{
197                                 div = document.getElementById("div."+value+"@0");
198                                 
199                                 div.className += ' children_group'; //here is div with a group of children.
200                                 
201                                 var childElement = parentElement.firstElementChild;
202                                 var countParent = parentElement.childElementCount;
203                                 var childElementString = childElement.innerHTML;
204                                 var find = value+"@0";
205                                 var re = new RegExp(find, 'g');
206                                 childElementString = childElementString.replace(re,value+'@' + countParent);
207                                 var clone = childElement.cloneNode(true);
208                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
209                             var childId = parentElement.childNodes[ii].id;
210                             if(ii = parentElement.childNodes.length){
211                                 var childnewId = childId.slice(0, -1);
212                                 var count = childId.slice(-1);
213                             }
214                         }
215                                 var countvalue = parseInt(count) + 1;
216                                 clone.id = childnewId+countvalue;
217                                 clone.value = '';
218                                 clone.innerHTML=childElementString;
219                                 document.getElementById("div."+value).appendChild(clone);
220                                 var selects = clone.getElementsByTagName("select");
221                                 var inputs = clone.getElementsByTagName("input");
222                                 var removeValues = [];
223                                 for(var i=0; i<inputs.length; i++){
224                                         if ($scope.temp.policy.ruleData!=undefined){
225                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
226                                                 if (checkValue!=undefined && checkValue != "undefined"){
227                                                         if($scope.temp.policy.ruleData != null){
228                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
229                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
230                                                                 plainAttributeKeys.push(inputs[i].id);
231                                                         }
232                                                 } else {
233 //                                                      removeValues.push(inputs[i].id);
234                                                         plainAttributeKeys.push(inputs[i].id);
235                                                 }
236                                         }else {
237                                                 plainAttributeKeys.push(inputs[i].id);
238                                         }
239                                 }
240                                 
241                                 for(var i=0; i<selects.length; i++){
242                                         if ($scope.temp.policy.ruleData!=undefined){
243                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
244                                                 if (checkValue!=undefined && checkValue!="undefined"){
245                                                         if($scope.temp.policy.ruleData != null){
246                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
247                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
248                                                                 plainAttributeKeys.push(selects[i].id);
249                                                         }
250                                                 } else {
251                                                         plainAttributeKeys.push(selects[i].id);
252                                                 }
253                                         }else {
254                                                 plainAttributeKeys.push(selects[i].id);
255                                         }
256                                 }
257                                 
258                                 for (var k=0; k<removeValues.length; k++){
259                                         var elem = document.getElementById(removeValues[k]);
260                                         elem.parentNode.removeChild(elem);
261                                 }
262                                 var ele = angular.element(document.getElementById("div."+value));
263                         $compile(ele.contents())($scope);
264                     $scope.$apply();
265                         }
266                  }
267          };
268          
269          $scope.removeChoice = function(value) {
270                  console.log(value);
271                  if(value != undefined){
272                          var c = document.getElementById("div."+value).childElementCount;
273                          
274                          if(c == 1){
275                                  Notification.error("The original one is not removable.");
276                                  return;
277                          }      
278                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
279                  }
280          };
281          
282          $scope.pullVersion = function(serviceName) {
283                  console.log(serviceName);
284                  if(serviceName != undefined){
285                          var uuu = "policyController/getModelServiceVersioneData.htm";
286                          var postData={policyData: serviceName};
287                          $.ajax({
288                                  type : 'POST',
289                                  url : uuu,
290                                  dataType: 'json',
291                                  contentType: 'application/json',
292                                  data: JSON.stringify(postData),
293                                  success : function(data){
294                                          $scope.$apply(function(){
295                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
296                                          });
297                                  },
298                                  error : function(data){
299                                          alert("Error While Retriving the Template Layout Pattren.");
300                                  }
301                          });             
302                  }
303          };
304     
305     var splitDash = '-';
306         var splitEqual = '=';
307         var splitComma = ',';
308         var splitcolon = ':';
309         var splitsemicolon = ";";
310         var splitEnum = "],";
311         var plainAttributeKeys = [];
312         var matching = [];
313         var enumKeyList = [];
314         var dictionaryList = [];
315         var dictionaryNameList = [];
316     $scope.addDataToFields = function(serviceName, version){
317         if(serviceName != null && version !=null){
318                 var service=serviceName+"-v"+version;
319                 var myNode = document.getElementById("DynamicTemplate");
320                 myNode.innerHTML = '';
321             var uuu = "policyController/getDCAEMSTemplateData.htm";
322             var postData={policyData: service};
323             $.ajax({
324                 type : 'POST',
325                 url : uuu,
326                 dataType: 'json',
327                 contentType: 'application/json',
328                 data: JSON.stringify(postData),
329                 success : function(data){
330                     $scope.$apply(function(){
331                         $scope.addNewChoice();
332                         var plainAttributeKeys = [];
333                         $scope.dcaeModelData = data[0].dcaeModelData;
334                         $scope.dcaeJsonDate = data[0].jsonValue;
335                         if(data[0].allManyTrueKeys){
336                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
337                         }
338                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
339                         var attributes = $scope.dcaeModelData.attributes;
340                         var refAttributes = $scope.dcaeModelData.ref_attributes;
341                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
342                         console.log("subAttributes: " + subAttributes); 
343                         console.log("refAttributes: " + refAttributes); 
344                         var enumAttributes = $scope.dcaeModelData.enumValues;
345                         var annotation = $scope.dcaeModelData.annotation;
346                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
347
348                         if (annotation == null || annotation.length<1){
349                                 $scope.isCheck = true;
350                         }else {
351                                 $scope.isCheck = false;
352                                 var annoationList = annotation.split(splitComma);
353                                 for (k = 0; k < annoationList.length; k++){
354                                         var splitAnnotation = annoationList[k].split(splitEqual);
355                                         if (splitAnnotation[1].includes("matching-true")){
356                                                 matching.push(splitAnnotation[0].trim());
357                                         }
358                                 }
359
360                         }
361
362                         if (dictionary!= null && dictionary.length>1){
363                                 for (m=0; m < dictionary.length; m += 1){
364                                         var keyCompare = dictionary[m].name;
365                                         var valueCompare = dictionary[m].value;
366                                         var valueModel = dictionary[m].modelName;
367                                         var conpairService = serviceName;
368                                         if (valueModel.includes('-v')){
369                                                 conpairService = service;
370                                         }
371                                         if(valueModel.localeCompare(conpairService) == 0){
372                                                 console.log(valueCompare);      
373                                                 dictionaryList.push(dictionary[m]);
374                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
375                                                         dictionaryNameList.push(dictionary[m].name)
376                                                 }
377                                         }
378                                 }
379                         }
380
381                                 $scope.temp.policy.ruleGridData = [];
382                                 
383                                 $scope.jsonLayout($scope.dcaeJsonDate);
384                                 
385                     });
386                     
387                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
388                         
389                         if($scope.temp.policy.editPolicy){
390                                 $scope.isInitEditTemplate = true;
391                         }
392                         
393                         var checkData = [];
394                         var data = [];
395                             // If ruleData contains extra elements created by clicked add button 
396                                 if($scope.temp.policy.ruleData != null){
397                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
398                                         propNames.forEach(function(name) {
399                                                 data.push(name);
400                                         });
401                                         
402                                         var extraElements = data;
403                                         
404                                         if(plainAttributeKeys != null){
405                                                 for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
406                                                         var newValue = plainAttributeKeys[b].split("*");
407                                                         for(a = 0; a < data.length; a++){
408                                                                 if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
409                                                                         extraElements.splice(a, 1);
410                                                                 }
411                                                         }
412                                         }
413                                         
414                                         //--- Populate these extra elements created by clicked add button 
415                                         for(a = 0; a < extraElements.length; a++){                              
416                                                 if(extraElements[a].includes("@")){
417                                                         var index = extraElements[a].lastIndexOf("@");
418                                                         if(index > 0){
419                                                             // Get the number after @
420                                                             var n = getNumOfDigits(extraElements[a], index+1);
421                                                                                 
422                                                                 var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
423                                                                 console.log("key: " + key);
424                                                                 checkData.push(key);
425                                                         }
426                                                 }
427                                         }
428                                         var unique = checkData.filter(onlyUnique);
429                                         for(i =0; i < unique.length; i++){
430                                                 //remove @x and let addNewChoice add @1 or @2...
431                                                 //var newKey = unique[i].substring(0, unique[i].length-2);
432                                                 var index = unique[i].lastIndexOf("@");
433                                                 var newKey = unique[i].substring(0, index);
434                                                 console.log("newKey: " + newKey);       
435                                                 $scope.addNewChoice(newKey);
436                                         }
437                                 }
438                             }
439                         //After initially create the edit template, reset it to false.
440                             $scope.isInitEditTemplate = false;
441                             if($scope.temp.policy.editPolicy){
442                                 //reset it to false since the template has been created
443                                 $scope.temp.policy.editPolicy = false;
444                                 //clean all the events of addNewChoice
445                                 $scope.$on('$destroy', addNewChoice);
446                             }
447                             
448                     }
449                     var ele = angular.element(document.getElementById("DynamicTemplate"));
450                         $compile(ele.contents())($scope);
451                     $scope.$apply();
452                 },
453                 error : function(data){
454                     alert("Error While Retriving the Template Layout Pattren.");
455                 }
456             });
457         }
458     };
459     
460     function getNumOfDigits(str_value, index){
461                 // Get the number after @
462                 var str = str_value.substring(index, str_value.length); 
463                 var c = '';
464                 var n = 0;
465                 for (var x = 0; x < str.length; x++){                                                                   
466                     c = str.charAt(x);
467                             if(!isNaN(c)){ 
468                 n++;                                                     
469                     }else{
470                 break;
471             }
472                 }
473                 return n;
474     }
475     
476     function getDictionary(attribute){
477         var dicName = attribute;
478         if(attribute){
479            if(attribute.includes(":")){
480                    dicName = attribute.split(":")[0];
481            }
482         }
483             var dictionaryRegExp = new RegExp(dicName);
484             listemunerateValues = [];
485             if (dictionaryRegExp.test(dictionaryNameList)) {
486                         for (p=0; p < dictionaryList.length; p += 1) {
487                                 if (dicName == dictionaryList[p].name) {
488                                         listemunerateValues.push(dictionaryList[p].value);
489                                 }
490                         }
491             }
492             return listemunerateValues;
493     }
494     
495     function getList(attribute) {
496                 var enumName = attribute;
497                 console.log("In getList: attribute => " + attribute);
498                 if(attribute){
499                    if(attribute.includes(":")){
500                            enumName = attribute.split(":")[0];
501                    }
502                 }   
503             var baseEnum = $scope.dcaeModelData.enumValues;
504             var enumList = [];
505             if(baseEnum != null){
506                 enumList = baseEnum.split(splitEnum);
507             }
508                 var enumAttributes;
509                 var patternTest = new RegExp(enumName);
510                 for (k=0; k < enumList.length; k += 1){
511                         if(patternTest.test(enumList[k]) == true){
512                                 enumAttributes = enumList[k].trim();
513                 }
514         }
515
516          if(enumAttributes){
517                 enumAttributes = enumAttributes.replace("[", "");
518                 enumAttributes = enumAttributes.replace("]", "");
519                 enumAttributes = enumAttributes.replace(/ /g, '');
520                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
521                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
522                         //enumKeyList.push(attribute); 
523                 return listemunerateValues;
524          }
525          
526             return [];
527             }
528             
529             function getBooleanList(){
530                 var booleanList = [];
531                 booleanList.push(true);
532                 booleanList.push(false);
533                 return booleanList;
534             }
535             
536
537             function isArray(arrayTest) {
538                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
539             }
540             var lableList = [];
541                 function deconstructJSON(dataTest, level , name) {
542                         var array = false;
543                         var label = level;
544                          var stringValue = "java.lang.String";
545                          var string = "string";
546                          var intValue = "int";
547                          var integerValue = "integer";
548                          var double = "double";
549                          var boolean = "boolean";
550                          var baseLevel = level;
551                          
552                         if (name.length > 1){
553                                 label = label + name + '.';
554                         }
555                         
556                     for (key in dataTest) {
557                         array = isArray(dataTest[key]);
558                         console.log(key , dataTest[key]);
559                 
560                         if (!!dataTest[key] && typeof(dataTest[key])=="object") {
561                                 if (array==false && key!=="0"){
562                                         $scope.labelLayout(label, key, array );                         
563                                 }
564                                 
565                                 if (array == true && key!=0){
566                                         lableList.push(key);
567                                 }
568                                 
569                                 if (lableList.length > 0){
570                                         array = true;
571                                 }
572                                 if ( key==="0"){
573                                         var newKey = lableList.pop();
574                                         $scope.labelLayout(baseLevel, newKey, array );
575                                         if (array){
576                                                 label = baseLevel + newKey + '@0.';
577                                         } else {
578                                                 label = baseLevel + newKey + '.';
579                                         }
580                                 }
581                                 deconstructJSON(dataTest[key] , label, key);
582                         } else {
583                                 var attirbuteLabel = label;
584                                 var defaultValue='';
585                                 var isRequired = false;
586                                 if (dataTest[key].includes('defaultValue-')){
587                                         defaultValue = dataTest[key].split('defaultValue-')[1];
588                                 }
589
590                                 if (key==="0"){
591                                         array = true;
592                                         attributekey = lableList.pop();
593                                         attirbuteLabel = baseLevel;
594                                 } else {
595                                         attributekey = key.split();
596                                 }
597                                 
598                                 if (dataTest[key].includes('required-true')){
599                                         isRequired = true;
600                                 }
601                                 
602                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
603                                 
604                                 if(subAttributes){                                      
605                                         var jsonObject = JSON.parse(subAttributes);                                     
606                                         var allkeys = Object.keys(jsonObject);
607                                         if(allkeys){
608                                                 for (var k = 0; k < allkeys.length; k++) {
609                                                         var keyValue = allkeys[k];
610                                                         console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
611                                                         if(jsonObject[keyValue]){
612                                                                 var tempObject = jsonObject[keyValue];
613                                                                 if(tempObject && tempObject[key]){
614                                                                 if (tempObject[key].includes('required-true')){
615                                                                         isRequired = true;
616                                                                 }       
617                                                                 }
618                                                         }
619                                                 }                                               
620                                         }                                       
621                                 }
622                                 
623                                 switch (dataTest[key].split(splitcolon)[0]){
624                                         case stringValue:
625                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
626                                                 break;
627                                         case string:
628                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
629                                                 break;                                          
630                                         case intValue: 
631                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
632                                                 break;
633                                         case integerValue: 
634                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
635                                                 break;                                          
636                                         case double:
637                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
638                                                 break;
639                                         case boolean:
640                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], getBooleanList());
641                                                 break;
642                                         default:
643                                                 if (dataTest[key].includes('dictionary-')){
644                                                         var list = getDictionary(dataTest[key].split('dictionary-')[1]);
645                                                 }else{
646                                                         //--- get dropdown values from enumValues
647                                                         var list = getList(dataTest[key]);
648                                                 }
649                                                 if (list.length===0){ //not dropdown element
650                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
651                                                 }else{
652                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], list, isRequired);
653                                                 }
654                                                 break;
655                                 }
656                         }
657                     }
658                 }  
659
660             $scope.jsonLayout = function(dataTest){
661                 deconstructJSON(dataTest , "", "");
662             }
663             
664             
665             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
666                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
667                 var br = document.createElement("BR");
668                 
669                 var label = document.createElement("Label");
670                 var labeltext = null;
671                 var requiredLabName = "";
672                 if (matching.includes(attibuteKey)){
673                         labeltext = document.createTextNode(attibuteKey + "*!");        
674                         isRequired = true;  //set required as true for matching element
675                 }else {
676                         if(isRequired){
677                                 requiredLabName = attibuteKey + " *";
678                                 labeltext = document.createTextNode(requiredLabName);
679                         }else{
680                             labeltext = document.createTextNode(attibuteKey);   
681                         }
682                 }
683
684                 
685                 var divID = labelValue;
686                 
687                 if (labelValue.length  < 1){
688                         divID = "DynamicTemplate";
689                 }else if (labelValue.endsWith('.')){
690                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
691                 }
692                 
693                 label.appendChild(labeltext);
694                 
695                 var textField = document.createElement("INPUT");
696                 
697                 textField.setAttribute("class" , "form-control");
698                 if(dataType){
699                            if(dataType == "double"){
700                                    textField.setAttribute("type" , "number");
701                                    textField.setAttribute("step" , "any");
702                            }else{
703                               textField.setAttribute("type" , dataType);
704                            }
705                 }
706                 textField.setAttribute("style" , "width:300px;");
707                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
708                 var checkKey;
709                 if(attributeManyKey){
710                         checkKey = labelValue + attibuteKey+'@0';
711                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
712                         var divTag = document.createElement("div");
713                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
714                         var addButton = document.createElement("BUTTON");
715                         var buttonaddLabel = document.createTextNode("+");       
716                         addButton.appendChild(buttonaddLabel); 
717                         addButton.setAttribute("id", labelValue + attibuteKey);
718                         addButton.setAttribute("class", "btn btn-add-remove");
719                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
720                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
721                         var removeButton = document.createElement("BUTTON");
722                         var buttonremoveLabel = document.createTextNode("-");       
723                         removeButton.appendChild(buttonremoveLabel); 
724                         removeButton.setAttribute("class", "btn btn-add-remove");
725                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
726                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
727                         document.getElementById(divID).appendChild(addButton); 
728                         document.getElementById(divID).appendChild(removeButton); 
729                         document.getElementById(divID).appendChild(label); 
730                         var id = "div."+labelValue+attibuteKey;
731                         var divTag = document.createElement("div");
732                         divTag.setAttribute("id", id); 
733                         document.getElementById(divID).appendChild(divTag);
734                         textField.className += ' first_child';  
735                         if(isRequired){
736                                 textField.setAttribute("required", "true");
737                         }                       
738                         divTag.appendChild(textField);                  
739                         document.getElementById(divID).appendChild(divTag); 
740                         
741                 }else{
742                         checkKey = labelValue + attibuteKey;
743                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
744                         if(requiredLabName.includes("*")){
745                                 textField.setAttribute("required", "true");
746                         }
747                         document.getElementById(divID).appendChild(label);  
748                         document.getElementById(divID).appendChild(textField);  
749                         document.getElementById(divID).appendChild(br); 
750
751                 }
752                 
753                 if(divID.includes("@0") && divID.includes("div.")){
754                         var firstChild_Id = divID.split("@0")[0];
755                         var firstChild_element = document.getElementById(firstChild_Id);
756                         if(firstChild_element){
757                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
758                         }
759                 }
760                 console.log('firstChild_Id: ' + firstChild_Id);
761                 console.log('divID: ' + divID);
762                 
763                 if (defaultValue.length > 0){   
764                         if(defaultValue.includes(":")){
765                                 defaultValue = defaultValue.split(":")[0];
766                                 if(defaultValue === "NA") {
767                                         defaultValue = "";
768                                 }                               
769                         }
770                         if(defaultValue != "undefined" && defaultValue != undefined){
771                         document.getElementById(checkKey).value = defaultValue;
772                         }
773                 }
774                 
775                 if($scope.temp.policy.ruleData != null){
776                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
777                         if (attributeManyKey){
778                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
779                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
780                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
781                                 }
782                         }else{
783                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
784                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
785                                 }
786                         }
787                 } 
788                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
789     };
790   
791     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
792                 var label = document.createElement("Label")
793                 var divID = labelValue;
794                 if (labelValue.endsWith('.')){
795                         var workingLabel = labelValue.substring(0, labelValue.length-1);
796                 }else {
797                         var workingLabel = labelValue;
798                 }
799                 
800                 if (labelValue.length  < 1){
801                         divID = "DynamicTemplate";
802                 } else if (labelValue.endsWith('.')){
803                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
804                 }
805                 
806                 var labeltext = document.createTextNode(lableName);
807         
808                 label.appendChild(labeltext);
809                 
810                 var subAttributes = $scope.dcaeModelData.sub_attributes;
811
812                 if(labelManyKey){
813                         var addButton = document.createElement("BUTTON");
814                         var buttonLabel = document.createTextNode("+");       
815                         addButton.appendChild(buttonLabel); 
816                         addButton.setAttribute("class", "btn btn-add-remove");
817                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
818                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
819                         var removeButton = document.createElement("BUTTON");
820                         var buttonremoveLabel = document.createTextNode("-");       
821                         removeButton.appendChild(buttonremoveLabel); 
822                         removeButton.setAttribute("class", "btn btn-add-remove");
823                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
824                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
825                         document.getElementById(divID).appendChild(addButton); 
826                         document.getElementById(divID).appendChild(removeButton);
827                         document.getElementById(divID).appendChild(label);
828                         var id = "div."+labelValue+lableName;
829                         var divTag = document.createElement("div");
830                         divTag.setAttribute("id", id); 
831                         document.getElementById(divID).appendChild(divTag);
832                         
833                         var divTag = document.createElement("div");
834                         divTag.setAttribute("id", id +'@0');  
835                         
836                         divTag.className += ' children_group'; //here is div with a group of children.
837                         
838                         document.getElementById(id).appendChild(divTag);
839                 }else{
840                         var divTag = document.createElement("div");
841                         divTag.setAttribute("id", "div."+labelValue+lableName);
842                         divTag.className += ' children_group'; //here is div with a group of children.
843                         document.getElementById(divID).appendChild(label);  
844                         document.getElementById(divID).appendChild(divTag);                     
845                 }
846     };
847
848     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
849                 var br = document.createElement("BR");
850
851                 if (labelLevel.length  < 1){
852                         var divID = "DynamicTemplate";
853                 } else if (labelLevel.endsWith('.')){
854                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
855                 }       
856
857
858         var label = document.createElement("Label")
859         
860         var refAttributes = $scope.dcaeModelData.ref_attributes;
861         if(isRequired != true && refAttributes){ //check refAttributes also             
862                         var refAttributesList = refAttributes.split(splitComma);
863                         for (k = 0; k < refAttributesList.length; k++){
864                         var refAttribute = refAttributesList[k].split(splitEqual);                      
865                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
866                                 isRequired = true;
867                         }
868                         }
869         }
870         
871         if (matching.includes(attributeName)){
872                 var labeltext = document.createTextNode(attributeName + "*!");
873                 label.appendChild(labeltext);
874                 isRequired = true;  //set required as true for matching element
875         }else {
876                 var labeltext = document.createTextNode(attributeName);         
877                 if(isRequired){
878                         requiredLabName = attributeName+ " *";
879                         labeltext = document.createTextNode(requiredLabName);
880                 }else{
881                     labeltext = document.createTextNode(attributeName); 
882                 }
883         
884             label.appendChild(labeltext);               
885         }
886         label.appendChild(labeltext);
887
888         var listField = document.createElement("SELECT");
889         listField.setAttribute("class" , "form-control");
890         listField.setAttribute("style" , "width:300px;");
891         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
892         
893         if(isRequired){
894            listField.setAttribute("required", true);
895         }
896         if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
897                 var optionFirst = document.createElement('option');
898                 optionFirst.setAttribute('value', "");
899                 listField.appendChild(optionFirst);     
900         }
901         
902         for (i=0; i < listemunerateValues.length; i += 1) {
903                 
904                 if(listemunerateValues[i].includes("equal-sign")){
905                         listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
906                 }               
907                 
908             option = document.createElement('option');
909             option.setAttribute('value', listemunerateValues[i]);
910             option.appendChild(document.createTextNode(listemunerateValues[i]));
911             option.setAttribute('value', listemunerateValues[i]);
912             listField.appendChild(option);
913         }
914         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
915         
916         enumKeyList.push(attributeName);
917         
918         document.getElementById(divID).appendChild(label);  
919         document.getElementById(divID).appendChild(br); 
920                         
921         if(many == true){
922                 document.getElementById(divID).appendChild(listField).multiple = true;
923                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
924         }else {
925                 document.getElementById(divID).appendChild(listField).multiple = false;
926                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
927         }
928
929         if($scope.temp.policy.ruleData != null){
930                 if (many == true){
931                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
932                         for (i=0; i < listemunerateValues.length; i += 1) {
933                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
934                                 if (testValue === undefined){
935                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
936                                         }
937                                 var location = listemunerateValues.indexOf(testValue);
938                                 if (location!=-1){
939                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
940                                         }
941                                 }                       
942                         }else {
943                                     if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
944                             document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];        
945                                     }
946                         }
947                 }
948     };
949     
950     function onlyUnique(value, index, self) { 
951         return self.indexOf(value) === index;
952     };
953     
954     
955     function checkDictionary(value){
956         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
957                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
958                         return true;
959                 }
960         }
961         
962     }
963     $scope.savePolicy = function(policy){
964         if(policy.itemContent != undefined){
965                 $scope.refreshCheck = true; 
966                 $scope.policyNavigator = policy.itemContent;
967                 policy.itemContent = "";
968         }
969         $scope.savebutton = false;
970         var splitAt = '*';
971         var dot ='.';
972         var jsonPolicy = {};
973         if(plainAttributeKeys != null){
974                 for(a = 0; a < plainAttributeKeys.length; a++){
975                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
976                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
977                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
978                         var key = splitPlainAttributeKey[0];
979                 if(searchElement == null){
980                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
981                     key = splitPlainAttributeKey[0]+'@0';
982                 }else if (searchElement.nodeName == 'BUTTON'){
983                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
984                                 key = splitPlainAttributeKey[0]+'@0';
985                         }
986                         if(searchElement != null){
987                                 var keySplit = key.split(dot);
988                                 var elumentLocation = keySplit.length;
989                                 var enumKey = key;
990                                 if (elumentLocation > 1){
991                                         enumKey = keySplit[keySplit.length - 1];
992                                 }
993                                 //check it is undefined or not
994                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
995                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
996                                                         var multiSlect = [];
997                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
998                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
999                                                                 }
1000                                                         jsonPolicy[key]= multiSlect;
1001                                                 }else{
1002                                                         console.log(" searchElement.value = > " + searchElement.value);
1003                                                         jsonPolicy[key]= searchElement.value;
1004                                                 }
1005                                 } else {
1006                                         if(searchElement.value != null){
1007                                                         console.log(" searchElement.value = > " + searchElement.value);
1008                                                 jsonPolicy[key]= searchElement.value;
1009                                         }
1010                                 }
1011                         }
1012                 }
1013         }
1014         var uuu = "policycreation/save_policy";
1015         var postData={policyData: policy, policyJSON : jsonPolicy};
1016         $.ajax({
1017             type : 'POST',
1018             url : uuu,
1019             dataType: 'json',
1020             contentType: 'application/json',
1021             data: JSON.stringify(postData),
1022             success : function(data){
1023                 $scope.$apply(function(){
1024                         $scope.data=data.policyData;
1025                         if($scope.data == 'success'){
1026                                 $scope.temp.policy.readOnly = 'true';
1027                                 $scope.safetyChecker = data.policyData.split("#")[2];
1028                                 if ($scope.safetyChecker!=undefined) {
1029                                         Notification.success($scope.safetyChecker);
1030                                 }
1031                                 $scope.pushStatus=data.policyData.split("&")[1];
1032                                 if($scope.pushStatus=="successPush"){
1033                                         Notification.success("Policy pushed successfully");
1034                                 }
1035                                 Notification.success("Policy Saved Successfully.");     
1036                         }else if ($scope.data == 'PolicyExists'){
1037                                                 $scope.savebutton = true;
1038                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1039                                         }
1040                 });
1041                 console.log($scope.data);
1042             },
1043             error : function(data){
1044                 Notification.error("Error Occured while saving Policy.");
1045             }
1046         });
1047     };
1048     
1049     $scope.validatePolicy = function(policy){
1050         document.getElementById("validate").innerHTML = "";
1051         var splitAt = '*';
1052         var dot ='.';
1053         var jsonPolicy = {};
1054         if(plainAttributeKeys != null){
1055                 for(a = 0; a < plainAttributeKeys.length; a++){
1056                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1057                         console.log(splitPlainAttributeKey[1]); 
1058                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1059                         var key = splitPlainAttributeKey[0];
1060                         if(searchElement == null){
1061                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1062                                 key = splitPlainAttributeKey[0]+'@0';
1063                         }else if (searchElement.nodeName == 'BUTTON'){
1064                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1065                                 key = splitPlainAttributeKey[0]+'@0';
1066                         }
1067                         if(searchElement != null){
1068                                 if (enumKeyList.indexOf(key) != -1){
1069                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1070                                                         var multiSlect = [];
1071                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1072                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1073                                                                 }
1074                                                         jsonPolicy[key]= multiSlect;
1075                                                 }else{
1076                                                         jsonPolicy[key]= searchElement.value;
1077                                                 }
1078                                         if(searchElement.getAttribute("required")){
1079                                                 if(!searchElement.value){
1080                                                         return;
1081                                                 }
1082                                         } 
1083                                 } else {
1084                                         if(searchElement.value != null){
1085                                                 jsonPolicy[key]= searchElement.value;
1086                                                 if(searchElement.getAttribute("required")){
1087                                                         if(!searchElement.value){
1088                                                                 return;
1089                                                         }
1090                                                 }                                               
1091                                         }
1092                                 }
1093                         }
1094                 }
1095         }
1096         var uuu = "policyController/validate_policy.htm";
1097
1098         console.log("$scope.isCheck:" + $scope.isCheck);
1099         
1100         if($scope.isCheck == true){
1101                 if(("configName" in policy) == false){
1102                                 Notification.error("Validation Failed: configName is required");
1103                                 $scope.savebutton = true;
1104                                 return;
1105                 }
1106                 if(("location" in policy) == false){
1107                                 Notification.error("Validation Failed: location is required");
1108                                 $scope.savebutton = true;
1109                                 return;
1110                 }
1111                 if(("uuid" in policy) == false){
1112                                 Notification.error("Validation Failed: uuid is required");
1113                                 $scope.savebutton = true;
1114                                 return;
1115                 }
1116                 if(("policyScope" in policy) == false){
1117                                 Notification.error("Validation Failed: policyScope is required");
1118                                 $scope.savebutton = true;
1119                                 return;
1120                 }
1121         }        
1122         
1123         var postData={policyData: policy, policyJSON : jsonPolicy};
1124                 $.ajax({
1125                         type : 'POST',
1126                         url : uuu,
1127                         dataType: 'json',
1128                         contentType: 'application/json',
1129                         data: JSON.stringify(postData),
1130                         success : function(data){
1131                                 $scope.$apply(function(){
1132                                         $scope.validateData = data.data.replace(/\"/g, "");
1133                                         $scope.data=data.data.substring(1,8);
1134                                                 var size = data.data.length;
1135                                                 if($scope.data == 'success'){
1136                                                         Notification.success("Validation Success.");
1137                                                         $scope.savebutton = false;
1138                                                         if (size > 18){
1139                                                                 var displayWarning = data.data.substring(19,size  - 1);
1140                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1141                                                                 document.getElementById("validate").style.color = "white";
1142                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1143                                                         }
1144                                                 }else{
1145                                                         Notification.error("Validation Failed.");
1146                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1147                                                         document.getElementById("validate").style.color = "white";
1148                                                         document.getElementById("validate").style.backgroundColor = "red";
1149                                                         $scope.savebutton = true;
1150                                                 }
1151                                                 
1152                                 });
1153                                 console.log($scope.data);       
1154                         },
1155                         error : function(data){
1156                                 Notification.error("Validation Failed.");
1157                                 $scope.savebutton = true;
1158                         }
1159                 });
1160     };
1161
1162     function extend(obj, src) {
1163         for (var key in src) {
1164             if (src.hasOwnProperty(key)) obj[key] = src[key];
1165         }
1166         return obj;
1167     }
1168 }]);