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