Merge "Updated guard policy documentation"
[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 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          
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 + 1;
180                                 clone.id = ''+value+'@'+addElement;
181                                 clone.value = '';
182                                 clone.className += ' child_single'; //here cloned is single element
183                                 document.getElementById("div."+value).appendChild(clone);
184                                 plainAttributeKeys.push(''+value+'@'+addElement);
185                         }else{
186                                 div = document.getElementById("div."+value+"@0");
187                                 
188                                 div.className += ' children_group'; //here is div with a group of children.
189                                 
190                                 var childElement = parentElement.firstElementChild;
191                                 var countParent = parentElement.childElementCount;
192                                 var childElementString = childElement.innerHTML;
193                                 var find = value+"@0";
194                                 var re = new RegExp(find, 'g');
195                                 childElementString = childElementString.replace(re,value+'@' + countParent);
196                                 var clone = childElement.cloneNode(true);
197                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
198                             var childId = parentElement.childNodes[ii].id;
199                             if(ii = parentElement.childNodes.length){
200                                 var childnewId = childId.slice(0, -1);
201                                 var count = childId.slice(-1);
202                             }
203                         }
204                                 var countvalue = parseInt(count) + 1;
205                                 clone.id = childnewId+countvalue;
206                                 clone.value = '';
207                                 clone.innerHTML=childElementString;
208                                 document.getElementById("div."+value).appendChild(clone);
209                                 var selects = clone.getElementsByTagName("select");
210                                 var inputs = clone.getElementsByTagName("input");
211                                 var removeValues = [];
212                                 for(var i=0; i<inputs.length; i++){
213                                         if ($scope.temp.policy.ruleData!=undefined){
214                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
215                                                 if (checkValue!=undefined){
216                                                         if($scope.temp.policy.ruleData != null){
217                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
218                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
219                                                                 plainAttributeKeys.push(inputs[i].id);
220                                                         }
221                                                 } else {
222                                                         plainAttributeKeys.push(inputs[i].id);
223                                                 }
224                                         }else {
225                                                 plainAttributeKeys.push(inputs[i].id);
226                                         }
227                                 }
228                                 
229                                 for(var i=0; i<selects.length; i++){
230                                         if ($scope.temp.policy.ruleData!=undefined){
231                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
232                                                 if (checkValue!=undefined){
233                                                         if($scope.temp.policy.ruleData != null){
234                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
235                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
236                                                                 plainAttributeKeys.push(selects[i].id);
237                                                         }
238                                                 } else {
239                                                         plainAttributeKeys.push(selects[i].id);
240                                                 }
241                                         }else {
242                                                 plainAttributeKeys.push(selects[i].id);
243                                         }
244                                 }
245                                 
246                                 for (var k=0; k<removeValues.length; k++){
247                                         var elem = document.getElementById(removeValues[k]);
248                                         elem.parentNode.removeChild(elem);
249                                 }
250                                 var ele = angular.element(document.getElementById("div."+value));
251                         $compile(ele.contents())($scope);
252                     $scope.$apply();
253                         }
254                  }
255          };
256          
257          $scope.removeChoice = function(value) {
258                  console.log(value);
259                  if(value != undefined){
260                          var c = document.getElementById("div."+value).childElementCount;
261                          
262                          if(c == 1){
263                                  Notification.error("The original one is not removable.");
264                                  return;
265                          }      
266                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
267                  }
268          };
269          
270          $scope.pullVersion = function(serviceName) {
271                  console.log(serviceName);
272                  if(serviceName != undefined){
273                          var uuu = "policyController/getModelServiceVersioneData.htm";
274                          var postData={policyData: serviceName};
275                          $.ajax({
276                                  type : 'POST',
277                                  url : uuu,
278                                  dataType: 'json',
279                                  contentType: 'application/json',
280                                  data: JSON.stringify(postData),
281                                  success : function(data){
282                                          $scope.$apply(function(){
283                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
284                                          });
285                                  },
286                                  error : function(data){
287                                          alert("Error While Retriving the Template Layout Pattren.");
288                                  }
289                          });             
290                  }
291          };
292     
293     var splitDash = '-';
294         var splitEqual = '=';
295         var splitComma = ',';
296         var splitcolon = ':';
297         var splitsemicolon = ";";
298         var splitEnum = "],";
299         var plainAttributeKeys = [];
300         var matching = [];
301         var enumKeyList = [];
302         var dictionaryList = [];
303         var dictionaryNameList = [];
304     $scope.addDataToFields = function(serviceName, version){
305         if(serviceName != null && version !=null){
306                 var service=serviceName+"-v"+version;
307                 var myNode = document.getElementById("DynamicTemplate");
308                 myNode.innerHTML = '';
309             var uuu = "policyController/getDCAEMSTemplateData.htm";
310             var postData={policyData: service};
311             $.ajax({
312                 type : 'POST',
313                 url : uuu,
314                 dataType: 'json',
315                 contentType: 'application/json',
316                 data: JSON.stringify(postData),
317                 success : function(data){
318                     $scope.$apply(function(){
319                         $scope.addNewChoice();
320                         var plainAttributeKeys = [];
321                         $scope.dcaeModelData = data[0].dcaeModelData;
322                         $scope.dcaeJsonDate = data[0].jsonValue;
323                         $scope.allManyTrueKeys =  data[0].allManyTrueKeys;
324                         console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
325                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
326                         var attributes = $scope.dcaeModelData.attributes;
327                         var refAttributes = $scope.dcaeModelData.ref_attributes;
328                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
329                         console.log("subAttributes: " + subAttributes); 
330                         console.log("refAttributes: " + refAttributes); 
331                         var enumAttributes = $scope.dcaeModelData.enumValues;
332                         var annotation = $scope.dcaeModelData.annotation;
333                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
334
335                         if (annotation == null || annotation.length<1){
336                                 $scope.isCheck = true;
337                         }else {
338                                 $scope.isCheck = false;
339                                 var annoationList = annotation.split(splitComma);
340                                 for (k = 0; k < annoationList.length; k++){
341                                         var splitAnnotation = annoationList[k].split(splitEqual);
342                                         if (splitAnnotation[1].includes("matching-true")){
343                                                 matching.push(splitAnnotation[0].trim());
344                                         }
345                                 }
346
347                         }
348
349                         if (dictionary!= null && dictionary.length>1){
350                                 for (m=0; m < dictionary.length; m += 1){
351                                         var keyCompare = dictionary[m].name;
352                                         var valueCompare = dictionary[m].value;
353                                         var valueModel = dictionary[m].modelName;
354                                         var conpairService = serviceName;
355                                         if (valueModel.includes('-v')){
356                                                 conpairService = service;
357                                         }
358                                         if(valueModel.localeCompare(conpairService) == 0){
359                                                 console.log(valueCompare);      
360                                                 dictionaryList.push(dictionary[m]);
361                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
362                                                         dictionaryNameList.push(dictionary[m].name)
363                                                 }
364                                         }
365                                 }
366                         }
367
368                                 $scope.temp.policy.ruleGridData = [];
369                                 
370                                 $scope.jsonLayout($scope.dcaeJsonDate);
371                                 
372                     });
373                     
374                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
375                         var checkData = [];
376                         var data = [];
377                                 if($scope.temp.policy.ruleData != null){
378                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
379                                         propNames.forEach(function(name) {
380                                                 data.push(name);
381                                         });
382                                         
383                                         var extraElements = data;
384                                         
385                                         if(plainAttributeKeys != null){
386                                                 for(b = 0; b < plainAttributeKeys.length; b++){ // remove already populated elements from extraElements array
387                                                         var newValue = plainAttributeKeys[b].split("*");
388                                                         for(a = 0; a < data.length; a++){
389                                                                 if(data[a] === newValue[0]){
390                                                                         extraElements.splice(a, 1);
391                                                                 }
392                                                         }
393                                         }
394                                         
395                                         //--- populate these extral elements generated from clicking add button
396                                         for(a = 0; a < extraElements.length; a++){                              
397                                                 if(extraElements[a].includes("@")){
398                                                                 var n = extraElements[a].lastIndexOf("@");
399                                                                 var key = extraElements[a].substring(0, n+2); //include @x in key also by n+2 since x can be  1, or 2, or 3
400                                                             checkData.push(key);
401                                                 }
402                                         }
403                                         var unique = checkData.filter(onlyUnique);
404                                         for(i =0; i < unique.length; i++){
405                                                 //remove @x and let addNewChoice add @1 or @2...
406                                                 var newKey = unique[i].substring(0, unique[i].length-2);
407                                                 $scope.addNewChoice(newKey);
408                                         }
409                                 }
410                             }
411
412                     }
413                     var ele = angular.element(document.getElementById("DynamicTemplate"));
414                         $compile(ele.contents())($scope);
415                     $scope.$apply();
416                 },
417                 error : function(data){
418                     alert("Error While Retriving the Template Layout Pattren.");
419                 }
420             });
421         }
422     };
423     
424     function getDictionary(attribute){
425         var dicName = attribute;
426         if(attribute){
427            if(attribute.includes(":")){
428                    dicName = attribute.split(":")[0];
429            }
430         }
431             var dictionaryRegExp = new RegExp(dicName);
432             listemunerateValues = [];
433             if (dictionaryRegExp.test(dictionaryNameList)) {
434                         for (p=0; p < dictionaryList.length; p += 1) {
435                                 if (dicName == dictionaryList[p].name) {
436                                         listemunerateValues.push(dictionaryList[p].value);
437                                 }
438                         }
439             }
440             return listemunerateValues;
441     }
442     
443     function getList(attribute) {
444                 var enumName = attribute;
445                 console.log("In getList: attribute => " + attribute);
446                 if(attribute){
447                    if(attribute.includes(":")){
448                            enumName = attribute.split(":")[0];
449                    }
450                 }   
451             var baseEnum = $scope.dcaeModelData.enumValues;
452             var enumList = [];
453             if(baseEnum != null){
454                 enumList = baseEnum.split(splitEnum);
455             }
456                 var enumAttributes;
457                 var patternTest = new RegExp(enumName);
458                 for (k=0; k < enumList.length; k += 1){
459                         if(patternTest.test(enumList[k]) == true){
460                                 enumAttributes = enumList[k].trim();
461                 }
462         }
463
464          if(enumAttributes){
465                 enumAttributes = enumAttributes.replace("[", "");
466                 enumAttributes = enumAttributes.replace("]", "");
467                 enumAttributes = enumAttributes.replace(/ /g, '');
468                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
469                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
470                         //enumKeyList.push(attribute); 
471                 return listemunerateValues;
472          }
473          
474             return [];
475             }
476             
477             function getBooleanList(){
478                 var booleanList = [];
479                 booleanList.push(true);
480                 booleanList.push(false);
481                 return booleanList;
482             }
483             
484
485             function isArray(arrayTest) {
486                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
487             }
488             var lableList = [];
489                 function deconstructJSON(dataTest, level , name) {
490                         var array = false;
491                         var label = level;
492                          var stringValue = "java.lang.String";
493                          var string = "string";
494                          var intValue = "int";
495                          var integerValue = "integer";
496                          var double = "double";
497                          var boolean = "boolean";
498                          var baseLevel = level;
499                          
500                         if (name.length > 1){
501                                 label = label + name + '.';
502                         }
503                         
504                     for (key in dataTest) {
505                         array = isArray(dataTest[key]);
506                         console.log(key , dataTest[key]);
507                 
508                         if (!!dataTest[key] && typeof(dataTest[key])=="object") {
509                                 if (array==false && key!=="0"){
510                                         $scope.labelLayout(label, key, array );                         
511                                 }
512                                 
513                                 if (array == true && key!=0){
514                                         lableList.push(key);
515                                 }
516                                 
517                                 if (lableList.length > 0){
518                                         array = true;
519                                 }
520                                 if ( key=="0"){
521                                         var newKey = lableList.pop();
522                                         $scope.labelLayout(baseLevel, newKey, array );
523                                         if (array){
524                                                 label = baseLevel + newKey + '@0.';
525                                         } else {
526                                                 label = baseLevel + newKey + '.';
527                                         }
528                                 }
529                                 deconstructJSON(dataTest[key] , label, key);
530                         } else {
531                                 var attirbuteLabel = label;
532                                 var defaultValue='';
533                                 var isRequired = false;
534                                 if (dataTest[key].includes('defaultValue-')){
535                                         defaultValue = dataTest[key].split('defaultValue-')[1];
536                                 }
537
538                                 if (key==="0"){
539                                         array = true;
540                                         attributekey = lableList.pop();
541                                         attirbuteLabel = baseLevel;
542                                 } else {
543                                         attributekey = key.split();
544                                 }
545                                 
546                                 if (dataTest[key].includes('required-true')){
547                                         isRequired = true;
548                                 }
549                                 
550                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
551                                 
552                                 if(subAttributes){                                      
553                                         var jsonObject = JSON.parse(subAttributes);                                     
554                                         var allkeys = Object.keys(jsonObject);
555                                         if(allkeys){
556                                                 for (var k = 0; k < allkeys.length; k++) {
557                                                         var keyValue = allkeys[k];
558                                                         console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
559                                                         if(jsonObject[keyValue]){
560                                                                 var tempObject = jsonObject[keyValue];
561                                                                 if(tempObject && tempObject[key]){
562                                                                 if (tempObject[key].includes('required-true')){
563                                                                         isRequired = true;
564                                                                 }       
565                                                                 }
566                                                         }
567                                                 }                                               
568                                         }                                       
569                                 }
570                                 
571                                 switch (dataTest[key].split(splitcolon)[0]){
572                                         case stringValue:
573                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
574                                                 break;
575                                         case string:
576                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
577                                                 break;                                          
578                                         case intValue: 
579                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
580                                                 break;
581                                         case integerValue: 
582                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
583                                                 break;                                          
584                                         case double:
585                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
586                                                 break;
587                                         case boolean:
588                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], getBooleanList());
589                                                 break;
590                                         default:
591                                                 if (dataTest[key].includes('dictionary-')){
592                                                         var list = getDictionary(dataTest[key].split('dictionary-')[1]);
593                                                 }else{
594                                                         //--- get dropdown values from enumValues
595                                                         var list = getList(dataTest[key]);
596                                                 }
597                                                 if (list.length===0){ //not dropdown element
598                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
599                                                 }else{
600                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, dataTest[key], list);
601                                                 }
602                                                 break;
603                                 }
604                         }
605                     }
606                 }  
607
608             $scope.jsonLayout = function(dataTest){
609                 deconstructJSON(dataTest , "", "");
610             }
611             
612             
613             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
614                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
615                 var br = document.createElement("BR");
616                 
617                 var label = document.createElement("Label");
618                 var labeltext = null;
619                 var requiredLabName = "";
620                 if (matching.includes(attibuteKey)){
621                         labeltext = document.createTextNode(attibuteKey + "*!");                
622                 }else {
623                         //var labeltext = document.createTextNode(refattributeLabel);
624                         if(isRequired){
625                                 requiredLabName = attibuteKey + " *";
626                                 labeltext = document.createTextNode(requiredLabName);
627                         }else{
628                             labeltext = document.createTextNode(attibuteKey);   
629                         }
630                 }
631
632                 
633                 var divID = labelValue;
634                 
635                 if (labelValue.length  < 1){
636                         divID = "DynamicTemplate";
637                 }else if (labelValue.endsWith('.')){
638                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
639                 }
640                 
641                 label.appendChild(labeltext);
642                 
643                 var textField = document.createElement("INPUT");
644                 
645                 textField.setAttribute("class" , "form-control");
646                 if(dataType){
647                            if(dataType == "double"){
648                                    textField.setAttribute("type" , "number");
649                                    textField.setAttribute("step" , "any");
650                            }else{
651                               textField.setAttribute("type" , dataType);
652                            }
653                 }
654                 textField.setAttribute("style" , "width:300px;");
655                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
656                 var checkKey;
657                 if(attributeManyKey){
658                         checkKey = labelValue + attibuteKey+'@0';
659                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
660                         var divTag = document.createElement("div");
661                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
662                         var addButton = document.createElement("BUTTON");
663                         var buttonaddLabel = document.createTextNode("+");       
664                         addButton.appendChild(buttonaddLabel); 
665                         addButton.setAttribute("id", labelValue + attibuteKey);
666                         addButton.setAttribute("class", "btn btn-add-remove");
667                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
668                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
669                         var removeButton = document.createElement("BUTTON");
670                         var buttonremoveLabel = document.createTextNode("-");       
671                         removeButton.appendChild(buttonremoveLabel); 
672                         removeButton.setAttribute("class", "btn btn-add-remove");
673                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
674                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
675                         document.getElementById(divID).appendChild(addButton); 
676                         document.getElementById(divID).appendChild(removeButton); 
677                         document.getElementById(divID).appendChild(label); 
678                         var id = "div."+labelValue+attibuteKey;
679                         var divTag = document.createElement("div");
680                         divTag.setAttribute("id", id); 
681                         document.getElementById(divID).appendChild(divTag);
682                         textField.className += ' first_child';                  
683                         divTag.appendChild(textField);                  
684                         document.getElementById(divID).appendChild(divTag); 
685                         
686                 }else{
687                         checkKey = labelValue + attibuteKey;
688                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
689                         if(requiredLabName.includes("*")){
690                                 textField.setAttribute("required", "true");
691                         }
692                         document.getElementById(divID).appendChild(label);  
693                         document.getElementById(divID).appendChild(textField);  
694                         document.getElementById(divID).appendChild(br); 
695
696                 }
697                 
698                 if(divID.includes("@0") && divID.includes("div.")){
699                         var firstChild_Id = divID.split("@0")[0];
700                         var firstChild_element = document.getElementById(firstChild_Id);
701                         if(firstChild_element){
702                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
703                         }
704                 }
705                 console.log('firstChild_Id: ' + firstChild_Id);
706                 console.log('divID: ' + divID);
707                 
708                 if (defaultValue.length > 0){   
709                         if(defaultValue.includes(":")){
710                                 defaultValue = defaultValue.split(":")[0];
711                                 if(defaultValue === "NA") {
712                                         defaultValue = "";
713                                 }                               
714                         }
715                         document.getElementById(checkKey).value = defaultValue;
716                 }
717                 
718                 if($scope.temp.policy.ruleData != null){
719                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
720                         if (attributeManyKey){
721                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
722                                 document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
723                                 var i =1 ;
724                                 while(true){
725                                         var newValue = $scope.temp.policy.ruleData[newCheckKey+'@'+i];
726                                         if(newValue==null){
727                                                 break;
728                                         }else{
729                                                 $scope.addNewChoice(newCheckKey);
730                                                 document.getElementById(newCheckKey+'@'+i).value = newValue;
731                                                 i = i+1;
732                                         }
733                                 }               
734                 
735                         }else{
736                                 document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
737                         }
738                 } 
739                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
740     };
741   
742     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
743                 var label = document.createElement("Label")
744                 var divID = labelValue;
745                 if (labelValue.endsWith('.')){
746                         var workingLabel = labelValue.substring(0, labelValue.length-1);
747                 }else {
748                         var workingLabel = labelValue;
749                 }
750                 
751                 if (labelValue.length  < 1){
752                         divID = "DynamicTemplate";
753                 } else if (labelValue.endsWith('.')){
754                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
755                 }
756                 
757                 var labeltext = document.createTextNode(lableName);
758         
759                 label.appendChild(labeltext);
760                 
761                 var subAttributes = $scope.dcaeModelData.sub_attributes;
762
763                 if(labelManyKey){
764                         var addButton = document.createElement("BUTTON");
765                         var buttonLabel = document.createTextNode("+");       
766                         addButton.appendChild(buttonLabel); 
767                         addButton.setAttribute("class", "btn btn-add-remove");
768                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
769                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
770                         var removeButton = document.createElement("BUTTON");
771                         var buttonremoveLabel = document.createTextNode("-");       
772                         removeButton.appendChild(buttonremoveLabel); 
773                         removeButton.setAttribute("class", "btn btn-add-remove");
774                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
775                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
776                         document.getElementById(divID).appendChild(addButton); 
777                         document.getElementById(divID).appendChild(removeButton);
778                         document.getElementById(divID).appendChild(label);
779                         var id = "div."+labelValue+lableName;
780                         var divTag = document.createElement("div");
781                         divTag.setAttribute("id", id); 
782                         document.getElementById(divID).appendChild(divTag);
783                         
784                         var divTag = document.createElement("div");
785                         divTag.setAttribute("id", id +'@0');  
786                         
787                         divTag.className += ' children_group'; //here is div with a group of children.
788                         
789                         document.getElementById(id).appendChild(divTag);
790                 }else{
791                         var divTag = document.createElement("div");
792                         divTag.setAttribute("id", "div."+labelValue+lableName);
793                         divTag.className += ' children_group'; //here is div with a group of children.
794                         document.getElementById(divID).appendChild(label);  
795                         document.getElementById(divID).appendChild(divTag);                     
796                 }
797     };
798
799     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
800                 var br = document.createElement("BR");
801
802                 if (labelLevel.length  < 1){
803                         var divID = "DynamicTemplate";
804                 } else if (labelLevel.endsWith('.')){
805                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
806                 }       
807
808
809         var label = document.createElement("Label")
810         if (matching.includes(attributeName)){
811                 var labeltext = document.createTextNode(attributeName + "*!");
812                 label.appendChild(labeltext);
813         }else {
814                 var labeltext = document.createTextNode(attributeName);
815                 var isRequired = false;
816                 var refAttributes = $scope.dcaeModelData.ref_attributes;
817                 if(refAttributes){              
818                 var refAttributesList = refAttributes.split(splitComma);
819                 for (k = 0; k < refAttributesList.length; k++){
820                         var refAttribute = refAttributesList[k].split(splitEqual);
821                         
822                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
823                                 isRequired = true;
824                         }
825                 }                               
826                 }
827                 
828                 if(isRequired){
829                         requiredLabName = attributeName+ " *";
830                         labeltext = document.createTextNode(requiredLabName);
831                 }else{
832                     labeltext = document.createTextNode(attributeName); 
833                 }
834         
835             label.appendChild(labeltext);               
836         }
837         label.appendChild(labeltext);
838
839         var listField = document.createElement("SELECT");
840         listField.setAttribute("class" , "form-control");
841         listField.setAttribute("style" , "width:300px;");
842         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
843         
844         if(isRequired){
845            listField.setAttribute("required", true);
846         }
847         var optionFirst = document.createElement('option');
848         optionFirst.setAttribute('value', "");
849         listField.appendChild(optionFirst);     
850         
851         for (i=0; i < listemunerateValues.length; i += 1) {
852             option = document.createElement('option');
853             option.setAttribute('value', listemunerateValues[i]);
854             option.appendChild(document.createTextNode(listemunerateValues[i]));
855             option.setAttribute('value', listemunerateValues[i]);
856             listField.appendChild(option);
857         }
858         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
859         
860         enumKeyList.push(attributeName);
861         
862         document.getElementById(divID).appendChild(label);  
863         document.getElementById(divID).appendChild(br); 
864                         
865         if(many == true){
866                 document.getElementById(divID).appendChild(listField).multiple = true;
867                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
868         }else {
869                 document.getElementById(divID).appendChild(listField).multiple = false;
870                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
871         }
872
873         if($scope.temp.policy.ruleData != null){
874                 if (many == true){
875                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
876                         for (i=0; i < listemunerateValues.length; i += 1) {
877                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
878                                 if (testValue === undefined){
879                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
880                                         }
881                                 var location = listemunerateValues.indexOf(testValue);
882                                 if (location!=-1){
883                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
884                                         }
885                                 }                       
886                         }else {
887                         document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];    
888                                 
889                         }
890                 }
891     };
892     
893     function onlyUnique(value, index, self) { 
894         return self.indexOf(value) === index;
895     };
896     
897     
898     function checkDictionary(value){
899         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
900                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
901                         return true;
902                 }
903         }
904         
905     }
906     $scope.savePolicy = function(policy){
907         if(policy.itemContent != undefined){
908                 $scope.refreshCheck = true; 
909                 $scope.policyNavigator = policy.itemContent;
910                 policy.itemContent = "";
911         }
912         $scope.savebutton = false;
913         var splitAt = '*';
914         var dot ='.';
915         var jsonPolicy = {};
916         if(plainAttributeKeys != null){
917                 for(a = 0; a < plainAttributeKeys.length; a++){
918                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
919                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
920                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
921                         var key = splitPlainAttributeKey[0];
922                 if(searchElement == null){
923                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
924                     key = splitPlainAttributeKey[0]+'@0';
925                 }else if (searchElement.nodeName == 'BUTTON'){
926                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
927                                 key = splitPlainAttributeKey[0]+'@0';
928                         }
929                         if(searchElement != null){
930                                 var keySplit = key.split(dot);
931                                 var elumentLocation = keySplit.length;
932                                 var enumKey = key;
933                                 if (elumentLocation > 1){
934                                         enumKey = keySplit[keySplit.length - 1];
935                                 }
936                                 //check it is undefined or not
937                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
938                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
939                                                         var multiSlect = [];
940                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
941                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
942                                                                 }
943                                                         jsonPolicy[key]= multiSlect;
944                                                 }else{
945                                                         console.log(" searchElement.value = > " + searchElement.value);
946                                                         jsonPolicy[key]= searchElement.value;
947                                                 }
948                                 } else {
949                                         if(searchElement.value != null){
950                                                         console.log(" searchElement.value = > " + searchElement.value);
951                                                 jsonPolicy[key]= searchElement.value;
952                                         }
953                                 }
954                         }
955                 }
956         }
957         var uuu = "policycreation/save_policy";
958         var postData={policyData: policy, policyJSON : jsonPolicy};
959         $.ajax({
960             type : 'POST',
961             url : uuu,
962             dataType: 'json',
963             contentType: 'application/json',
964             data: JSON.stringify(postData),
965             success : function(data){
966                 $scope.$apply(function(){
967                         $scope.data=data.policyData;
968                         if($scope.data == 'success'){
969                                 $scope.temp.policy.readOnly = 'true';
970                                 $scope.safetyChecker = data.policyData.split("#")[2];
971                                 if ($scope.safetyChecker!=undefined) {
972                                         Notification.success($scope.safetyChecker);
973                                 }
974                                 $scope.pushStatus=data.policyData.split("&")[1];
975                                 if($scope.pushStatus=="successPush"){
976                                         Notification.success("Policy pushed successfully");
977                                 }
978                                 Notification.success("Policy Saved Successfully.");     
979                         }else if ($scope.data == 'PolicyExists'){
980                                                 $scope.savebutton = true;
981                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
982                                         }
983                 });
984                 console.log($scope.data);
985             },
986             error : function(data){
987                 Notification.error("Error Occured while saving Policy.");
988             }
989         });
990     };
991     
992     $scope.validatePolicy = function(policy){
993         document.getElementById("validate").innerHTML = "";
994         var splitAt = '*';
995         var dot ='.';
996         var jsonPolicy = {};
997         if(plainAttributeKeys != null){
998                 for(a = 0; a < plainAttributeKeys.length; a++){
999                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1000                         console.log(splitPlainAttributeKey[1]); 
1001                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1002                         var key = splitPlainAttributeKey[0];
1003                         if(searchElement == null){
1004                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1005                                 key = splitPlainAttributeKey[0]+'@0';
1006                         }else if (searchElement.nodeName == 'BUTTON'){
1007                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1008                                 key = splitPlainAttributeKey[0]+'@0';
1009                         }
1010                         if(searchElement != null){
1011                                 if (enumKeyList.indexOf(key) != -1){
1012                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1013                                                         var multiSlect = [];
1014                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1015                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1016                                                                 }
1017                                                         jsonPolicy[key]= multiSlect;
1018                                                 }else{
1019                                                         jsonPolicy[key]= searchElement.value;
1020                                                 }
1021                                         if(searchElement.getAttribute("required")){
1022                                                 if(!searchElement.value){
1023                                                         return;
1024                                                 }
1025                                         } 
1026                                 } else {
1027                                         if(searchElement.value != null){
1028                                                 jsonPolicy[key]= searchElement.value;
1029                                                 if(searchElement.getAttribute("required")){
1030                                                         if(!searchElement.value){
1031                                                                 return;
1032                                                         }
1033                                                 }                                               
1034                                         }
1035                                 }
1036                         }
1037                 }
1038         }
1039         var uuu = "policyController/validate_policy.htm";
1040
1041         console.log("$scope.isCheck:" + $scope.isCheck);
1042         
1043         if($scope.isCheck == true){
1044                 if(("configName" in policy) == false){
1045                                 Notification.error("Validation Failed: configName is required");
1046                                 $scope.savebutton = true;
1047                                 return;
1048                 }
1049                 if(("location" in policy) == false){
1050                                 Notification.error("Validation Failed: location is required");
1051                                 $scope.savebutton = true;
1052                                 return;
1053                 }
1054                 if(("uuid" in policy) == false){
1055                                 Notification.error("Validation Failed: uuid is required");
1056                                 $scope.savebutton = true;
1057                                 return;
1058                 }
1059                 if(("policyScope" in policy) == false){
1060                                 Notification.error("Validation Failed: policyScope is required");
1061                                 $scope.savebutton = true;
1062                                 return;
1063                 }
1064         }        
1065         
1066         var postData={policyData: policy, policyJSON : jsonPolicy};
1067                 $.ajax({
1068                         type : 'POST',
1069                         url : uuu,
1070                         dataType: 'json',
1071                         contentType: 'application/json',
1072                         data: JSON.stringify(postData),
1073                         success : function(data){
1074                                 $scope.$apply(function(){
1075                                         $scope.validateData = data.data.replace(/\"/g, "");
1076                                         $scope.data=data.data.substring(1,8);
1077                                                 var size = data.data.length;
1078                                                 if($scope.data == 'success'){
1079                                                         Notification.success("Validation Success.");
1080                                                         $scope.savebutton = false;
1081                                                         if (size > 18){
1082                                                                 var displayWarning = data.data.substring(19,size  - 1);
1083                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1084                                                                 document.getElementById("validate").style.color = "white";
1085                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1086                                                         }
1087                                                 }else{
1088                                                         Notification.error("Validation Failed.");
1089                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1090                                                         document.getElementById("validate").style.color = "white";
1091                                                         document.getElementById("validate").style.backgroundColor = "red";
1092                                                         $scope.savebutton = true;
1093                                                 }
1094                                                 
1095                                 });
1096                                 console.log($scope.data);       
1097                         },
1098                         error : function(data){
1099                                 Notification.error("Validation Failed.");
1100                                 $scope.savebutton = true;
1101                         }
1102                 });
1103     };
1104
1105     function extend(obj, src) {
1106         for (var key in src) {
1107             if (src.hasOwnProperty(key)) obj[key] = src[key];
1108         }
1109         return obj;
1110     }
1111 }]);