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