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