Merge "documentation for using guard in the PDP"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateDcaeMicroServiceController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23
24 import java.io.BufferedInputStream;
25 import java.io.BufferedOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.io.StringReader;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.LinkedHashMap;
45 import java.util.LinkedList;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Map.Entry;
49 import java.util.Set;
50 import java.util.TreeMap;
51 import java.util.UUID;
52 import java.util.zip.ZipEntry;
53 import java.util.zip.ZipFile;
54
55 import javax.json.Json;
56 import javax.json.JsonArray;
57 import javax.json.JsonArrayBuilder;
58 import javax.json.JsonObject;
59 import javax.json.JsonObjectBuilder;
60 import javax.json.JsonReader;
61 import javax.json.JsonValue;
62 import javax.servlet.http.HttpServletRequest;
63 import javax.servlet.http.HttpServletResponse;
64
65 import org.apache.commons.compress.utils.IOUtils;
66 import org.apache.commons.fileupload.FileItem;
67 import org.apache.commons.fileupload.FileUploadException;
68 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
69 import org.apache.commons.fileupload.servlet.ServletFileUpload;
70 import org.apache.commons.io.FileUtils;
71 import org.apache.commons.lang.StringUtils;
72 import org.json.JSONArray;
73 import org.json.JSONObject;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.controller.PolicyController;
77 import org.onap.policy.rest.XACMLRestProperties;
78 import org.onap.policy.rest.adapter.PolicyRestAdapter;
79 import org.onap.policy.rest.dao.CommonClassDao;
80 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
81 import org.onap.policy.rest.jpa.MicroServiceModels;
82 import org.onap.policy.rest.jpa.PolicyEntity;
83 import org.onap.policy.rest.util.MSAttributeObject;
84 import org.onap.policy.rest.util.MSModelUtils;
85 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
86 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
87 import org.openecomp.portalsdk.core.web.support.JsonMessage;
88 import org.springframework.beans.factory.annotation.Autowired;
89 import org.springframework.http.MediaType;
90 import org.springframework.stereotype.Controller;
91 import org.springframework.web.bind.annotation.RequestMapping;
92 import org.springframework.web.servlet.ModelAndView;
93 import org.yaml.snakeyaml.Yaml;
94
95 import com.att.research.xacml.util.XACMLProperties;
96 import com.fasterxml.jackson.core.JsonProcessingException;
97 import com.fasterxml.jackson.databind.DeserializationFeature;
98 import com.fasterxml.jackson.databind.JsonNode;
99 import com.fasterxml.jackson.databind.ObjectMapper;
100 import com.fasterxml.jackson.databind.ObjectWriter;
101 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
102 import com.fasterxml.jackson.databind.node.ObjectNode;
103 import com.google.gson.Gson;
104
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
106 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
107 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
108 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
109 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
110 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
111 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
112
113 @Controller
114 @RequestMapping("/")
115 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
116         private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
117
118         private static CommonClassDao commonClassDao;
119         
120         public static CommonClassDao getCommonClassDao() {
121                 return commonClassDao;
122         }
123
124         public static void setCommonClassDao(CommonClassDao commonClassDao) {
125                 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
126         }
127
128         private MicroServiceModels newModel;
129         private String newFile;
130         private String directory;
131         private List<String> modelList = new ArrayList<>();
132         private List<String> dirDependencyList = new ArrayList<>();
133         private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
134         //Tosca Model related Datastructure. 
135         String referenceAttributes;
136         String attributeString;
137         String listConstraints;
138         String subAttributeString;
139         HashMap<String, Object> retmap = new HashMap<>();
140         Set<String> uniqueKeys= new HashSet<>();
141         Set<String> uniqueDataKeys= new HashSet<>();
142         StringBuilder dataListBuffer=new StringBuilder();
143         List<String> dataConstraints= new ArrayList <>();
144         
145         public static final String DATATYPE  = "data_types.policy.data.";
146         public static final String PROPERTIES=".properties.";
147         public static final String TYPE=".type";
148         public static final String STRING="string";
149         public static final String INTEGER="integer";
150         public static final String LIST="list";
151         public static final String DEFAULT=".default";
152         public static final String REQUIRED=".required";
153         public static final String MANYFALSE=":MANY-false";
154         
155         
156         @Autowired
157         private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
158                 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
159         }
160
161         public CreateDcaeMicroServiceController(){}
162
163         protected PolicyRestAdapter policyAdapter = null;
164         private int priorityCount; 
165         private Map<String, String> attributesListRefMap =  new HashMap<>();
166         private Map<String, LinkedList<String>> arrayTextList =  new HashMap<>();
167
168         public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
169                 
170                 String jsonContent = null;
171                 try{
172                         LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
173                         
174                         String tempJson = root.get("policyJSON").toString();
175                         
176                         //---replace empty value with the value below before calling decodeContent method.
177                         String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
178                         LOGGER.info("dummyValue:" + dummyValue);
179                         tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
180                         ObjectMapper mapper = new ObjectMapper();
181                         JsonNode tempJsonNode = mapper.readTree(tempJson);
182                         jsonContent = decodeContent(tempJsonNode).toString();
183                         constructJson(policyData, jsonContent, dummyValue);
184                 }catch(Exception e){
185                         LOGGER.error("Error while decoding microservice content", e);
186                 }
187                 
188                 return policyData;
189         }
190         
191         private GroupPolicyScopeList getPolicyObject(String policyScope) {
192                 GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
193                 return groupList;
194         }
195         
196         private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
197                 ObjectWriter om = new ObjectMapper().writer();
198                 String json="";
199                 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
200                 MicroServiceModels returnModel = new MicroServiceModels();
201                 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
202                 if(policyAdapter.getServiceType() !=null){
203                         microServiceObject.setService(policyAdapter.getServiceType());
204                         microServiceObject.setVersion(policyAdapter.getVersion());
205                         returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
206                 }
207                 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
208                         if(policyAdapter.getUuid()!=null){
209                                 microServiceObject.setUuid(policyAdapter.getUuid());
210                         }
211                         if(policyAdapter.getLocation()!=null){
212                                 microServiceObject.setLocation(policyAdapter.getLocation());
213                         } 
214                         if(policyAdapter.getConfigName()!=null){
215                                 microServiceObject.setConfigName(policyAdapter.getConfigName());
216                         }
217                         GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
218                         if(policyScopeValue!=null){
219                                 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());     
220                         }
221                 }
222                 
223                 if(policyAdapter.getPolicyName()!=null){
224                         microServiceObject.setPolicyName(policyAdapter.getPolicyName());
225                 }
226                 if(policyAdapter.getPolicyDescription()!=null){
227                         microServiceObject.setDescription(policyAdapter.getPolicyDescription());
228                 }
229                 if (policyAdapter.getPriority()!=null){
230                         microServiceObject.setPriority(policyAdapter.getPriority());
231                 }else {
232                         microServiceObject.setPriority("9999");
233                 }
234                 
235                 if (policyAdapter.getRiskLevel()!=null){
236                         microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
237                 }
238                 if (policyAdapter.getRiskType()!=null){
239                         microServiceObject.setRiskType(policyAdapter.getRiskType());
240                 }
241                 if (policyAdapter.getGuard()!=null){
242                         microServiceObject.setGuard(policyAdapter.getGuard());
243                 }
244                 microServiceObject.setContent(jsonContent);
245                 
246                 try {
247                         json = om.writeValueAsString(microServiceObject);
248                 } catch (JsonProcessingException e) {
249                         LOGGER.error("Error writing out the object", e);
250                 }
251                 LOGGER.info("input json: " + json);
252                 LOGGER.info("input jsonContent: " + jsonContent);
253                 String cleanJson = cleanUPJson(json);
254         //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
255                 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""},  new String[]{"\"\""});
256                 LOGGER.info("tempJson: " + tempJson);
257                 cleanJson = removeNullAttributes(tempJson);
258                 policyAdapter.setJsonBody(cleanJson);
259                 return policyAdapter;
260         }
261         
262         private String removeNullAttributes(String cleanJson) {
263                 ObjectMapper mapper = new ObjectMapper();
264
265                 try {
266                         JsonNode rootNode = mapper.readTree(cleanJson);
267                         JsonNode returnNode = mapper.readTree(cleanJson);
268                         Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
269                         boolean remove = false;
270                         JsonObject removed = null;
271                         boolean contentChanged = false;
272                         while (fieldsIterator.hasNext()) {
273                                 Map.Entry<String, JsonNode> field = fieldsIterator.next();
274                                 final String key = field.getKey();
275                                 final JsonNode value = field.getValue();
276                                 if("content".equalsIgnoreCase(key)){
277                                         String contentStr = value.toString();
278                                         try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
279                                 JsonObject jsonContent = reader.readObject();                 
280                                                         removed = removeNull(jsonContent);
281                                                         if(!jsonContent.toString().equals(removed.toString())){
282                                                         contentChanged = true;  
283                                                 }
284                     }
285
286                                         if  (value==null || value.isNull()){
287                                                 ((ObjectNode) returnNode).remove(key);
288                                                 remove = true;
289                                         }
290                                 }
291                                 if (remove){
292                                         cleanJson = returnNode.toString();
293                                 }
294                                 if  (value==null || value.isNull()){
295                                         ((ObjectNode) returnNode).remove(key);
296                                         remove = true;
297                                 }
298                         }
299                         if (remove){
300                                 cleanJson = returnNode.toString();
301                         }
302                         
303                         if(contentChanged){
304                                 //set modified content to cleanJson
305                                 JSONObject  jObject  =  new JSONObject(cleanJson);      
306                                 jObject.put("content",removed.toString());
307                                 cleanJson = cleanUPJson(jObject.toString());
308                         }
309                         
310                 } catch (IOException e) {
311                         LOGGER.error("Error writing out the JsonNode",e);
312                 }
313                 return cleanJson;
314         }
315         
316         public static JsonArray removeNull(JsonArray array) {
317             JsonArrayBuilder builder = Json.createArrayBuilder();
318             int i = 0;
319             for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
320                 JsonValue value = it.next();
321                 switch (value.getValueType()) {
322                 case ARRAY:
323                     JsonArray a = removeNull(array.getJsonArray(i));
324                     if (!a.isEmpty())
325                         builder.add(a);
326                     break;
327                 case OBJECT:
328                     JsonObject object = removeNull(array.getJsonObject(i));
329                     if (!object.isEmpty())
330                         builder.add(object);
331                     break;
332                 case STRING:
333                     String s = array.getString(i);
334                     if (s != null && !s.isEmpty())
335                         builder.add(s);
336                     break;
337                 case NUMBER:
338                     builder.add(array.getJsonNumber(i));
339                     break;
340                 case TRUE:
341                 case FALSE:
342                     builder.add(array.getBoolean(i));
343                     break;
344                 case NULL:
345                     break;
346                 }
347             }
348             return builder.build();
349         }
350
351         public static JsonObject removeNull(JsonObject obj) {
352             JsonObjectBuilder builder = Json.createObjectBuilder();
353             for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
354                 Entry<String, JsonValue> e = it.next();
355                 String key = e.getKey();
356                 JsonValue value = e.getValue();
357                 switch (value.getValueType()) {
358                 case ARRAY:
359                     JsonArray array = removeNull(obj.getJsonArray(key));
360                     if (!array.isEmpty())
361                         builder.add(key, array);
362                     break;
363                 case OBJECT:
364                     JsonObject object = removeNull(obj.getJsonObject(key));
365                     if (!object.isEmpty())
366                         builder.add(key, object);
367                     break;
368                 case STRING:
369                     String s = obj.getString(key);
370                     if (s != null && !s.isEmpty())
371                         builder.add(key, s);
372                     break;
373                 case NUMBER:
374                     builder.add(key, obj.getJsonNumber(key));
375                     break;
376                 case TRUE:
377                 case FALSE:
378                     builder.add(key, obj.getBoolean(key));
379                     break;
380                 case NULL:
381                     break;
382                 }
383             }
384             return builder.build();
385         }
386         
387         // Second index of dot should be returned. 
388         public int stringBetweenDots(String str){
389                 String stringToSearch=str;
390                 String[]ss=stringToSearch.split("\\.");
391                 if(ss!=null){
392                         int len= ss.length;
393                         if(len>2){
394                                 uniqueKeys.add(ss[2]);
395                         }
396                 }
397                 
398                 return uniqueKeys.size();
399         }
400         
401         public void stringBetweenDotsForDataFields(String str){
402                 String stringToSearch=str;
403                 String[]ss=stringToSearch.split("\\.");
404                 if(ss!=null){
405                         int len= ss.length;
406
407                         if(len>2){
408                                 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
409                         }
410                 }
411         }
412         
413  
414         @SuppressWarnings("unchecked")
415         public Map<String, String> load(String fileName) throws IOException { 
416                 File newConfiguration = new File(fileName);
417                 Yaml yaml = new Yaml();
418                 Map<Object, Object> yamlMap = null;
419                 try(InputStream is = new FileInputStream(newConfiguration)){
420                         yamlMap = (Map<Object, Object>) yaml.load(is); 
421                 } catch (FileNotFoundException e) {
422                         LOGGER.error(e);
423                 }
424
425                 StringBuilder sb = new StringBuilder(); 
426                 Map<String, String> settings = new HashMap<>(); 
427                 if (yamlMap == null) { 
428                         return settings; 
429                 } 
430                 List<String> path = new ArrayList <>(); 
431                 serializeMap(settings, sb, path, yamlMap); 
432                 return settings; 
433         } 
434
435         public Map<String, String> load(byte[] source) throws IOException { 
436                 Yaml yaml = new Yaml(); 
437                 @SuppressWarnings("unchecked")
438                 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source)); 
439                 StringBuilder sb = new StringBuilder(); 
440                 Map<String, String> settings = new HashMap <>(); 
441                 if (yamlMap == null) { 
442                         return settings; 
443                 } 
444                 List<String> path = new ArrayList <>(); 
445                 serializeMap(settings, sb, path, yamlMap); 
446                 return settings; 
447         } 
448
449         @SuppressWarnings({ "unchecked", "rawtypes" })
450         private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) { 
451                 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) { 
452                         if (entry.getValue() instanceof Map) { 
453                                 path.add((String) entry.getKey()); 
454                                 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue()); 
455                                 path.remove(path.size() - 1); 
456                         } else if (entry.getValue() instanceof List) { 
457                                 path.add((String) entry.getKey()); 
458                                 serializeList(settings, sb, path, (List) entry.getValue()); 
459                                 path.remove(path.size() - 1); 
460                         } else { 
461                                 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); 
462                         } 
463                 } 
464         } 
465
466         @SuppressWarnings("unchecked")
467         private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) { 
468                 int counter = 0; 
469                 for (Object listEle : yamlList) { 
470                         if (listEle instanceof Map) { 
471                                 path.add(Integer.toString(counter)); 
472                                 serializeMap(settings, sb, path, (Map<Object, Object>) listEle); 
473                                 path.remove(path.size() - 1); 
474                         } else if (listEle instanceof List) { 
475                                 path.add(Integer.toString(counter)); 
476                                 serializeList(settings, sb, path, (List<String>) listEle); 
477                                 path.remove(path.size() - 1); 
478                         } else { 
479                                 serializeValue(settings, sb, path, Integer.toString(counter), listEle); 
480                         } 
481                         counter++; 
482                 } 
483         } 
484
485         private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) { 
486                 if (value == null) { 
487                         return; 
488                 } 
489                 sb.setLength(0); 
490                 for (String pathEle : path) { 
491                         sb.append(pathEle).append('.'); 
492                 } 
493                 sb.append(name); 
494                 settings.put(sb.toString(), value.toString()); 
495         } 
496     
497         void parseDataAndPolicyNodes(Map<String,String> map){
498                 for(String key:map.keySet()){
499                         if(key.contains("policy.nodes.Root"))
500                         {
501                                 continue;
502                         }
503                         else if(key.contains("policy.nodes")){
504                                 String wordToFind = "policy.nodes.";
505                                 int indexForPolicyNode=key.indexOf(wordToFind);
506                                 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
507
508                                 stringBetweenDots(subNodeString);
509                         }
510                         else if(key.contains("policy.data")){
511                                 String wordToFind="policy.data.";
512                                 int indexForPolicyNode=key.indexOf(wordToFind);
513                                 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
514
515                                 stringBetweenDotsForDataFields(subNodeString);
516                         }
517                 }
518         }
519         
520         HashMap<String,String> parseDataNodes(Map<String,String> map){
521                 HashMap<String,String> dataMapForJson=new HashMap <>(); 
522                 for(String uniqueDataKey: uniqueDataKeys){
523                         if(uniqueDataKey.contains("%")){
524                                 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
525                                 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
526                                 String typeValue=map.get(findType);
527                                 LOGGER.info(typeValue);
528                                 if(typeValue != null && typeValue.equalsIgnoreCase(STRING)||
529                                                 typeValue.equalsIgnoreCase(INTEGER)
530                                   )
531                                 {
532                                         String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
533                                         String defaultValue= map.get(findDefault);
534                                         LOGGER.info("defaultValue is:"+ defaultValue);
535                                         
536                                         String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
537                                         String requiredValue= map.get(findRequired);
538                                         LOGGER.info("requiredValue is:"+ requiredValue);
539                                         
540                                         StringBuilder attributeIndividualStringBuilder= new StringBuilder();
541                                         attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
542                                         attributeIndividualStringBuilder.append(defaultValue+":required-");
543                                         attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
544                                         dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());         
545                                 }
546                                 else if(typeValue != null && typeValue.equalsIgnoreCase(LIST)){
547                                         String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
548                                         String listValue=map.get(findList);
549                                         if(listValue!=null){
550                                                 LOGGER.info("Type of list is:"+ listValue);
551                                                 //Its userdefined
552                                                 if(listValue.contains(".")){
553                                                         String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
554                                                         StringBuilder referenceIndividualStringBuilder= new StringBuilder();
555                                                         referenceIndividualStringBuilder.append(trimValue+":MANY-true");
556                                                         dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
557                                                 }//Its string
558                                                 else{
559                                                         StringBuilder stringListItems= new StringBuilder();
560                                                         stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
561                                                         dataMapForJson.put(uniqueDataKey, stringListItems.toString());
562                                                         dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
563                                                         for(int i=0;i<10;i++){
564                                                                 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
565                                                                 String constraintsValue=map.get(findConstraints);
566                                                                 LOGGER.info(constraintsValue);
567                                                                 if(constraintsValue==null){
568                                                                         break;
569                                                                 }
570                                                                 else{
571                                                                         dataConstraints.add(constraintsValue);
572                                                                         dataListBuffer.append(constraintsValue+",");
573                                                                 }
574                                                         }
575                                                         dataListBuffer.append("]#");
576                                                         
577                                                         LOGGER.info(dataListBuffer);
578                                                 }
579                                         }
580                                 }
581                                 else{
582                                         String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
583                                         String userDefinedValue=map.get(findUserDefined);
584                                         String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
585                                         StringBuilder referenceIndividualStringBuilder= new StringBuilder();
586                                         referenceIndividualStringBuilder.append(trimValue+":MANY-false");
587                                         dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
588                                         
589                                 }
590                         }
591                 }
592                 return dataMapForJson;
593         }
594         
595         void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
596                 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
597                 HashMap<String,String> hmSub;
598                 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
599                         String uniqueDataKey= entry.getKey();
600                         String[] uniqueDataKeySplit=uniqueDataKey.split("%");
601                         String value= dataMapForJson.get(uniqueDataKey);
602                         if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
603                                 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
604                                 hmSub.put(uniqueDataKeySplit[1], value);
605                         }
606                         else{
607                                 hmSub=new HashMap <>();
608                                 hmSub.put(uniqueDataKeySplit[1], value);
609                         }
610                                 
611                         dataMapKey.put(uniqueDataKeySplit[0], hmSub);
612                 }
613                                 
614                 JSONObject mainObject= new JSONObject();
615                 JSONObject json;
616                 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
617                         String s=entry.getKey();
618                         json= new JSONObject();
619                         HashMap<String,String> jsonHm=dataMapKey.get(s);
620                         for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
621                                 String key=entryMap.getKey();
622                                 json.put(key, jsonHm.get(key));
623                         }
624                         mainObject.put(s,json);
625                 }       
626                 Iterator<String> keysItr = mainObject.keys();
627                 while(keysItr.hasNext()) {
628                         String key = keysItr.next();
629                         String value = mainObject.get(key).toString();
630                         retmap.put(key, value);
631                 }
632                 
633                 LOGGER.info("#############################################################################");
634                 LOGGER.info(mainObject);
635                 LOGGER.info("###############################################################################"); 
636         }
637         
638         
639         HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
640                 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
641                 for(String uniqueKey: uniqueKeys){
642                         HashMap<String,String> hm;
643
644                         for(Map.Entry<String,String> entry:map.entrySet()){
645                                 String key=entry.getKey();
646                                 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
647                                         if(mapKey.containsKey(uniqueKey)){
648                                                 hm = mapKey.get(uniqueKey);
649                                                 String keyStr= key.substring(key.lastIndexOf('.')+1);
650                                                 String valueStr= map.get(key);
651                                                 if(("type").equals(keyStr)){
652                                                         if(!key.contains("entry_schema"))
653                                                         {
654                                                                 hm.put(keyStr,valueStr);
655                                                         }
656                                                 }else{
657                                                         hm.put(keyStr,valueStr);
658                                                 }
659
660                                         } else {
661                                                 hm = new HashMap <>();
662                                                 String keyStr= key.substring(key.lastIndexOf('.')+1);
663                                                 String valueStr= map.get(key);
664                                                 if(("type").equals(keyStr)){
665                                                         if(!key.contains("entry_schema"))
666                                                         {
667                                                                 hm.put(keyStr,valueStr);
668                                                         }
669                                                 }else{
670                                                         hm.put(keyStr,valueStr);
671                                                 }
672                                                 mapKey.put(uniqueKey, hm);
673                                         }
674                                 }
675                         }
676                 }
677                 return mapKey;
678         }
679
680         void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
681                 StringBuilder attributeStringBuilder= new StringBuilder();
682                 StringBuilder referenceStringBuilder= new StringBuilder();
683                 StringBuilder listBuffer= new StringBuilder();
684                 List<String> constraints= new ArrayList<>();
685                 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
686                         String keySetString= entry.getKey();
687                         HashMap<String,String> keyValues=mapKey.get(keySetString);
688                         if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(STRING)||
689                                         keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(INTEGER)
690                                         ){
691                                 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
692                                 attributeIndividualStringBuilder.append(keySetString+"=");
693                                 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
694                                 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
695                                 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
696                                 attributeStringBuilder.append(attributeIndividualStringBuilder+",");    
697
698                         }
699                         else if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(LIST)){
700                                 //List Datatype
701                                 Set<String> keys= keyValues.keySet();
702                                 Iterator<String> itr=keys.iterator();
703                                 while(itr.hasNext()){
704                                         String key= itr.next();
705                                         if((!("type").equals(key) ||("required").equals(key)))
706                                         {
707                                                 String value= keyValues.get(key);
708                                                 //The "." in the value determines if its a string or a user defined type.  
709                                                 if (!value.contains(".")){
710                                                         //This is string
711                                                         constraints.add(keyValues.get(key));
712                                                 }else{
713                                                         //This is userdefined string
714                                                         String trimValue=value.substring(value.lastIndexOf('.')+1);
715                                                         StringBuilder referenceIndividualStringBuilder= new StringBuilder();
716                                                         referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
717                                                         referenceStringBuilder.append(referenceIndividualStringBuilder+",");
718                                                 }
719                                         }
720                                 }
721
722                         }else{
723                                 //User defined Datatype. 
724                                 String value=keyValues.get("type");
725                                 if(value != null && !value.isEmpty()){
726                                         String trimValue=value.substring(value.lastIndexOf('.')+1);
727                                         StringBuilder referenceIndividualStringBuilder= new StringBuilder();
728                                         referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
729                                         referenceStringBuilder.append(referenceIndividualStringBuilder+",");
730                                 }else{
731                                         LOGGER.info("keyValues.get(type) is null/empty");
732                                 }
733
734                         }
735                         if(constraints!=null &&constraints.isEmpty()==false){
736                                 //List handling. 
737                                 listBuffer.append(keySetString.toUpperCase()+"=[");
738                                 for(String str:constraints){
739                                         listBuffer.append(str+",");
740                                 }
741                                 listBuffer.append("]#");
742                                 LOGGER.info(listBuffer);
743
744
745                                 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
746                                 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
747                                 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
748                                 constraints.clear();
749                         }
750                 }
751                 
752                 dataListBuffer.append(listBuffer);
753                 
754
755                 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
756                 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);       
757                 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
758                 LOGGER.info("List String is:"+listBuffer);
759                 LOGGER.info("Data list buffer is:"+dataListBuffer);
760                 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
761                 
762                 this.listConstraints=dataListBuffer.toString();
763                 this.referenceAttributes=referenceStringBuilder.toString();
764                 this.attributeString=attributeStringBuilder.toString();
765         }
766         
767         
768     
769         public void parseTosca (String fileName){
770                 Map<String,String> map= new HashMap<>();
771     
772         try {
773                         map=load(fileName);
774                         
775                         parseDataAndPolicyNodes(map);
776                         
777                         HashMap<String,String> dataMapForJson=parseDataNodes(map);
778                         
779                         constructJsonForDataFields(dataMapForJson);     
780                         
781                         HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
782                         
783                         createAttributes(mapKey);
784                 
785         } catch (IOException e) {
786                 LOGGER.error(e);
787         }
788         
789         } 
790
791         private String cleanUPJson(String json) {
792                 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
793                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
794                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
795                 
796                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
797                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
798                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
799                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
800                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
801                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
802                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
803                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
804                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
805                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
806                 return cleanJson;
807         }
808         
809         private JSONObject decodeContent(JsonNode jsonNode){
810                 Iterator<JsonNode> jsonElements = jsonNode.elements();
811                 Iterator<String> jsonKeys = jsonNode.fieldNames();
812                 Map<String,String> element = new TreeMap<>();
813                 while(jsonElements.hasNext() && jsonKeys.hasNext()){
814                         element.put(jsonKeys.next(), jsonElements.next().toString());
815                 }
816                 JSONObject jsonResult = new JSONObject();
817                 JSONArray jsonArray = null;
818                 String oldValue = null;
819                 String nodeKey = null;
820                 String arryKey = null;
821                 Boolean isArray = false;
822                 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
823                 ObjectNode node = nodeFactory.objectNode();
824                 String prevKey = null;
825                 String presKey = null;
826                 for(String key: element.keySet()){
827                         if(key.contains(".")){
828                                 presKey = key.substring(0,key.indexOf("."));
829                         }else if(key.contains("@")){
830                                 presKey = key.substring(0,key.indexOf("@"));
831                         }else{
832                                 presKey = key;
833                         }
834                         // first check if we are different from old.
835                         LOGGER.info(key+"\n");
836                         if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
837                                 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
838                                         jsonResult.put(oldValue, jsonArray);
839                                         jsonArray = new JSONArray();
840                                 }
841                         }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ 
842                                 jsonResult.put(oldValue, jsonArray);
843                                 isArray = false;
844                                 jsonArray = new JSONArray();
845                         }
846         
847                         prevKey = presKey;
848                         // 
849                         if(key.contains(".")){
850                                 if(nodeKey==null){
851                                         nodeKey = key.substring(0,key.indexOf("."));
852                                 }
853                                 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
854                                         node.put(key.substring(key.indexOf(".")+1), element.get(key));
855                                 }else{
856                                         if(node.size()!=0){
857                                                 if(nodeKey.contains("@")){
858                                                         if(arryKey==null){
859                                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
860                                                         }
861                                                         if(nodeKey.endsWith("@0")){
862                                                                 isArray = true;
863                                                                 jsonArray = new JSONArray();
864                                                         }
865                                                         if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
866                                                                 jsonArray.put(decodeContent(node));
867                                                         } 
868                                                         if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){
869                                                                 jsonResult.put(arryKey, jsonArray);
870                                                                 jsonArray = new JSONArray();
871                                                         }
872                                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
873                                                 }else{
874                                                         isArray = false;
875                                                         jsonResult.put(nodeKey, decodeContent(node));
876                                                 }
877                                                 node = nodeFactory.objectNode();
878                                         }
879                                         nodeKey = key.substring(0,key.indexOf("."));
880                                         if(nodeKey.contains("@")){
881                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
882                                         }
883                                         node.put(key.substring(key.indexOf(".")+1), element.get(key));
884                                 }
885                         }else if(node.size()!=0){
886                                 if(nodeKey.contains("@")){
887                                         if(arryKey==null){
888                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
889                                         }
890                                         if(nodeKey.endsWith("@0")){
891                                                 isArray = true;
892                                                 jsonArray = new JSONArray();
893                                         }
894                                         if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
895                                                 jsonArray.put(decodeContent(node));
896                                         }
897                                         jsonResult.put(arryKey, jsonArray);
898                                         jsonArray = new JSONArray();
899                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
900                                 }else{
901                                         isArray = false;
902                                         jsonResult.put(nodeKey, decodeContent(node));
903                                 }
904                                 node = nodeFactory.objectNode();
905                                 if(key.contains("@")){
906                                         isArray = true;
907                                         if(key.endsWith("@0")|| jsonArray==null){
908                                                 jsonArray = new JSONArray();
909                                         }
910                                 }else if(!key.contains("@")){
911                                         isArray = false;
912                                 }
913                                 if(isArray){
914                                         if(oldValue==null){
915                                                 oldValue = key.substring(0,key.indexOf("@"));
916                                         }
917                                         if(oldValue!=prevKey){
918                                                 oldValue = key.substring(0,key.indexOf("@"));
919                                         }
920                                         if(oldValue.equals(key.substring(0,key.indexOf("@")))){
921                                                 jsonArray.put(element.get(key));
922                                         }else{
923                                                 jsonResult.put(oldValue, jsonArray);
924                                                 jsonArray = new JSONArray();
925                                         }
926                                         oldValue = key.substring(0,key.indexOf("@"));
927                                 }else{
928                                         jsonResult.put(key, element.get(key));
929                                 }
930                         }else{
931                                 if(key.contains("@")){
932                                         isArray = true;
933                                         if(key.endsWith("@0")|| jsonArray==null){
934                                                 jsonArray = new JSONArray();
935                                         }
936                                 }else if(!key.contains("@")){
937                                         isArray = false;
938                                 }
939                                 if(isArray){
940                                         if(oldValue==null){
941                                                 oldValue = key.substring(0,key.indexOf("@"));
942                                         }
943                                         if(oldValue!=prevKey){
944                                                 oldValue = key.substring(0,key.indexOf("@"));
945                                         }
946                                         if(oldValue.equals(key.substring(0,key.indexOf("@")))){
947                                                 jsonArray.put(element.get(key));
948                                         }else{
949                                                 jsonResult.put(oldValue, jsonArray);
950                                                 jsonArray = new JSONArray();
951                                         }
952                                         oldValue = key.substring(0,key.indexOf("@"));
953                                 }else{
954                                         jsonResult.put(key, element.get(key));
955                                 }
956                         }
957                 }
958                 if(node.size()>0){
959                         if(nodeKey.contains("@")){
960                                 if(jsonArray==null){
961                                         jsonArray = new JSONArray();
962                                 }
963                                 if(arryKey==null){
964                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
965                                 }
966                                 jsonArray.put(decodeContent(node));
967                                 jsonResult.put(arryKey, jsonArray);
968                                 isArray = false;
969                         }else{
970                                 jsonResult.put(nodeKey, decodeContent(node));
971                         }
972                 }
973                 if(isArray && jsonArray.length() > 0){
974                         jsonResult.put(oldValue, jsonArray);
975                 }
976                 return jsonResult;
977         }
978         
979         @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
980         public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
981                 ObjectMapper mapper = new ObjectMapper();
982                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
983                 JsonNode root = mapper.readTree(request.getReader());
984
985                 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
986                 String  servicename = value.toString().split("-v")[0];
987                 String version = null;
988                 if (value.toString().contains("-v")){
989                         version = value.toString().split("-v")[1];
990                 }
991                 MicroServiceModels returnModel = getAttributeObject(servicename, version);
992                 
993                 
994                 //get all keys with "MANY-true" defined in their value from subAttribute
995                 Set<String> allkeys = null;
996                 if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
997                         JSONObject json = new JSONObject(returnModel.getSub_attributes());              
998                         allkeys = getAllKeys(json);
999                         LOGGER.info("allkeys : " + allkeys);
1000                 }
1001                 
1002                 String allManyTrueKeys = "";
1003                 if(allkeys != null){
1004                         allManyTrueKeys = allkeys.toString();
1005                 }
1006                 
1007                 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
1008                 
1009                 JSONObject jsonObject = new JSONObject(jsonModel);
1010                 
1011                 JSONObject finalJsonObject = null;
1012                 if(allkeys != null){
1013                         Iterator<String> iter = allkeys.iterator();
1014                         while(iter.hasNext()){
1015                                 //convert to array values for MANY-true keys
1016                                 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
1017                         }
1018                 }
1019
1020                 if(finalJsonObject != null){
1021                     LOGGER.info(finalJsonObject.toString());
1022                     jsonModel  = finalJsonObject.toString();
1023                 }
1024                 
1025                 //get all properties with "MANY-true" defined in Ref_attributes
1026                 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
1027                 if(manyTrueProperties != null){
1028                         JSONObject jsonObj = new JSONObject(jsonModel);
1029                         for (String s : manyTrueProperties) {
1030                                 LOGGER.info(s);
1031                                 //convert to array element for MANY-true properties
1032                                 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
1033                         }
1034                         
1035                         if(finalJsonObject != null){
1036                             LOGGER.info(finalJsonObject.toString());
1037                             jsonModel  = finalJsonObject.toString();
1038                         }
1039                 }
1040                 
1041                 response.setCharacterEncoding("UTF-8");
1042                 response.setContentType("application / json");
1043                 request.setCharacterEncoding("UTF-8");
1044                 List<Object>  list = new ArrayList<>();
1045                 PrintWriter out = response.getWriter();
1046                 String responseString = mapper.writeValueAsString(returnModel);
1047                 JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+ "}");
1048                 list.add(j);
1049                 out.write(list.toString());
1050                 return null;
1051         }
1052         
1053         @SuppressWarnings({ "unchecked", "rawtypes" })
1054         private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
1055                 Map<String, String> attributeMap = new HashMap<>();
1056                 Map<String, String> refAttributeMap = new HashMap<>();
1057                 String attribute = returnModel.getAttributes();
1058                 if(attribute != null){
1059                         attribute = attribute.trim();
1060                 }
1061                 String refAttribute = returnModel.getRef_attributes();
1062                 if(refAttribute != null){
1063                         refAttribute = refAttribute.trim();
1064                 }
1065                 String enumAttribute = returnModel.getEnumValues();
1066                 if(enumAttribute != null){
1067                         enumAttribute = enumAttribute.trim();
1068                 }
1069                 if (!StringUtils.isEmpty(attribute)){
1070                         attributeMap = convert(attribute, ",");
1071                 }
1072                 if (!StringUtils.isEmpty(refAttribute)){
1073                         refAttributeMap = convert(refAttribute, ",");
1074                 }
1075
1076                 Gson gson = new Gson();
1077                 
1078                 String subAttributes = returnModel.getSub_attributes();
1079                 if(subAttributes != null){
1080                         subAttributes = subAttributes.trim();
1081                 }else{
1082                         subAttributes = "";
1083                 }
1084                 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1085                 
1086                 JSONObject object = new JSONObject();
1087                 JSONArray array = new JSONArray();
1088                 
1089                 for (Entry<String, String> keySet : attributeMap.entrySet()){
1090                         array = new JSONArray();
1091                         String value = keySet.getValue();
1092                         if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1093                                 array.put(value);
1094                                 object.put(keySet.getKey().trim(), array);
1095                         }else {
1096                                 object.put(keySet.getKey().trim(), value.trim());
1097                         }
1098                 }
1099                 
1100                 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1101                         array = new JSONArray();
1102                         String value = keySet.getValue().split(":")[0];
1103                         if (gsonObject.containsKey(value)){
1104                                 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1105                                         array.put(recursiveReference(value, gsonObject, enumAttribute));
1106                                         object.put(keySet.getKey().trim(), array);
1107                                 }else {
1108                                         object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1109                                 }
1110                         }else {
1111                                 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1112                                         array.put(value.trim());
1113                                         object.put(keySet.getKey().trim(), array);
1114                                 }else {
1115                                         object.put(keySet.getKey().trim(), value.trim()); 
1116                                 }
1117                         }
1118                 }
1119                 
1120                 
1121
1122                 return object.toString();
1123         }
1124
1125         @SuppressWarnings("unchecked")
1126         private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1127                 JSONObject object = new JSONObject();
1128                 Map<String, String> map = new HashMap<>();
1129                 Object returnClass = subAttributeMap.get(name);
1130                 map = (Map<String, String>) returnClass; 
1131                 JSONArray array = new JSONArray();
1132                 
1133                 for( Entry<String, String> m:map.entrySet()){  
1134                         String[] splitValue = m.getValue().split(":");
1135                         array = new JSONArray();
1136                         if (subAttributeMap.containsKey(splitValue[0])){
1137                                 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1138                                         array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1139                                         object.put(m.getKey().trim(), array);
1140                                 }else {
1141                                         object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1142                                 }
1143                         } else{
1144                                 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1145                                         array.put(splitValue[0].trim());
1146                                         object.put(m.getKey().trim(), array);
1147                                 }else {
1148                                         object.put(m.getKey().trim(), splitValue[0].trim());
1149                                 }
1150                         }
1151                   }  
1152                 
1153                 return object;
1154         }
1155         
1156         //call this method to check if the key is in the many-true key set 
1157         private boolean isKeyFound(Set<String> allManyTruekeys, String key){
1158                 
1159              if(allManyTruekeys != null && key != null){
1160                 Iterator<String> iter = allManyTruekeys.iterator();
1161                 while(iter.hasNext()){
1162                         if(key.equals(iter.next())){
1163                                 return true;
1164                         }
1165                 }
1166              }
1167                 return false;
1168         }
1169         
1170         public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1171             return convertToArrayElement(json, new HashSet<>(), keyValue);
1172         }
1173         
1174         private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1175             for (String key : json.keySet()) {
1176                 Object obj = json.get(key);
1177                 if(key.equals(keyValue.trim())){
1178                         if(!(obj instanceof JSONArray)){
1179                                 JSONArray newJsonArray = new JSONArray();
1180                                 newJsonArray.put(obj);
1181                                 json.put(key, newJsonArray);
1182                         }
1183                         LOGGER.info("key : " + key);
1184                         LOGGER.info("obj : " + obj);
1185                         LOGGER.info("json.get(key) : " + json.get(key));
1186                         LOGGER.info("keyValue : " + keyValue);
1187                     keys.addAll(json.keySet());
1188                     
1189                     return json;
1190                 }
1191
1192                 if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);            
1193             }
1194
1195             return json;
1196         }
1197         
1198         // call this method to get all MANY-true properties 
1199         public static Set<String> getManyTrueProperties(String referAttributes){
1200                 LOGGER.info("referAttributes : " + referAttributes);
1201                 Set<String> manyTrueProperties = new HashSet<>();
1202                 
1203                 if(referAttributes != null){
1204                         String[] referAarray = referAttributes.split(",");
1205                         String []element= null;
1206                         for(int i=0; i<referAarray.length; i++){
1207                                 element = referAarray[i].split("=");      
1208                                 if(element.length > 1 && element[1].contains("MANY-true")){
1209                                         manyTrueProperties.add(element[0]);
1210                                 }
1211                         }               
1212                 }
1213                 
1214                 return manyTrueProperties;
1215         }
1216         
1217         //call this method to start the recursive
1218         private Set<String> getAllKeys(JSONObject json) {
1219             return getAllKeys(json, new HashSet<>());
1220         }
1221
1222         private Set<String> getAllKeys(JSONArray arr) {
1223             return getAllKeys(arr, new HashSet<>());
1224         }
1225
1226         private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1227             for (int i = 0; i < arr.length(); i++) {
1228                 Object obj = arr.get(i);
1229                 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
1230                 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
1231             }
1232
1233             return keys;
1234         }
1235     // this method returns a set of keys with "MANY-true" defined in their value.
1236         private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1237             for (String key : json.keySet()) {
1238                 Object obj = json.get(key);
1239                 if(obj instanceof String && ((String) obj).contains("MANY-true")){
1240                         LOGGER.info("key : " + key);
1241                         LOGGER.info("obj : " + obj);
1242                     keys.addAll(json.keySet());
1243                 }
1244                 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
1245                 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
1246             }
1247
1248             return keys;
1249         }
1250
1251         
1252         @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1253         public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1254                 ObjectMapper mapper = new ObjectMapper();
1255                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1256                 JsonNode root = mapper.readTree(request.getReader());
1257
1258                 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1259                 String  servicename = value.toString().split("-v")[0];
1260                 Set<String> returnList = getVersionList(servicename);
1261                 
1262                 response.setCharacterEncoding("UTF-8");
1263                 response.setContentType("application / json");
1264                 request.setCharacterEncoding("UTF-8");
1265         List<Object>  list = new ArrayList<>();
1266                 PrintWriter out = response.getWriter();
1267                 String responseString = mapper.writeValueAsString(returnList);
1268                 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1269                 list.add(j);
1270                 out.write(list.toString());
1271                 return null;
1272         }
1273
1274         private Set<String> getVersionList(String name) {       
1275                 MicroServiceModels workingModel = new MicroServiceModels();
1276                 Set<String> list = new HashSet<>();
1277                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1278                 for (int i = 0; i < microServiceModelsData.size(); i++) {
1279                         workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1280                         if (workingModel.getVersion()!=null){
1281                                 list.add(workingModel.getVersion());
1282                         }else{
1283                                 list.add("Default");
1284                         }
1285                 }
1286                 return list;
1287         }
1288         
1289         private MicroServiceModels getAttributeObject(String name, String version) {    
1290                 MicroServiceModels workingModel = new MicroServiceModels();
1291                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1292                 for (int i = 0; i < microServiceModelsData.size(); i++) {
1293                         workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1294                         if(version != null){
1295                                 if (workingModel.getVersion()!=null){
1296                                         if (workingModel.getVersion().equals(version)){
1297                                                 return workingModel;
1298                                         }
1299                                 }else{
1300                                         return workingModel;
1301                                 }
1302                         }else{
1303                                 return workingModel;
1304                         }
1305                         
1306                 }
1307                 return workingModel;
1308         }
1309
1310         @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1311         public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1312                 try{
1313                         Map<String, Object> model = new HashMap<>();
1314                         ObjectMapper mapper = new ObjectMapper();
1315                         List<String> priorityList = new ArrayList<>();
1316                         priorityCount = 10;
1317                         for (int i = 1; i < priorityCount; i++) {
1318                                 priorityList.add(String.valueOf(i));
1319                         }
1320                         model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1321                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1322                         JSONObject j = new JSONObject(msg);
1323                         response.getWriter().write(j.toString());
1324                 }
1325                 catch (Exception e){
1326                         LOGGER.error(e);
1327                 }
1328         }
1329
1330         public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1331                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1332                         Object policyData = policyAdapter.getPolicyData();
1333                         PolicyType policy = (PolicyType) policyData;
1334                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1335                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1336                         policyAdapter.setPolicyName(policyNameValue);
1337                         String description = "";
1338                         try{
1339                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1340                         }catch(Exception e){
1341                             LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1342                                 description = policy.getDescription();
1343                         }
1344                         policyAdapter.setPolicyDescription(description);
1345                         // Get the target data under policy.
1346                         TargetType target = policy.getTarget();
1347                         if (target != null) {
1348                                 // Under target we have AnyOFType
1349                                 List<AnyOfType> anyOfList = target.getAnyOf();
1350                                 if (anyOfList != null) {
1351                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1352                                         while (iterAnyOf.hasNext()) {
1353                                                 AnyOfType anyOf = iterAnyOf.next();
1354                                                 // Under AnyOFType we have AllOFType
1355                                                 List<AllOfType> allOfList = anyOf.getAllOf();
1356                                                 if (allOfList != null) {
1357                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
1358                                                         while (iterAllOf.hasNext()) {
1359                                                                 AllOfType allOf = iterAllOf.next();
1360                                                                 // Under AllOFType we have Match
1361                                                                 List<MatchType> matchList = allOf.getMatch();
1362                                                                 if (matchList != null) {
1363                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
1364                                                                         while (matchList.size()>1 && iterMatch.hasNext()) {
1365                                                                                 MatchType match = iterMatch.next();
1366                                                                                 //
1367                                                                                 // Under the match we have attribute value and
1368                                                                                 // attributeDesignator. So,finally down to the actual attribute.
1369                                                                                 //
1370                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
1371                                                                                 String value = (String) attributeValue.getContent().get(0);
1372                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
1373                                                                                 String attributeId = designator.getAttributeId();
1374                                                                                 // First match in the target is OnapName, so set that value.
1375                                                                                 if (attributeId.equals("ONAPName")) {
1376                                                                                         policyAdapter.setOnapName(value);
1377                                                                                 }
1378                                                                                 if (attributeId.equals("ConfigName")){
1379                                                                                         policyAdapter.setConfigName(value);
1380                                                                                 }
1381                                                                                 if (attributeId.equals("uuid")){
1382                                                                                         policyAdapter.setUuid(value);
1383                                                                                 }
1384                                                                                 if (attributeId.equals("location")){
1385                                                                                         policyAdapter.setLocation(value);
1386                                                                                 }
1387                                                                                 if (attributeId.equals("RiskType")){
1388                                                                                         policyAdapter.setRiskType(value);
1389                                                                                 }
1390                                                                                 if (attributeId.equals("RiskLevel")){
1391                                                                                         policyAdapter.setRiskLevel(value);
1392                                                                                 }
1393                                                                                 if (attributeId.equals("guard")){
1394                                                                                         policyAdapter.setGuard(value);
1395                                                                                 }
1396                                                                                 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1397                                                                                         PolicyController controller = new PolicyController();
1398                                                                                         String newDate = controller.convertDate(value);
1399                                                                                         policyAdapter.setTtlDate(newDate);
1400                                                                                 }
1401                                                                         }
1402                                                                         readFile(policyAdapter, entity);
1403                                                                 }
1404                                                         }
1405                                                 }
1406                                         }
1407                                 }
1408                         }
1409                 }
1410         }
1411         
1412         public static Map<String, String> convert(String str, String split) {
1413                 Map<String, String> map = new HashMap<>();
1414                 for(final String entry : str.split(split)) {
1415                     String[] parts = entry.split("=");
1416                     map.put(parts[0], parts[1]);
1417                 }
1418                 return map;
1419         }
1420
1421
1422         @SuppressWarnings("unchecked")
1423         private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1424                 String policyScopeName = null;
1425                 ObjectMapper mapper = new ObjectMapper();
1426                 try {
1427                         DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1428                         policyScopeName = getPolicyScope(msBody.getPolicyScope());
1429                         policyAdapter.setPolicyScope(policyScopeName);
1430
1431                         policyAdapter.setPriority(msBody.getPriority());
1432
1433                         if (msBody.getVersion()!= null){
1434                                 policyAdapter.setServiceType(msBody.getService());
1435                                 policyAdapter.setVersion(msBody.getVersion());
1436                         }else{
1437                                 policyAdapter.setServiceType(msBody.getService());
1438                         }
1439                         if(msBody.getContent() != null){
1440                                 LinkedHashMap<String, Object>  data = new LinkedHashMap<>();
1441                                 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1442                                 readRecursivlyJSONContent(map, data);
1443                                 policyAdapter.setRuleData(data);
1444                         }
1445
1446                 } catch (Exception e) {
1447                         LOGGER.error(e);
1448                 }
1449
1450         }
1451
1452         @SuppressWarnings({ "rawtypes", "unchecked" })
1453         private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1454                 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1455                         Object key =  iterator.next();
1456                         Object value = map.get(key);
1457                         if(value instanceof LinkedHashMap<?, ?>){
1458                                 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>(); 
1459                                 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1460                                 for(String objKey: secondObjec.keySet()){
1461                                         data.put(key+"." +objKey, secondObjec.get(objKey));
1462                                 }
1463                         }else if(value instanceof ArrayList){
1464                                 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1465                                 for(int i = 0; i < jsonArrayVal.size(); i++){
1466                                         Object arrayvalue = jsonArrayVal.get(i);
1467                                         if(arrayvalue instanceof LinkedHashMap<?, ?>){
1468                                                 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();   
1469                                                 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1470                                                 for(String objKey: newData.keySet()){
1471                                                         data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1472                                                 }
1473                                         }else if(arrayvalue instanceof ArrayList){
1474                                                 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1475                                                 for(int j = 0; j < jsonArrayVal1.size(); j++){
1476                                                         Object arrayvalue1 = jsonArrayVal1.get(i);
1477                                                         data.put(key+"@"+j, arrayvalue1.toString());
1478                                                 }       
1479                                         }else{
1480                                                 data.put(key+"@"+i, arrayvalue.toString());
1481                                         }       
1482                                 }
1483                         }else{
1484                                 data.put(key.toString(), value.toString());
1485                         }       
1486                 }
1487         }
1488
1489         private String getPolicyScope(String value) {
1490                 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1491                 if(groupList != null && !groupList.isEmpty()){
1492                         GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1493                         return pScope.getGroupName();           
1494                 }
1495                 return null;
1496         }
1497
1498         //Convert the map values and set into JSON body
1499         public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1500                 Map<String, String> attribute = new HashMap<>();
1501                 String temp = null;
1502                 String key;
1503                 String value;
1504                 for (Entry<String, String> entry : attributesMap.entrySet()) {
1505                         key = entry.getKey();
1506                         value = entry.getValue();
1507                         attribute.put(key, value);
1508                 }
1509                 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1510                         key = entryRef.getKey();
1511                         value = entryRef.getValue().toString();
1512                         attribute.put(key, value);
1513                 }
1514                 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1515                         key = entryList.getKey();
1516                         value = entryList.getValue().toString();
1517                         attribute.put(key, value);
1518                 }
1519                 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1520                         key = arrayList.getKey();
1521                         temp = null;
1522                         for (Object textList : arrayList.getValue()){
1523                                 if (temp == null){
1524                                         temp = "[" + textList;
1525                                 }else{
1526                                         temp = temp + "," + textList;
1527                                 }
1528                         }
1529                         attribute.put(key, temp+ "]");                  
1530                 }
1531
1532                 return  attribute;
1533         }
1534         
1535         @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1536         public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1537                 modelList = new ArrayList<>();
1538                 dirDependencyList = new ArrayList<>();
1539                 classMap = new HashMap<>();
1540                 retmap = new HashMap<>();
1541                 uniqueKeys= new HashSet<>();
1542                 uniqueDataKeys= new HashSet<>();
1543                 dataListBuffer=new StringBuilder();
1544                 dataConstraints= new ArrayList <>();
1545                 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1546                 boolean zip = false;
1547                 boolean yml= false;
1548                 String errorMsg = "";
1549                 for (FileItem item : items) {
1550                         if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1551                                 this.newModel = new MicroServiceModels();
1552                                 try{
1553                                         File file = new File(item.getName());
1554                                         OutputStream outputStream = new FileOutputStream(file);
1555                                         IOUtils.copy(item.getInputStream(), outputStream);
1556                                         outputStream.close();
1557                                         this.newFile = file.toString();
1558                                         this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
1559                                 
1560                                         if (this.newFile.toString().contains("-v")){
1561                                                 if (item.getName().endsWith(".zip")){
1562                                                         this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
1563                                                         zip = true;
1564                                                 }else if(item.getName().endsWith(".yml")){
1565                                                         this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
1566                                                         yml = true;
1567                                                 }
1568                                                 else {
1569                                                         this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
1570                                                 }
1571                                         }else{
1572                                                 errorMsg = "Upload error: The file name should contain '-v', such as xxx-v1802.yml";
1573                                         }
1574                                 
1575                                 }catch(Exception e){
1576                                         LOGGER.error("Upload error : ", e);
1577                                         errorMsg = "Upload error:" + e.getMessage();
1578                                 }
1579                         }
1580                         
1581                 }
1582                 
1583                 if(!errorMsg.isEmpty()){
1584                         
1585                         PrintWriter out = response.getWriter();
1586                         
1587                         response.setCharacterEncoding("UTF-8");
1588                         response.setContentType("application / json");
1589                         request.setCharacterEncoding("UTF-8");
1590                         
1591                         ObjectMapper mapper = new ObjectMapper();
1592                         JSONObject j = new JSONObject();
1593                         j.put("errorMsg", errorMsg);
1594                         out.write(j.toString());
1595                         return;
1596                 }
1597                 
1598                 List<File> fileList = new ArrayList<>();;
1599                 this.directory = "model";
1600                 if (zip){
1601                         extractFolder(this.newFile);
1602                         fileList = listModelFiles(this.directory);
1603                 }else if (yml==true){
1604                         parseTosca(this.newFile);
1605                 }else {
1606                         File file = new File(this.newFile);
1607                         fileList.add(file);
1608                 }
1609                 String modelType= "";
1610                 if(yml==false){
1611                         modelType="xmi";
1612                         //Process Main Model file first
1613                         classMap = new HashMap<>();
1614                         for (File file : fileList) {
1615                                 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1616                         retreiveDependency(file.toString(), true);
1617                     }   
1618                         }
1619                         
1620                         modelList = createList();
1621                         
1622                         cleanUp(this.newFile);
1623                         cleanUp(directory);
1624                 }else{
1625                         modelType="yml";
1626                         modelList.add(this.newModel.getModelName());
1627                         String className=this.newModel.getModelName();
1628                         MSAttributeObject msAttributes= new MSAttributeObject();
1629                         msAttributes.setClassName(className);
1630                         
1631                         HashMap<String, String> returnAttributeList =new HashMap<>();
1632                         returnAttributeList.put(className, this.attributeString);
1633                         msAttributes.setAttribute(returnAttributeList);
1634                         
1635                         msAttributes.setSubClass(this.retmap);
1636                         
1637                         HashMap<String, String> returnReferenceList =new HashMap<>();
1638                         //String[] referenceArray=this.referenceAttributes.split("=");
1639                         returnReferenceList.put(className, this.referenceAttributes);
1640                         msAttributes.setRefAttribute(returnReferenceList);
1641                         
1642                         if(this.listConstraints!=""){
1643                                 HashMap<String, String> enumList =new HashMap<>();
1644                                 String[] listArray=this.listConstraints.split("#");
1645                 for(String str:listArray){
1646                     String[] strArr= str.split("=");
1647                     if(strArr.length>1){
1648                         enumList.put(strArr[0], strArr[1]);
1649                     }
1650                 }
1651                                 msAttributes.setEnumType(enumList);
1652                         }
1653                         
1654                         classMap=new HashMap<>();
1655                         classMap.put(className, msAttributes);
1656                         
1657                 }
1658                 
1659                 PrintWriter out = response.getWriter();
1660                 
1661                 response.setCharacterEncoding("UTF-8");
1662                 response.setContentType("application / json");
1663                 request.setCharacterEncoding("UTF-8");
1664                 
1665                 ObjectMapper mapper = new ObjectMapper();
1666                 JSONObject j = new JSONObject();
1667                 j.put("classListDatas", modelList);
1668                 j.put("modelDatas", mapper.writeValueAsString(classMap));
1669                 j.put("modelType", modelType);
1670                 out.write(j.toString());
1671         }
1672         
1673         /*
1674          * Unzip file and store in the model directory for processing
1675          */
1676         @SuppressWarnings("rawtypes")
1677         private void extractFolder(String zipFile )  {
1678             int BUFFER = 2048;
1679             File file = new File(zipFile);
1680
1681             ZipFile zip = null;
1682                 try {
1683                         zip = new ZipFile(file);
1684                     String newPath =  "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1685                     this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1686                     checkZipDirectory(this.directory);
1687                     new File(newPath).mkdir();
1688                     Enumeration zipFileEntries = zip.entries();
1689         
1690                     // Process each entry
1691                     while (zipFileEntries.hasMoreElements()){
1692                         // grab a zip file entry
1693                         ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1694                         String currentEntry = entry.getName();
1695                         File destFile = new File("model" + File.separator + currentEntry);
1696                         File destinationParent = destFile.getParentFile();
1697                         
1698                         destinationParent.mkdirs();
1699         
1700                         if (!entry.isDirectory()){
1701                             BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1702                             int currentByte;
1703                             byte data[] = new byte[BUFFER];
1704                             FileOutputStream fos = new FileOutputStream(destFile);
1705                             BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1706                             while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1707                                 dest.write(data, 0, currentByte);
1708                             }
1709                             dest.flush();
1710                             dest.close();
1711                             is.close();
1712                         }
1713         
1714                         if (currentEntry.endsWith(".zip")){
1715                             extractFolder(destFile.getAbsolutePath());
1716                         }
1717                     }
1718             } catch (IOException e) {
1719                 LOGGER.error("Failed to unzip model file " + zipFile, e);
1720                 }finally{
1721                         try {
1722                                 if(zip != null)
1723                                 zip.close();
1724                         } catch (IOException e) {
1725                                 LOGGER.error("Exception Occured While closing zipfile " + e);
1726                         }
1727                 }
1728         }
1729         
1730         private void retreiveDependency(String workingFile, Boolean modelClass) {
1731                 
1732                 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1733             HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
1734             
1735             tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1736             
1737             classMap.putAll(tempMap);
1738             LOGGER.info(tempMap);
1739             
1740             return;     
1741             
1742         }
1743                 
1744         private List<File> listModelFiles(String directoryName) {
1745                 File directory = new File(directoryName);
1746                 List<File> resultList = new ArrayList<>();
1747                 File[] fList = directory.listFiles();
1748                 for (File file : fList) {
1749                         if (file.isFile()) {
1750                                 resultList.add(file);
1751                         } else if (file.isDirectory()) {
1752                                 dirDependencyList.add(file.getName());
1753                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1754                         }
1755                 }
1756                 return resultList;
1757         }
1758         
1759     private void cleanUp(String path) {
1760         if (path!=null){
1761             try {
1762                 FileUtils.forceDelete(new File(path));
1763             } catch (IOException e) {
1764                 LOGGER.error("Failed to delete folder " + path, e);
1765             }  
1766         }
1767     }
1768  
1769     private void checkZipDirectory(String zipDirectory) {
1770         Path path = Paths.get(zipDirectory);
1771  
1772         if (Files.exists(path)) {
1773             cleanUp(zipDirectory);
1774         }
1775     }
1776         
1777     private List<String> createList() {
1778         List<String> list = new  ArrayList<>();
1779         for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1780             if (cMap.getValue().isPolicyTempalate()){
1781                 list.add(cMap.getKey());
1782             }
1783             
1784         }
1785         
1786         if (list.isEmpty()){
1787             if (classMap.containsKey(this.newModel.getModelName())){
1788                 list.add(this.newModel.getModelName());
1789             }else {
1790                 list.add("EMPTY");
1791             }
1792         }
1793         return list;
1794     }
1795
1796         public Map<String, String> getAttributesListRefMap() {
1797                 return attributesListRefMap;
1798         }
1799
1800         public Map<String, LinkedList<String>> getArrayTextList() {
1801                 return arrayTextList;
1802         }
1803
1804 }
1805
1806 class DCAEMicroServiceObject {
1807
1808         private String service;
1809         private String location;
1810         private String uuid;
1811         private String policyName;
1812         private String description;
1813         private String configName;
1814         private String templateVersion;
1815         private String version;
1816         private String priority;
1817         private String policyScope;
1818         private String riskType;
1819         private String riskLevel; 
1820         private String guard = null;
1821
1822         public String getGuard() {
1823                 return guard;
1824         }
1825         public void setGuard(String guard) {
1826                 this.guard = guard;
1827         }
1828         public String getRiskType() {
1829                 return riskType;
1830         }
1831         public void setRiskType(String riskType) {
1832                 this.riskType = riskType;
1833         }
1834         public String getRiskLevel() {
1835                 return riskLevel;
1836         }
1837         public void setRiskLevel(String riskLevel) {
1838                 this.riskLevel = riskLevel;
1839         }
1840         public String getPolicyScope() {
1841                 return policyScope;
1842         }
1843         public void setPolicyScope(String policyScope) {
1844                 this.policyScope = policyScope;
1845         }
1846
1847         public String getPriority() {
1848                 return priority;
1849         }
1850         public void setPriority(String priority) {
1851                 this.priority = priority;
1852         }
1853         public String getVersion() {
1854                 return version;
1855         }
1856         public void setVersion(String version) {
1857                 this.version = version;
1858         }
1859         private Object content;
1860
1861
1862         public String getPolicyName() {
1863                 return policyName;
1864         }
1865         public void setPolicyName(String policyName) {
1866                 this.policyName = policyName;
1867         }
1868         public String getDescription() {
1869                 return description;
1870         }
1871         public void setDescription(String description) {
1872                 this.description = description;
1873         }
1874         public String getConfigName() {
1875                 return configName;
1876         }
1877         public void setConfigName(String configName) {
1878                 this.configName = configName;
1879         }
1880         public Object getContent() {
1881                 return content;
1882         }
1883         public void setContent(Object content) {
1884                 this.content = content;
1885         }
1886
1887         public String getService() {
1888                 return service;
1889         }
1890         public void setService(String service) {
1891                 this.service = service;
1892         }
1893         public String getLocation() {
1894                 return location;
1895         }
1896         public void setLocation(String location) {
1897                 this.location = location;
1898         }
1899
1900         public String getUuid() {
1901                 return uuid;
1902         }
1903         public void setUuid(String uuid) {
1904                 this.uuid = uuid;
1905         }
1906         public String getTemplateVersion() {
1907                 return templateVersion;
1908         }
1909         public void setTemplateVersion(String templateVersion) {
1910                 this.templateVersion = templateVersion;
1911         }
1912
1913 }