Fix wrong data name
[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     var layer = 0;
29     
30     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
31         $scope.temp.policy = {
32                         policyType : "Config",
33                         configPolicyType : "Micro Service"
34         }
35     };
36     
37     $scope.refresh = function(){
38         if($scope.refreshCheck){
39                 $scope.policyNavigator.refresh();
40         }
41         $scope.modal('createNewPolicy', true);
42         $scope.temp.policy = "";
43     };
44     
45     $scope.modal = function(id, hide) {
46         return $('#' + id).modal(hide ? 'hide' : 'show');
47     };
48     
49     $('#ttlDate').datepicker({
50         dateFormat: 'dd/mm/yy',
51         changeMonth: true,
52         changeYear: true,
53         onSelect: function(date) {
54                 angular.element($('#ttlDate')).triggerHandler('input');
55         }
56     });
57     
58         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
59                 if ($scope.temp.policy.configName == undefined){
60                         $scope.isCheck = false;
61                 }else{
62                         $scope.isCheck = true;
63                 }
64         }else {
65                 $scope.isCheck = false;
66         }
67                 
68         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
69                 var j = data;
70                 $scope.data = JSON.parse(j.data);
71                 console.log($scope.data);
72                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
73                 console.log($scope.onapNameDictionaryDatas);
74         }, function (error) {
75                 console.log("failed");
76         });
77
78         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
79                 var j = data;
80                 $scope.data = JSON.parse(j.data);
81                 console.log($scope.data);
82                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
83                 console.log($scope.priorityDatas);
84         }, function (error) {
85                 console.log("failed");
86         });
87
88         PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
89                 var j = data;
90                 $scope.data = JSON.parse(j.data);
91                 console.log($scope.data);
92                 $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
93                 console.log($scope.groupPolicyScopeListDatas);
94         }, function (error) {
95                 console.log("failed");
96         });
97
98         PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
99                 var j = data;
100                 $scope.data = JSON.parse(j.data);
101                 console.log($scope.data);
102                 console.log("$scope.data.microServiceConfigNameDictionaryDatas : " + $scope.data.microServiceConfigNameDictionaryDatas);
103                 if($scope.data.microServiceConfigNameDictionaryDatas){
104                     $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
105                 }
106                 console.log($scope.microServiceCongigNameDictionaryDatas);
107         }, function (error) {
108                 console.log("failed");
109         });
110
111         PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
112                 var j = data;
113                 $scope.data = JSON.parse(j.data);
114                 console.log($scope.data);
115                 $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
116                 console.log($scope.microServiceLocationDictionaryDatas);
117         }, function (error) {
118                 console.log("failed");
119         });
120
121         PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
122                 var j = data;
123                 $scope.data = JSON.parse(j.data);
124                 console.log($scope.data);
125                 var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
126                 var unique = {};
127                 var uniqueList = [];
128                 for(var i = 0; i < inputModelList.length; i++){
129                         if(typeof unique[inputModelList[i]] == "undefined"){
130                                 unique[inputModelList[i]] = "";
131                                 uniqueList.push(inputModelList[i]);
132                         }
133                 }
134                 $scope.microServiceModelsDictionaryDatas = uniqueList;
135                 console.log($scope.microServiceModelsDictionaryDatas);
136         }, function (error) {
137                 console.log("failed");
138         });
139
140         PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
141                 var j = data;
142                 $scope.data = JSON.parse(j.data);
143                 console.log($scope.data);
144                 $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
145                 console.log($scope.dcaeUUIDDictionaryDatas);
146         }, function (error) {
147                 console.log("failed");
148         });
149
150         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
151                 var j = data;
152                 $scope.data = JSON.parse(j.data);
153                 console.log($scope.data);
154                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
155                 console.log($scope.riskTypeDictionaryDatas);
156         }, function (error) {
157                 console.log("failed");
158         });
159
160         PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
161                 var j = data;
162                 $scope.data = JSON.parse(j.data);
163                 console.log($scope.data);
164                 $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
165                 console.log($scope.microServiceAttributeDictionaryDatas);
166         }, function (error) {
167                 console.log("failed");
168         });
169             
170
171          $scope.choices = [];
172          $scope.attributeDatas = [{"attributes" : $scope.choices}];
173          $scope.isInitEditTemplate = true;  //just initially create the edit template, didn't click add button yet.
174          addNewChoice = function(value) {
175                  console.log("input value : " + value);
176                  if(value != undefined){
177                         if (value.startsWith('div.')){
178                                 value = value.replace('div.','');
179                         }
180                         
181                         console.log(" document.getElementById : div."+value);
182                         var parentElement = document.getElementById("div."+value);
183                         console.log("parentElement : " + parentElement);
184                         var div = document.getElementById(value+"@0");
185                         if(div != null){
186                                 var clone = div.cloneNode(true); 
187                                 var addElement = parentElement.childElementCount;
188                                 clone.id = ''+value+'@'+addElement;
189                                 clone.value = '';
190                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
191                                         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
192                                                 if($scope.temp.policy.ruleData[clone.id]){
193                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
194                                                 }
195                                                 if(!clone.className.includes("child_single")){
196                                                    clone.className += ' child_single'; //here cloned is single element
197                                                 }
198                                                 document.getElementById("div."+value).appendChild(clone);
199                                                 plainAttributeKeys.push(''+value+'@'+addElement);
200                                         }
201                                 }else{ //not view or edit
202                                         if(!clone.className.includes("child_single")){
203                                             clone.className += ' child_single'; //here cloned is single element
204                                         }
205                                         document.getElementById("div."+value).appendChild(clone);
206                                         plainAttributeKeys.push(''+value+'@'+addElement);
207                                 }
208                         }else{
209                                 
210                                 if(parentElement == null){
211                                         return;
212                                 }
213                                 div = document.getElementById("div."+value+"@0");
214                                 if(div){
215                                         
216                                         if(!div.className.includes('children_group border')){
217                                                 layer++;
218                                                 if(layer > 4){ 
219                                                         layer = 1
220                                                 };
221                                     div.className += ' children_group border' + layer; //here is div with a group of children.
222                                         }
223                                 }
224                                 var childElement = parentElement.firstElementChild;
225                                 var countParent = parentElement.childElementCount;
226                                 var childElementString = childElement.innerHTML;
227                                 var find = value+"@0";
228                                 var re = new RegExp(find, 'g');
229                                 childElementString = childElementString.replace(re,value+'@' + countParent);
230                                 var clone = childElement.cloneNode(true);
231                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
232                             var childId = parentElement.childNodes[ii].id;
233                             if(ii = parentElement.childNodes.length){
234                                 var childnewId = childId.slice(0, -1);
235                                 var count = childId.slice(-1);
236                             }
237                         }
238                                 var countvalue = parseInt(count) + 1;
239                                 clone.id = childnewId+countvalue;
240                                 clone.value = '';
241                                 clone.innerHTML=childElementString;
242                                 document.getElementById("div."+value).appendChild(clone);
243                                 var selects = clone.getElementsByTagName("select");
244                                 var inputs = clone.getElementsByTagName("input");
245                                 var removeValues = [];
246                                 for(var i=0; i<inputs.length; i++){
247                                         if ($scope.temp.policy.ruleData!=undefined){
248                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
249                                                 if (checkValue!=undefined && checkValue != "undefined"){
250                                                         document.getElementById(inputs[i].id).value = checkValue;
251                                                                 plainAttributeKeys.push(inputs[i].id);
252                                                 } else {
253                                                         plainAttributeKeys.push(inputs[i].id);
254                                                 }
255                                         }else {
256                                                 plainAttributeKeys.push(inputs[i].id);
257                                         }
258                                 }
259                                 
260                                 for(var i=0; i<selects.length; i++){
261                                         if ($scope.temp.policy.ruleData!=undefined){
262                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
263                                                 if (checkValue!=undefined && checkValue!="undefined"){
264                                                         if($scope.temp.policy.ruleData != null){
265                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
266                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
267                                                                 plainAttributeKeys.push(selects[i].id);
268                                                         }
269                                                 } else {
270                                                         plainAttributeKeys.push(selects[i].id);
271                                                 }
272                                         }else {
273                                                 plainAttributeKeys.push(selects[i].id);
274                                         }
275                                 }
276                                 
277                                 for (var k=0; k<removeValues.length; k++){
278                                         var elem = document.getElementById(removeValues[k]);
279                                         elem.parentNode.removeChild(elem);
280                                 }
281                                 var ele = angular.element(document.getElementById("div."+value));
282                         $compile(ele.contents())($scope)
283                         }
284                  }
285          };
286          
287         
288          removeChoice = function(value) {
289                  console.log(value);
290                  if(value != undefined){
291                          var c = document.getElementById("div."+value).childElementCount;
292                          
293                          if(c == 1){
294                                  Notification.error("The original one is not removable.");
295                                  return;
296                          }      
297                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
298                  }
299          };
300          
301          function findVal(object, key) {
302                     var value;
303                     Object.keys(object).some(function(k) {
304                         if (k === key) {
305                             value = object[k];
306                             return true;
307                         }
308                         if (object[k] && typeof object[k] === 'object') {
309                             value = findVal(object[k], key);
310                             return value !== undefined;
311                         }
312                     });
313                     return value;
314         }
315          
316          $scope.pullVersion = function(serviceName) {
317                  console.log(serviceName);
318                  if(serviceName != undefined){
319                          var uuu = "policyController/getModelServiceVersioneData.htm";
320                          var postData={policyData: serviceName};
321                          $.ajax({
322                                  type : 'POST',
323                                  url : uuu,
324                                  dataType: 'json',
325                                  contentType: 'application/json',
326                                  data: JSON.stringify(postData),
327                                  success : function(data){
328                                          $scope.$apply(function(){
329                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
330                                          });
331                                  },
332                                  error : function(data){
333                                          alert("Error While Retriving the Template Layout Pattren.");
334                                  }
335                          });             
336                  }
337          };
338     
339     var splitDash = '-';
340         var splitEqual = '=';
341         var splitComma = ',';
342         var splitcolon = ':';
343         var splitsemicolon = ";";
344         var splitEnum = "],";
345         var plainAttributeKeys = [];
346         var matching = [];
347         var enumKeyList = [];
348         var dictionaryList = [];
349         var dictionaryNameList = [];
350     $scope.addDataToFields = function(serviceName, version){
351         if(serviceName != null && version !=null){
352                 var service=serviceName+"-v"+version;
353                 var myNode = document.getElementById("DynamicTemplate");
354                 myNode.innerHTML = '';
355             var uuu = "policyController/getDCAEMSTemplateData.htm";
356             var postData={policyData: service};
357             
358             console.log("service: " +service);
359             
360             var dataOrderInfo = "";
361
362             $.ajax({
363                 type : 'POST',
364                 url : uuu,
365                 dataType: 'json',
366                 contentType: 'application/json',
367                 data: JSON.stringify(postData),
368                 success : function(data){
369                     $scope.$apply(function(){
370                         var plainAttributeKeys = [];
371                         $scope.dcaeModelData = data[0].dcaeModelData;
372                         $scope.dcaeJsonDate = data[0].jsonValue;
373                         $scope.dataOrderInfo = null;
374                         $scope.dataOrderInfo = data[0].dataOrderInfo;
375                         console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
376                         console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);   
377                         
378                         if(data[0].allManyTrueKeys){
379                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
380                         }
381                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
382                         var attributes = $scope.dcaeModelData.attributes;                       
383                         console.log("attributes: " +attributes);                        
384                         var refAttributes = $scope.dcaeModelData.ref_attributes;
385                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
386                         console.log("subAttributes: " + subAttributes); 
387                         console.log("refAttributes: " + refAttributes); 
388                         var headDefautlsData  = data[0].headDefautlsData;
389                         if(headDefautlsData != null){
390                                          $scope.temp.policy.onapName = headDefautlsData.onapName;
391                                          $scope.temp.policy.guard = headDefautlsData.guard;
392                                          $scope.temp.policy.riskType = headDefautlsData.riskType;
393                                          $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
394                                          $scope.temp.policy.priority = headDefautlsData.priority;
395                         }
396                         
397                         var enumAttributes = $scope.dcaeModelData.enumValues;
398                         var annotation = $scope.dcaeModelData.annotation;
399                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
400
401                         if (annotation == null || annotation.length<1){
402                                 $scope.isCheck = true;
403                         }else {
404                                 $scope.isCheck = false;
405                                 var annoationList = annotation.split(splitComma);
406                                 for (k = 0; k < annoationList.length; k++){
407                                         var splitAnnotation = annoationList[k].split(splitEqual);
408                                         if (splitAnnotation[1].includes("matching-true")){
409                                                 matching.push(splitAnnotation[0].trim());
410                                         }
411                                 }
412
413                         }
414
415                         if (dictionary!= null && dictionary.length>1){
416                                 for (m=0; m < dictionary.length; m += 1){
417                                         var keyCompare = dictionary[m].name;
418                                         var valueCompare = dictionary[m].value;
419                                         var valueModel = dictionary[m].modelName;
420                                         var conpairService = serviceName;
421                                         if (valueModel.includes('-v')){
422                                                 conpairService = service;
423                                         }
424                                         if(valueModel.localeCompare(conpairService) == 0){
425                                                 console.log(valueCompare);      
426                                                 dictionaryList.push(dictionary[m]);
427                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
428                                                         dictionaryNameList.push(dictionary[m].name)
429                                                 }
430                                         }
431                                 }
432                         }
433
434                                 $scope.temp.policy.ruleGridData = [];
435                                 
436                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
437                                         dataOrderInfo = $scope.dataOrderInfo;
438                                 }
439                                 
440                                 $scope.jsonLayout($scope.dcaeJsonDate);
441                                 
442                     });
443                     
444                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
445                         
446                         if($scope.temp.policy.editPolicy){
447                                 $scope.isInitEditTemplate = true;
448                         }
449                         
450                         var checkData = [];
451                         var data = [];
452                             // If ruleData contains extra elements created by clicked add button 
453                                 if($scope.temp.policy.ruleData != null){
454                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
455                                         propNames.forEach(function(name) {
456                                                 data.push(name);
457                                         });
458                                         
459                                         var extraElements = data;
460                                         
461                                             if(plainAttributeKeys != null){
462                                                         for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
463                                                                 var newValue = plainAttributeKeys[b].split("*");
464                                                                 for(var a = 0; a < data.length; a++){
465                                                                         if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
466                                                                                 extraElements.splice(a, 1);
467                                                                         }
468                                                                 }
469                                                 }
470                                                 
471                                                 //--- Populate these extra elements created by clicked add button 
472                                                 for(var a = 0; a < extraElements.length; a++){                                  
473                                                         if(extraElements[a].includes("@")){
474                                                                 var index = extraElements[a].lastIndexOf("@");
475                                                                 if(index > 0){
476                                                                     // Get the number after @
477                                                                     var n = getNumOfDigits(extraElements[a], index+1);
478                                                                                         
479                                                                         var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
480                                                                         console.log("key: " + key);
481                                                                         checkData.push(key);
482                                                                 }
483                                                         }
484                                                 }
485                                                 var unique = checkData.filter(onlyUnique);
486                                                 var parentLevelElements = [];
487                                                 if(unique){
488                                                         //--- get all root level exta elments first (only contains one "@")
489                                                         for(var i =0; i < unique.length; i++){
490                                                                 var firstIndex = unique[i].indexOf("@");
491                                                                 var lastIndex = unique[i].lastIndexOf("@");
492                                                                 if(firstIndex == lastIndex){    
493                                                                         var newKey = unique[i].substring(0, firstIndex);
494                                                                         console.log("root element: " + newKey);
495                                                                         parentLevelElements.push(newKey);
496                                                                         unique[i] = "*processed*";
497                                                                 }
498                                                         }                                                       
499                                                 }
500                                                 //if no layout order info, keep the process as before
501                                                 if(!dataOrderInfo){
502                                                         for(var i =0; i < unique.length; i++){
503                                                                 //remove @x and let addNewChoice add @1 or @2...
504                                                                 //var newKey = unique[i].substring(0, unique[i].length-2);
505                                                                 var index = unique[i].lastIndexOf("@");
506                                                                 var newKey = unique[i].substring(0, index);
507                                                                 console.log("newKey: " + newKey);       
508                                                                 addNewChoice(newKey);
509                                                         }
510                                                 }else{
511
512                                                                 for (var i = 0; i < $scope.labelManyKeys.length; i++) {
513                                                                         //console.log("dataOrderInfo["+i+"]"+  dataOrderInfo[i]);
514                                                                     var label = $scope.labelManyKeys[i];
515                                                                     
516                                                                     if(parentLevelElements){
517                                                                         for (var k = 0; k < parentLevelElements.length; k++){
518                                                                                 if(label == parentLevelElements[k]){
519                                                                                         addNewChoice(label);
520                                                                                 }
521                                                                         }
522                                                                         
523                                                                     }
524                                                                                 
525                                                                 }
526                                                                 
527                                                                 //---reset to default
528                                                                 dataOrderInfo = [];
529                                                                 $scope.labelManyKeys = [];
530                                                                 
531                                                                 //---process none labels
532                                                                 for (var j = 0; j < unique.length; j++){
533                                                                         if(unique[j] != "*processed*"){
534                                                                                 // if not created yet
535                                                                                 if(!document.getElementById(unique[j])){
536                                                                                         var index = unique[j].lastIndexOf("@");
537                                                                                         var newKey = unique[j].substring(0, index);
538                                                                                         
539                                                                                         var newElement = document.getElementById("div."+unique[j]);
540                                                                                         
541                                                                                         //check weather it has been created already
542                                                         if(newElement != null){
543                                                                 continue;
544                                                         }else{
545                                                                 newElement = document.getElementById(unique[j]);
546                                                                 if(newElement != null){
547                                                                         continue;
548                                                                 }
549                                                         } 
550                                                         //if not created yet, then create it.                                                                                           
551                                                                                         addNewChoice(newKey);
552                                                                                    
553                                                                                 }
554                                                                         }
555                                                                 }
556                                                         }
557                                             }
558                                 }
559
560                     }
561                     var ele = angular.element(document.getElementById("DynamicTemplate"));
562                         $compile(ele.contents())($scope);
563                     $scope.$apply();
564                     
565                 },
566                 error : function(data){
567                     alert("Error While Retriving the Template Layout Pattren.");
568                 }
569             });
570
571         }
572     };
573     
574     function getNumOfDigits(str_value, index){
575                 // Get the number after @
576                 var str = str_value.substring(index, str_value.length); 
577                 var c = '';
578                 var n = 0;
579                 for (var x = 0; x < str.length; x++){                                                                   
580                     c = str.charAt(x);
581                             if(!isNaN(c)){ 
582                 n++;                                                     
583                     }else{
584                 break;
585             }
586                 }
587                 return n;
588     }
589     
590     function getDictionary(attribute){
591         var dicName = attribute;
592         if(attribute){
593            if(attribute.includes(":")){
594                    dicName = attribute.split(":")[0];
595            }
596         }
597             var dictionaryRegExp = new RegExp(dicName);
598             listemunerateValues = [];
599             if (dictionaryRegExp.test(dictionaryNameList)) {
600                         for (p=0; p < dictionaryList.length; p += 1) {
601                                 if (dicName == dictionaryList[p].name) {
602                                         listemunerateValues.push(dictionaryList[p].value);
603                                 }
604                         }
605             }
606             return listemunerateValues;
607     }
608     
609     function getList(attribute) {
610                 var enumName = attribute;
611                 console.log("In getList: attribute => " + attribute);
612                 if(attribute){
613                    if(attribute.includes(":")){
614                            enumName = attribute.split(":")[0];
615                    }
616                 }   
617             var baseEnum = $scope.dcaeModelData.enumValues;
618             var enumList = [];
619             if(baseEnum != null){
620                 enumList = baseEnum.split(splitEnum);
621             }
622                 var enumAttributes;
623                 var patternTest = new RegExp(enumName);
624                 for (k=0; k < enumList.length; k += 1){
625                         if(patternTest.test(enumList[k]) == true){
626                                 enumAttributes = enumList[k].trim();
627                 }
628         }
629
630          if(enumAttributes){
631                 enumAttributes = enumAttributes.replace("[", "");
632                 enumAttributes = enumAttributes.replace("]", "");
633                 enumAttributes = enumAttributes.replace(/ /g, '');
634                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
635                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
636                         //enumKeyList.push(attribute); 
637                 return listemunerateValues;
638          }
639          
640             return [];
641             }
642             
643             function getBooleanList(){
644                 var booleanList = [];
645                 booleanList.push(true);
646                 booleanList.push(false);
647                 return booleanList;
648             }
649             
650
651             function isArray(arrayTest) {
652                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
653             }
654             var lableList = [];
655             
656             $scope.layOutElementList = [];
657             $scope.layOutOnlyLableList = [];
658             
659             var elementOrderNum = 0;
660             
661                 function deconstructJSON(layOutData, level , name) {
662
663                          var array = false;
664                          var label = level;
665                          var stringValue = "java.lang.String";
666                          var string = "string";
667                          var intValue = "int";
668                          var integerValue = "integer";
669                          var double = "double";
670                          var boolean = "boolean";
671                          var baseLevel = level;
672                          var list = "list";
673                          var String = "String";
674                          
675                          var attributekey = "";
676                          
677                         if (name.length > 1){
678                                 label = label + name + '.';
679                         }
680                         
681                     for (key in layOutData) {
682                         array = isArray(layOutData[key]);
683                         console.log("key: " + key , "value: " + layOutData[key]);
684                 
685                         if (!!layOutData[key] && typeof(layOutData[key])=="object") {
686                                 
687                                 if (array==false && key!=="0"){
688                                         
689                                         if($scope.dataOrderInfo){
690                                             var labelObject = {"label" : key, "level" : label, "array" : array};
691                                             //save it to the list
692                                             $scope.layOutOnlyLableList.push(labelObject);
693                                             
694                                         }else {
695                                                 //call label layout
696                                                 $scope.labelLayout(label, key, array );
697                                         }
698                                         
699                                 }
700                                 
701                                 if (array == true && key!=0){
702                                         lableList.push(key);
703                                 }
704                                 
705                                 if (lableList.length > 0){
706                                         array = true;
707                                 }
708                                 if ( key==="0"){
709                                         var newKey = lableList.pop();
710                                         
711                                         if($scope.dataOrderInfo){
712                                                 
713                                                 var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
714                                                 //save it to the list
715                                                 $scope.layOutOnlyLableList.push(labelObject);
716                                                 
717                                         }else {
718                                                 //call label layout 
719                                             $scope.labelLayout(baseLevel, newKey, array );
720                                         }
721                                         
722                                         if (array){
723                                                 label = baseLevel + newKey + '@0.';
724                                         } else {
725                                                 label = baseLevel + newKey + '.';
726                                         }
727                                 }
728                                 deconstructJSON(layOutData[key] , label, key);
729                         } else {
730                                 var attirbuteLabel = label;
731                                 var defaultValue='';
732                                 var isRequired = false;
733                                 if (layOutData[key].includes('defaultValue-')){
734                                         defaultValue = layOutData[key].split('defaultValue-')[1];
735                                 }
736
737                                 if (key==="0"){
738                                         array = true;
739                                         attributekey = lableList.pop();
740                                         attirbuteLabel = baseLevel;
741                                 } else {
742                                         attributekey = key.split();
743                                 }
744                                 
745                                 if (layOutData[key].includes('required-true')){
746                                         isRequired = true;
747                                 }
748                                 
749                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
750                                 
751                                 if(subAttributes){                                      
752                                         var jsonObject = JSON.parse(subAttributes);     
753                                         
754                                     var lablInfo = findVal(jsonObject, attributekey);
755                                         console.log("deconstructJSON:findValue : " + attributekey +": "+ lablInfo);
756                                         if (lablInfo){
757                                                 if(lablInfo.includes('required-true')){
758                                                         isRequired = true;
759                                                 }       
760                                         }else{                                  
761                                            var allkeys = Object.keys(jsonObject);
762                                            if(allkeys){
763                                                    for (var k = 0; k < allkeys.length; k++) {
764                                                           var keyValue = allkeys[k];
765                                                           console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
766                                                           if(jsonObject[keyValue]){
767                                                                  var tempObject = jsonObject[keyValue];
768                                                                  if(tempObject && tempObject[key]){
769                                                                  if (tempObject[key].includes('required-true')){
770                                                                         isRequired = true;
771                                                                  }      
772                                                                  }
773                                                           }
774                                                    }                                            
775                                            }                                    
776                                         } 
777                                 }
778                                 
779                                 var elementObject = {};
780                                 switch (layOutData[key].split(splitcolon)[0]){
781                                 
782                                         case stringValue:
783                                         case string:
784                                                 if($scope.dataOrderInfo){                                                       
785                                                         elementOrderNum++;
786                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
787                                                         $scope.layOutElementList.push(elementObject);
788                                                 }else{
789                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
790                                                 }
791                                                 break;                                          
792                                         case intValue: 
793                                         case integerValue: 
794                                                 if($scope.dataOrderInfo){
795                                                         elementOrderNum++;
796                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
797                                                         $scope.layOutElementList.push(elementObject);
798                                                 }else{
799                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
800                                                 }
801                                                 break;                                          
802                                         case double:
803                                                 if($scope.dataOrderInfo){
804                                                         elementOrderNum++;
805                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
806                                                         $scope.layOutElementList.push(elementObject);                                                   
807                                                 }else{
808                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
809                                                 }
810                                                 break;
811                                         case boolean:
812                                                 if($scope.dataOrderInfo){
813                                                         elementOrderNum++;
814                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
815                                                         $scope.layOutElementList.push(elementObject);
816                                                 }else{
817                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
818                                                 }
819                                                 break;
820                                         default:
821                                                 if (layOutData[key].includes('dictionary-')){
822                                                         var list = getDictionary(layOutData[key].split('dictionary-')[1]);
823                                                 }else{
824                                                         //--- get dropdown values from enumValues
825                                                         var list = getList(layOutData[key]);
826                                                 }
827                                                 if (list.length===0){ //not dropdown element
828                                                         if($scope.dataOrderInfo){
829                                                                 elementOrderNum++;
830                                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
831                                                                 $scope.layOutElementList.push(elementObject);
832                                                                 
833                                                         }else{
834                                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
835                                                         }                                                       
836                                                 }else{
837                                                         if($scope.dataOrderInfo){
838                                                                 elementOrderNum++;
839                                                                 elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
840                                                                 $scope.layOutElementList.push(elementObject);                                                           
841                                                         }else{
842                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
843                                                         }
844                                                 }
845                                                 break;
846                                 }
847                         }
848                     }
849                 }  
850                 
851                 
852             $scope.validContionalRequired = function(parentId) {
853                 console.log("ng-blur event: parentId : " + parentId);
854                 var c = document.getElementById(parentId).children;
855                 var i;
856                 var hasValue = false;
857                 for (i = 0; i < c.length; i++) {
858                         if(c[i].getAttribute("data-conditional")){
859                             console.log(c[i].getAttribute("data-conditional"));
860                             console.log(c[i].value);
861                             if(c[i].value != null && c[i].value.trim() != ""){
862                                 hasValue = true;
863                             }
864                         }
865                 }
866
867                     for (i = 0; i < c.length; i++) {
868                         if(c[i].getAttribute("data-conditional")){
869                                 if(hasValue){
870                                     c[i].setAttribute("required", true);
871                                 }else{
872                                         c[i].removeAttribute("required");
873                                 }
874                         }
875                     }           
876              }
877                                 
878             $scope.jsonLayout = function(layOutData){
879                 
880                    deconstructJSON(layOutData , "", "");
881                    
882                    var orderValue = $scope.dataOrderInfo;
883                    var layOutElementList = $scope.layOutElementList;
884                    var labelList = $scope.layOutOnlyLableList;
885                     
886                    //reset to default
887                    elementOrderNum = 0;
888                    $scope.layOutElementList = [];
889                    $scope.layOutOnlyLableList = [];
890                    
891                    // Only layout in order if order info provided
892                    if(orderValue){
893                            
894                            if(orderValue.includes("[")){
895                                   orderValue = orderValue.replace("[", "") ;
896                                   orderValue = orderValue.replace("]", "") ;
897                            }
898                            
899                            orderValue = orderValue.split(',') ;
900                            
901                            for (var i = 0; i < orderValue.length; i++) {
902                                    console.log("orderValue["+i+"]"+  orderValue[i]);
903                                    var key = orderValue[i].trim();
904                                  
905                                     //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
906                                    if(labelList){
907                                            for (var k = 0; k < labelList.length; k++){
908                                                    
909                                                   var label = labelList[k].label.toString().trim();
910                                                   var level = labelList[k].level.toString().trim();
911                                                   var array = labelList[k].array;
912                                                   
913                                                   if(key == label){                                                       
914                                                          $scope.labelLayout(level, label, array);
915                                                          //in case to have duplicate label names
916                                                          labelList[k].label = "*processed*";
917                                                          break;
918                                                   }
919                                            }
920                                    }
921                                    //--- then layout each element based on its order defined in YAML file
922                                    for (var j = 0; j < layOutElementList.length; j++) { 
923                                            
924                                            var attributekey = layOutElementList[j].attributekey.toString().trim();                                         
925                                         
926                                            if(key == attributekey){     
927
928                                                    var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
929                                                    var defaultValue = layOutElementList[j].defaultValue.toString().trim();
930                                                    var isRequired = layOutElementList[j].isRequired;
931                                                    
932                                                    console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
933                                                 console.log("layOutElementList[" +j+ "]: type:" + layOutElementList[j].type);
934                                                    if (layOutElementList[j].type == "dropBox"){ 
935                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
936                                         
937                                                    }else{
938                                                             $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type); 
939         
940                                                    }
941                                                    
942                                                    //in case to have duplicate attribute names
943                                                    layOutElementList[j].attributekey = "*processed*";
944                                                    break;
945                                            }
946                                    }
947                            }
948                    }
949             }
950             
951             
952             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
953                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
954                 var br = document.createElement("BR");
955                 
956                 var label = document.createElement("Label");
957                 var labeltext = null;
958                 var requiredLabName = "";
959                 if (matching.includes(attibuteKey)){
960                         labeltext = document.createTextNode(attibuteKey + "*!");        
961                         isRequired = true;  //set required as true for matching element
962                 }else {
963                         if(isRequired){
964                                 requiredLabName = attibuteKey + " * ";
965                                 labeltext = document.createTextNode(requiredLabName);
966                         }else{
967                             labeltext = document.createTextNode(attibuteKey);   
968                         }
969                 }
970
971                 
972                 var divID = labelValue;
973                 
974                 if (labelValue.length  < 1){
975                         divID = "DynamicTemplate";
976                 }else if (labelValue.endsWith('.')){
977                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
978                 }
979                 
980                 label.appendChild(labeltext);
981                 
982                 var textField = document.createElement("INPUT");
983                 
984                 textField.setAttribute("class" , "form-control");
985                 if(dataType){
986                            if(dataType == "double"){
987                                    textField.setAttribute("type" , "number");
988                                    textField.setAttribute("step" , "any");
989                            }else{
990                               textField.setAttribute("type" , dataType);
991                            }
992                 }
993                 textField.setAttribute("style" , "width:300px;");
994                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
995                 var checkKey;
996                 var id = "";
997                 if(attributeManyKey){
998                         checkKey = labelValue + attibuteKey+'@0';
999                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
1000                         var divTag = document.createElement("div");
1001                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
1002                         var addButton = document.createElement("BUTTON");
1003                         var buttonaddLabel = document.createTextNode("+");       
1004                         addButton.appendChild(buttonaddLabel); 
1005                         addButton.setAttribute("id", labelValue + attibuteKey);
1006                         addButton.setAttribute("class", "btn btn-add-remove");
1007                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
1008                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1009                         var removeButton = document.createElement("BUTTON");
1010                         var buttonremoveLabel = document.createTextNode("-");       
1011                         removeButton.appendChild(buttonremoveLabel); 
1012                         removeButton.setAttribute("class", "btn btn-add-remove");
1013                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue + attibuteKey+'");');
1014                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1015                         document.getElementById(divID).appendChild(addButton); 
1016                         document.getElementById(divID).appendChild(removeButton); 
1017                         document.getElementById(divID).appendChild(label); 
1018                         id = "div."+labelValue+attibuteKey;
1019                         //var divTag = document.createElement("div");
1020                         divTag.setAttribute("id", id); 
1021                         document.getElementById(divID).appendChild(divTag);
1022                         textField.className += ' first_child';  
1023                         if(isRequired){
1024                                 textField.setAttribute("required", "true");
1025                         }                       
1026                         divTag.appendChild(textField);                  
1027                         document.getElementById(divID).appendChild(divTag); 
1028                         
1029                 }else{
1030                         checkKey = labelValue + attibuteKey;
1031                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
1032                         if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
1033                                 if(requiredLabName.includes("*") || isRequired){
1034                                         textField.setAttribute("required", "true");
1035                                 }
1036                         }else if (document.getElementById(divID).hasAttribute('data-conditional')){
1037                                 if(requiredLabName.includes("*")){                                      
1038                                         var requiredNode = document.createElement('span');
1039                                         requiredNode.setAttribute("class", "mstooltip");
1040                                         requiredNode.textContent = "?";
1041                                         label.appendChild(requiredNode);
1042                                         
1043                                         var requiredNodeToolTip = document.createElement('span');
1044                                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
1045                                         requiredNodeToolTip.textContent = "Conditional Required";
1046                                         requiredNode.appendChild(requiredNodeToolTip);
1047                                         
1048                                         textField.setAttribute("data-conditional", divID);
1049                                         textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1050                                 }
1051                         }
1052             
1053                         document.getElementById(divID).appendChild(label);  
1054                         document.getElementById(divID).appendChild(textField);  
1055                         document.getElementById(divID).appendChild(br); 
1056
1057                 }
1058
1059                 if(divID.includes("@0") && divID.includes("div.")){
1060                         var firstChild_Id = divID.split("@0")[0];
1061                         var firstChild_element = document.getElementById(firstChild_Id);
1062                         if(firstChild_element){
1063                         
1064                                 if(!firstChild_element.className.includes('children_group border')){
1065                                         layer++;
1066                                         if(layer > 4){ 
1067                                                 layer = 1
1068                                         };
1069                                         firstChild_element.className += ' children_group border' + layer; //here is div with a group of children.
1070                                 }
1071                         }
1072                 }
1073                 console.log('firstChild_Id: ' + firstChild_Id);
1074                 console.log('divID: ' + divID);
1075                 
1076                 if (defaultValue.length > 0){   
1077                         if(defaultValue.includes(":")){
1078                                 defaultValue = defaultValue.split(":")[0];
1079                                 if(defaultValue === "NA") {
1080                                         defaultValue = "";
1081                                 }                               
1082                         }
1083                         if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
1084                         document.getElementById(checkKey).value = defaultValue;
1085                         }
1086                 }
1087                 
1088                 if($scope.temp.policy.ruleData != null){
1089                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1090                         if (attributeManyKey){
1091                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
1092                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
1093                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
1094                                 }
1095                         }else{
1096                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
1097                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1098                                 }
1099                         }
1100                 } 
1101                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
1102     };
1103   
1104     $scope.labelManyKeys = [];
1105     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
1106                 var label = document.createElement("Label")
1107                 var divID = labelValue;
1108                 if (labelValue.endsWith('.')){
1109                         var workingLabel = labelValue.substring(0, labelValue.length-1);
1110                 }else {
1111                         var workingLabel = labelValue;
1112                 }
1113                 
1114                 if (labelValue.length  < 1){
1115                         divID = "DynamicTemplate";
1116                 } else if (labelValue.endsWith('.')){
1117                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1118                 }
1119                 
1120                 var subAttributes = $scope.dcaeModelData.sub_attributes;
1121             var jsonObject = JSON.parse(subAttributes); 
1122             var lablInfo = findVal(jsonObject, lableName);
1123                 console.log("findValue : " + lableName +": "+ lablInfo);
1124                 var star = "";
1125                 var required = null;
1126                 if(lablInfo){
1127                         if(typeof lablInfo === 'string' ){
1128                            if(lablInfo.includes("required-true")){
1129                                    star = " *";
1130                                    required = true;
1131                             }else if (lablInfo.includes("required-false")){
1132                                    required = false
1133                             }
1134                         }
1135                 }
1136                 
1137                 var labeltext = document.createTextNode(lableName + star);
1138         
1139                 label.appendChild(labeltext);
1140
1141
1142                 if(labelManyKey){
1143                         var addButton = document.createElement("BUTTON");
1144                         var buttonLabel = document.createTextNode("+");       
1145                         addButton.appendChild(buttonLabel); 
1146                         addButton.setAttribute("class", "btn btn-add-remove");
1147                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + lableName+'");');
1148                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1149                         var removeButton = document.createElement("BUTTON");
1150                         var buttonremoveLabel = document.createTextNode("-");       
1151                         removeButton.appendChild(buttonremoveLabel); 
1152                         removeButton.setAttribute("class", "btn btn-add-remove");
1153                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue +lableName+'");');
1154                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
1155                         document.getElementById(divID).appendChild(addButton); 
1156                         document.getElementById(divID).appendChild(removeButton);
1157                         document.getElementById(divID).appendChild(label);
1158                         var id = "div."+labelValue+lableName;
1159                         var divTag = document.createElement("div");
1160                         divTag.setAttribute("id", id); 
1161                         document.getElementById(divID).appendChild(divTag);
1162                         
1163                         var divTag = document.createElement("div");
1164                         divTag.setAttribute("id", id +'@0');  
1165                         
1166                         if(!divTag.className.includes('children_group border')){
1167                                 layer++;
1168                                 if(layer > 4){ 
1169                                         layer = 1
1170                                 };
1171                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1172                         }
1173                         if(required){
1174                            divTag.setAttribute("required", required);  
1175                         }else if(required == false){
1176                            divTag.setAttribute("data-conditional", "yes");  
1177                         }
1178                         
1179                         document.getElementById(id).appendChild(divTag);
1180                         
1181                         $scope.labelManyKeys.push(lableName);
1182                         
1183                 }else{
1184                         var divTag = document.createElement("div");
1185                         divTag.setAttribute("id", "div."+labelValue+lableName);
1186                         
1187                         if(!divTag.className.includes('children_group border')){
1188                                 layer++;
1189                                 if(layer > 4){ 
1190                                         layer = 1
1191                                 };
1192                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1193                         }
1194                         if(required){
1195                             divTag.setAttribute("required", required);  
1196                         }else if(required == false){
1197                                 divTag.setAttribute("data-conditional", "yes");  
1198                         }  
1199                         document.getElementById(divID).appendChild(label);  
1200                         document.getElementById(divID).appendChild(divTag);                     
1201                 }
1202     };
1203
1204     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
1205                         var br = document.createElement("BR");
1206                 
1207                         if (labelLevel.length  < 1){
1208                                         var divID = "DynamicTemplate";
1209                         } else if (labelLevel.endsWith('.')){
1210                                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
1211                         }       
1212                 
1213                 
1214                         var label = document.createElement("Label")
1215                         
1216                         var refAttributes = $scope.dcaeModelData.ref_attributes;
1217                         if(isRequired != true && refAttributes){ //check refAttributes also             
1218                                         var refAttributesList = refAttributes.split(splitComma);
1219                                         for (k = 0; k < refAttributesList.length; k++){
1220                                         var refAttribute = refAttributesList[k].split(splitEqual);                      
1221                                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
1222                                                 isRequired = true;
1223                                         }
1224                                         }
1225                         }
1226                         
1227                         if (matching.includes(attributeName)){
1228                                 var labeltext = document.createTextNode(attributeName + "*!");
1229                                 label.appendChild(labeltext);
1230                                 isRequired = true;  //set required as true for matching element
1231                         }else {
1232                                 var labeltext = document.createTextNode(attributeName);         
1233                                 if(isRequired){
1234                                     var requiredLabName = attributeName+ " * ";
1235                                         labeltext = document.createTextNode(requiredLabName);
1236                                 }else{
1237                                     labeltext = document.createTextNode(attributeName); 
1238                                 }
1239                         
1240                             label.appendChild(labeltext);               
1241                         }
1242                         label.appendChild(labeltext);
1243                         // if this field is required, but its parent is not required
1244                         if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
1245                                 var requiredNode = document.createElement('span');
1246                                 requiredNode.setAttribute("class", "mstooltip");
1247                                 requiredNode.textContent = "?";
1248                                 label.appendChild(requiredNode);
1249                                         
1250                                 var requiredNodeToolTip = document.createElement('span');
1251                                 requiredNodeToolTip.setAttribute("class", "tooltiptext");
1252                                 requiredNodeToolTip.textContent = "Conditional Required";
1253                                 requiredNode.appendChild(requiredNodeToolTip);
1254
1255                         }
1256                 
1257                         var listField = document.createElement("SELECT");
1258                         listField.setAttribute("class" , "form-control");
1259                         listField.setAttribute("style" , "width:300px;");
1260                         listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1261                         
1262                         if(isRequired){
1263                             if(document.getElementById(divID).hasAttribute('data-conditional')){
1264                                 listField.setAttribute("data-conditional", divID);
1265                                 listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1266                             }else{
1267                                         listField.setAttribute("required", true);
1268                             }
1269                         }
1270                         if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
1271                                 var optionFirst = document.createElement('option');
1272                                 optionFirst.setAttribute('value', "");
1273                                 listField.appendChild(optionFirst);     
1274                         }
1275                         
1276                         for (i=0; i < listemunerateValues.length; i += 1) {
1277                                 if(listemunerateValues[i].includes("equal-sign")){
1278                                         listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
1279                                 }
1280                             option = document.createElement('option');
1281                             option.setAttribute('value', listemunerateValues[i]);
1282                             option.appendChild(document.createTextNode(listemunerateValues[i]));
1283                             option.setAttribute('value', listemunerateValues[i]);
1284                             listField.appendChild(option);
1285                         }
1286                         listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
1287                         
1288                         enumKeyList.push(attributeName);
1289                         
1290                         document.getElementById(divID).appendChild(label);  
1291                         document.getElementById(divID).appendChild(br); 
1292                                         
1293                         if(many == true){
1294                                 document.getElementById(divID).appendChild(listField).multiple = true;
1295                                 plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
1296                         }else {
1297                                 document.getElementById(divID).appendChild(listField).multiple = false;
1298                                 plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
1299                         }
1300                 
1301                         if($scope.temp.policy.ruleData != null){
1302                                 if (many == true){
1303                                         document.getElementById(labelLevel +attributeName).options[0].selected = false;
1304                                         for (i=0; i < listemunerateValues.length; i += 1) {
1305                                                 var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
1306                                                 if (testValue === undefined){
1307                                                         testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
1308                                                         }
1309                                                 var location = listemunerateValues.indexOf(testValue);
1310                                                 if (location!=-1){
1311                                                         document.getElementById(labelLevel +attributeName).options[location].selected = true;
1312                                                         }
1313                                                 }                       
1314                                         }else {
1315                                                     if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1316                                             document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];        
1317                                                     }
1318                                         }
1319                                 }
1320                     };
1321     
1322     function onlyUnique(value, index, self) { 
1323         return self.indexOf(value) === index;
1324     };
1325     
1326     
1327     function checkDictionary(value){
1328         for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
1329                 if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
1330                         return true;
1331                 }
1332         }
1333         
1334     }
1335     $scope.savePolicy = function(policy){
1336         if(policy.itemContent != undefined){
1337                 $scope.refreshCheck = true; 
1338                 $scope.policyNavigator = policy.itemContent;
1339                 policy.itemContent = "";
1340         }
1341         $scope.savebutton = false;
1342         var splitAt = '*';
1343         var dot ='.';
1344         var jsonPolicy = {};
1345         if(plainAttributeKeys != null){
1346                 for(a = 0; a < plainAttributeKeys.length; a++){
1347                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1348                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
1349                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1350                         var key = splitPlainAttributeKey[0];
1351                 if(searchElement == null){
1352                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1353                     key = splitPlainAttributeKey[0]+'@0';
1354                 }else if (searchElement.nodeName == 'BUTTON'){
1355                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1356                                 key = splitPlainAttributeKey[0]+'@0';
1357                         }
1358                         if(searchElement != null){
1359                                 var keySplit = key.split(dot);
1360                                 var elumentLocation = keySplit.length;
1361                                 var enumKey = key;
1362                                 if (elumentLocation > 1){
1363                                         enumKey = keySplit[keySplit.length - 1];
1364                                 }
1365                                 //check it is undefined or not
1366                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
1367                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
1368                                                         var multiSlect = [];
1369                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1370                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1371                                                                 }
1372                                                         jsonPolicy[key]= multiSlect;
1373                                                 }else{
1374                                                         console.log(" searchElement.value = > " + searchElement.value);
1375                                                         jsonPolicy[key]= searchElement.value;
1376                                                 }
1377                                 } else {
1378                                         if(searchElement.value != null){
1379                                                         console.log(" searchElement.value = > " + searchElement.value);
1380                                                 jsonPolicy[key]= searchElement.value;
1381                                         }
1382                                 }
1383                         }
1384                 }
1385         }
1386         var uuu = "policycreation/save_policy";
1387         var postData={policyData: policy, policyJSON : jsonPolicy};
1388         $.ajax({
1389             type : 'POST',
1390             url : uuu,
1391             dataType: 'json',
1392             contentType: 'application/json',
1393             data: JSON.stringify(postData),
1394             success : function(data){
1395                 $scope.$apply(function(){
1396                         $scope.data=data.policyData;
1397                         if($scope.data == 'success'){
1398                                 $scope.temp.policy.readOnly = 'true';
1399                                 $scope.safetyChecker = data.policyData.split("#")[2];
1400                                 if ($scope.safetyChecker!=undefined) {
1401                                         Notification.success($scope.safetyChecker);
1402                                 }
1403                                 $scope.pushStatus=data.policyData.split("&")[1];
1404                                 if($scope.pushStatus=="successPush"){
1405                                         Notification.success("Policy pushed successfully");
1406                                 }
1407                                 Notification.success("Policy Saved Successfully.");     
1408                         }else if ($scope.data == 'PolicyExists'){
1409                                                 $scope.savebutton = true;
1410                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1411                                         }
1412                 });
1413                 console.log($scope.data);
1414             },
1415             error : function(data){
1416                 Notification.error("Error Occured while saving Policy.");
1417             }
1418         });
1419     };
1420     
1421     $scope.validatePolicy = function(policy){
1422         document.getElementById("validate").innerHTML = "";
1423         var splitAt = '*';
1424         var dot ='.';
1425         var jsonPolicy = {};
1426         if(plainAttributeKeys != null){
1427                 for(a = 0; a < plainAttributeKeys.length; a++){
1428                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1429                         console.log(splitPlainAttributeKey[1]); 
1430                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1431                         var key = splitPlainAttributeKey[0];
1432                         if(searchElement == null){
1433                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1434                                 key = splitPlainAttributeKey[0]+'@0';
1435                         }else if (searchElement.nodeName == 'BUTTON'){
1436                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1437                                 key = splitPlainAttributeKey[0]+'@0';
1438                         }
1439                         if(searchElement != null){
1440                                 if (enumKeyList.indexOf(key) != -1){
1441                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1442                                                         var multiSlect = [];
1443                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1444                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1445                                                                 }
1446                                                         jsonPolicy[key]= multiSlect;
1447                                                 }else{
1448                                                         jsonPolicy[key]= searchElement.value;
1449                                                 }
1450                                         if(searchElement.getAttribute("required")){
1451                                                 if(!searchElement.value){
1452                                                         return;
1453                                                 }
1454                                         } 
1455                                 } else {
1456                                         if(searchElement.value != null){
1457                                                 jsonPolicy[key]= searchElement.value;
1458                                                 if(searchElement.getAttribute("required")){
1459                                                         if(!searchElement.value){
1460                                                                 return;
1461                                                         }
1462                                                 }                                               
1463                                         }
1464                                 }
1465                         }
1466                 }
1467         }
1468         var uuu = "policyController/validate_policy.htm";
1469
1470         console.log("$scope.isCheck:" + $scope.isCheck);
1471         
1472         if($scope.isCheck == true){
1473                 if(("configName" in policy) == false){
1474                                 Notification.error("Validation Failed: configName is required");
1475                                 $scope.savebutton = true;
1476                                 return;
1477                 }
1478                 if(("location" in policy) == false){
1479                                 Notification.error("Validation Failed: location is required");
1480                                 $scope.savebutton = true;
1481                                 return;
1482                 }
1483                 if(("uuid" in policy) == false){
1484                                 Notification.error("Validation Failed: uuid is required");
1485                                 $scope.savebutton = true;
1486                                 return;
1487                 }
1488                 if(("policyScope" in policy) == false){
1489                                 Notification.error("Validation Failed: policyScope is required");
1490                                 $scope.savebutton = true;
1491                                 return;
1492                 }
1493         }        
1494         
1495         var postData={policyData: policy, policyJSON : jsonPolicy};
1496                 $.ajax({
1497                         type : 'POST',
1498                         url : uuu,
1499                         dataType: 'json',
1500                         contentType: 'application/json',
1501                         data: JSON.stringify(postData),
1502                         success : function(data){
1503                                 $scope.$apply(function(){
1504                                         $scope.validateData = data.data.replace(/\"/g, "");
1505                                         $scope.data=data.data.substring(1,8);
1506                                                 var size = data.data.length;
1507                                                 if($scope.data == 'success'){
1508                                                         Notification.success("Validation Success.");
1509                                                         $scope.savebutton = false;
1510                                                         if (size > 18){
1511                                                                 var displayWarning = data.data.substring(19,size  - 1);
1512                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1513                                                                 document.getElementById("validate").style.color = "white";
1514                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1515                                                         }
1516                                                 }else{
1517                                                         Notification.error("Validation Failed.");
1518                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1519                                                         document.getElementById("validate").style.color = "white";
1520                                                         document.getElementById("validate").style.backgroundColor = "red";
1521                                                         $scope.savebutton = true;
1522                                                 }
1523                                                 
1524                                 });
1525                                 console.log($scope.data);       
1526                         },
1527                         error : function(data){
1528                                 Notification.error("Validation Failed.");
1529                                 $scope.savebutton = true;
1530                         }
1531                 });
1532     };
1533
1534     function extend(obj, src) {
1535         for (var key in src) {
1536             if (src.hasOwnProperty(key)) obj[key] = src[key];
1537         }
1538         return obj;
1539     }
1540 }]);