Merge "Documentation: Release Notes; Installation;"
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
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.FileOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.io.PrintWriter;
31 import java.io.StringReader;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.ArrayList;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.LinkedList;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Map.Entry;
45 import java.util.Set;
46 import java.util.TreeMap;
47 import java.util.UUID;
48 import java.util.zip.ZipEntry;
49 import java.util.zip.ZipFile;
50
51 import javax.json.Json;
52 import javax.json.JsonArray;
53 import javax.json.JsonArrayBuilder;
54 import javax.json.JsonObject;
55 import javax.json.JsonObjectBuilder;
56 import javax.json.JsonReader;
57 import javax.json.JsonValue;
58 import javax.servlet.http.HttpServletRequest;
59 import javax.servlet.http.HttpServletResponse;
60
61 import org.apache.commons.compress.utils.IOUtils;
62 import org.apache.commons.fileupload.FileItem;
63 import org.apache.commons.fileupload.FileUploadException;
64 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
65 import org.apache.commons.fileupload.servlet.ServletFileUpload;
66 import org.apache.commons.io.FileUtils;
67 import org.apache.commons.lang.StringUtils;
68 import org.json.JSONArray;
69 import org.json.JSONObject;
70 import org.onap.policy.common.logging.flexlogger.FlexLogger;
71 import org.onap.policy.common.logging.flexlogger.Logger;
72 import org.onap.policy.rest.XACMLRestProperties;
73 import org.onap.policy.rest.adapter.PolicyRestAdapter;
74 import org.onap.policy.rest.dao.CommonClassDao;
75 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
76 import org.onap.policy.rest.jpa.MicroServiceModels;
77 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
78 import org.onap.policy.rest.jpa.PolicyEntity;
79 import org.onap.policy.rest.util.MSAttributeObject;
80 import org.onap.policy.rest.util.MSModelUtils;
81 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
82 import org.onap.portalsdk.core.controller.RestrictedBaseController;
83 import org.onap.portalsdk.core.web.support.JsonMessage;
84 import org.springframework.beans.factory.annotation.Autowired;
85 import org.springframework.http.MediaType;
86 import org.springframework.stereotype.Controller;
87 import org.springframework.web.bind.annotation.RequestMapping;
88 import org.springframework.web.servlet.ModelAndView;
89 import com.att.research.xacml.util.XACMLProperties;
90 import com.fasterxml.jackson.core.JsonProcessingException;
91 import com.fasterxml.jackson.databind.DeserializationFeature;
92 import com.fasterxml.jackson.databind.JsonNode;
93 import com.fasterxml.jackson.databind.ObjectMapper;
94 import com.fasterxml.jackson.databind.ObjectWriter;
95 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
96 import com.fasterxml.jackson.databind.node.ObjectNode;
97 import com.google.gson.Gson;
98
99 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
100 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
101 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
102 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
103 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
104 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
106
107 @Controller
108 @RequestMapping("/")
109 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
110         private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
111
112         private static CommonClassDao commonClassDao;
113         
114         public static CommonClassDao getCommonClassDao() {
115                 return commonClassDao;
116         }
117
118         public static void setCommonClassDao(CommonClassDao commonClassDao) {
119                 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
120         }
121
122         private MicroServiceModels newModel;
123         private String newFile;
124         private String directory;
125         private List<String> modelList = new ArrayList<>();
126         private List<String> dirDependencyList = new ArrayList<>();
127         private LinkedHashMap<String,MSAttributeObject > classMap = new LinkedHashMap<>();
128         String referenceAttributes;
129         String attributeString;
130         Set<String> allManyTrueKeys= new HashSet <>();
131
132         public static final String DATATYPE  = "data_types.policy.data.";
133         public static final String PROPERTIES=".properties.";
134         public static final String TYPE=".type";
135         public static final String STRING="string";
136         public static final String INTEGER="integer";
137         public static final String LIST="list";
138         public static final String DEFAULT=".default";
139         public static final String REQUIRED=".required";
140         public static final String MATCHABLE=".matchable";
141         public static final String MANYFALSE=":MANY-false";
142         
143         
144         @Autowired
145         private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
146                 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
147         }
148
149         public CreateDcaeMicroServiceController(){
150                 // Empty Constructor
151         }
152
153         protected PolicyRestAdapter policyAdapter = null;
154         private int priorityCount; 
155         private Map<String, String> attributesListRefMap =  new HashMap<>();
156         private Map<String, LinkedList<String>> arrayTextList =  new HashMap<>();
157
158         public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
159                 
160                 String jsonContent = null;
161                 try{
162                         LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
163                         
164                         String tempJson = root.get("policyJSON").toString();
165                         
166                         //---replace empty value with the value below before calling decodeContent method.
167                         String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
168                         LOGGER.info("dummyValue:" + dummyValue);
169                         tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
170                         ObjectMapper mapper = new ObjectMapper();
171                         JsonNode tempJsonNode = mapper.readTree(tempJson);
172                         jsonContent = decodeContent(tempJsonNode).toString();
173                         constructJson(policyData, jsonContent, dummyValue);
174                 }catch(Exception e){
175                         LOGGER.error("Error while decoding microservice content", e);
176                 }
177                 
178                 return policyData;
179         }
180         
181         private GroupPolicyScopeList getPolicyObject(String policyScope) {
182                 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
183         }
184         
185         private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
186                 ObjectWriter om = new ObjectMapper().writer();
187                 String json="";
188                 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
189                 MicroServiceModels returnModel = new MicroServiceModels();
190                 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
191                 if(policyAdapter.getServiceType() !=null){
192                         microServiceObject.setService(policyAdapter.getServiceType());
193                         microServiceObject.setVersion(policyAdapter.getVersion());
194                         returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
195                 }
196                 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
197                         if(policyAdapter.getUuid()!=null){
198                                 microServiceObject.setUuid(policyAdapter.getUuid());
199                         }
200                         if(policyAdapter.getLocation()!=null){
201                                 microServiceObject.setLocation(policyAdapter.getLocation());
202                         } 
203                         if(policyAdapter.getConfigName()!=null){
204                                 microServiceObject.setConfigName(policyAdapter.getConfigName());
205                         }
206                         GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
207                         if(policyScopeValue!=null){
208                                 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());     
209                         }
210                 }
211                 
212                 if(policyAdapter.getPolicyName()!=null){
213                         microServiceObject.setPolicyName(policyAdapter.getPolicyName());
214                 }
215                 if(policyAdapter.getPolicyDescription()!=null){
216                         microServiceObject.setDescription(policyAdapter.getPolicyDescription());
217                 }
218                 if (policyAdapter.getPriority()!=null){
219                         microServiceObject.setPriority(policyAdapter.getPriority());
220                 }else {
221                         microServiceObject.setPriority("9999");
222                 }
223                 
224                 if (policyAdapter.getRiskLevel()!=null){
225                         microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
226                 }
227                 if (policyAdapter.getRiskType()!=null){
228                         microServiceObject.setRiskType(policyAdapter.getRiskType());
229                 }
230                 if (policyAdapter.getGuard()!=null){
231                         microServiceObject.setGuard(policyAdapter.getGuard());
232                 }
233                 microServiceObject.setContent(jsonContent);
234                 
235                 try {
236                         json = om.writeValueAsString(microServiceObject);
237                 } catch (JsonProcessingException e) {
238                         LOGGER.error("Error writing out the object", e);
239                 }
240                 LOGGER.info("input json: " + json);
241                 LOGGER.info("input jsonContent: " + jsonContent);
242                 String cleanJson = cleanUPJson(json);
243         //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
244                 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""},  new String[]{"\"\""});
245                 LOGGER.info("tempJson: " + tempJson);
246                 cleanJson = removeNullAttributes(tempJson);
247                 policyAdapter.setJsonBody(cleanJson);
248                 return policyAdapter;
249         }
250         
251         public String removeNullAttributes(String cleanJson) {
252                 ObjectMapper mapper = new ObjectMapper();
253
254                 try {
255                         JsonNode rootNode = mapper.readTree(cleanJson);
256                         JsonNode returnNode = mapper.readTree(cleanJson);
257                         Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
258                         boolean remove = false;
259                         JsonObject removed = null;
260                         boolean contentChanged = false;
261                         while (fieldsIterator.hasNext()) {
262                                 Map.Entry<String, JsonNode> field = fieldsIterator.next();
263                                 final String key = field.getKey();
264                                 final JsonNode value = field.getValue();
265                                 if("content".equalsIgnoreCase(key)){
266                                         String contentStr = value.toString();
267                                         try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
268                                 JsonObject jsonContent = reader.readObject();                 
269                                                         removed = removeNull(jsonContent);
270                                                         if(!jsonContent.toString().equals(removed.toString())){
271                                                         contentChanged = true;  
272                                                 }
273                     }
274
275                                         if  (value==null || value.isNull()){
276                                                 ((ObjectNode) returnNode).remove(key);
277                                                 remove = true;
278                                         }
279                                 }
280                                 if (remove){
281                                         cleanJson = returnNode.toString();
282                                 }
283                                 if  (value==null || value.isNull()){
284                                         ((ObjectNode) returnNode).remove(key);
285                                         remove = true;
286                                 }
287                         }
288                         if (remove){
289                                 cleanJson = returnNode.toString();
290                         }
291                         
292                         if(contentChanged){
293                                 //set modified content to cleanJson
294                                 JSONObject  jObject  =  new JSONObject(cleanJson);      
295                                 jObject.put("content",removed.toString());
296                                 cleanJson = cleanUPJson(jObject.toString());
297                         }
298                         
299                 } catch (IOException e) {
300                         LOGGER.error("Error writing out the JsonNode",e);
301                 }
302                 return cleanJson;
303         }
304         
305         public static JsonArray removeNull(JsonArray array) {
306             JsonArrayBuilder builder = Json.createArrayBuilder();
307             int i = 0;
308             for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
309                 JsonValue value = it.next();
310                 switch (value.getValueType()) {
311                 case ARRAY:
312                     JsonArray a = removeNull(array.getJsonArray(i));
313                     if (!a.isEmpty())
314                         builder.add(a);
315                     break;
316                 case OBJECT:
317                     JsonObject object = removeNull(array.getJsonObject(i));
318                     if (!object.isEmpty())
319                         builder.add(object);
320                     break;
321                 case STRING:
322                     String s = array.getString(i);
323                     if (s != null && !s.isEmpty())
324                         builder.add(s);
325                     break;
326                 case NUMBER:
327                     builder.add(array.getJsonNumber(i));
328                     break;
329                 case TRUE:
330                 case FALSE:
331                     builder.add(array.getBoolean(i));
332                     break;
333                 case NULL:
334                     break;
335                 }
336             }
337             return builder.build();
338         }
339
340         public static JsonObject removeNull(JsonObject obj) {
341             JsonObjectBuilder builder = Json.createObjectBuilder();
342             for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
343                 Entry<String, JsonValue> e = it.next();
344                 String key = e.getKey();
345                 JsonValue value = e.getValue();
346                 switch (value.getValueType()) {
347                 case ARRAY:
348                     JsonArray array = removeNull(obj.getJsonArray(key));
349                     if (!array.isEmpty())
350                         builder.add(key, array);
351                     break;
352                 case OBJECT:
353                     JsonObject object = removeNull(obj.getJsonObject(key));
354                     if (!object.isEmpty())
355                         builder.add(key, object);
356                     break;
357                 case STRING:
358                     String s = obj.getString(key);
359                     if (s != null && !s.isEmpty())
360                         builder.add(key, s);
361                     break;
362                 case NUMBER:
363                     builder.add(key, obj.getJsonNumber(key));
364                     break;
365                 case TRUE:
366                 case FALSE:
367                     builder.add(key, obj.getBoolean(key));
368                     break;
369                 case NULL:
370                     break;
371                 }
372             }
373             return builder.build();
374         }
375         
376         public String cleanUPJson(String json) {
377                 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
378                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
379                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
380                 
381                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
382                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
383                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
384                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
385                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
386                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
387                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
388                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
389                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
390                 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
391                 return cleanJson;
392         }
393         
394         public JSONObject decodeContent(JsonNode jsonNode){
395                 Iterator<JsonNode> jsonElements = jsonNode.elements();
396                 Iterator<String> jsonKeys = jsonNode.fieldNames();
397                 Map<String,String> element = new TreeMap<>();
398                 while(jsonElements.hasNext() && jsonKeys.hasNext()){
399                         element.put(jsonKeys.next(), jsonElements.next().toString());
400                 }
401                 JSONObject jsonResult = new JSONObject();
402                 JSONArray jsonArray = null;
403                 String oldValue = null;
404                 String nodeKey = null;
405                 String arryKey = null;
406                 Boolean isArray = false;
407                 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
408                 ObjectNode node = nodeFactory.objectNode();
409                 String prevKey = null;
410                 String presKey;
411                 for(Entry<String, String> entry: element.entrySet()){
412                         String key = entry.getKey();
413                         String value = entry.getValue();
414                         if(key.contains(".")){
415                                 presKey = key.substring(0,key.indexOf('.'));
416                         }else if(key.contains("@")){
417                                 presKey = key.substring(0,key.indexOf('@'));
418                         }else{
419                                 presKey = key;
420                         }
421                         // first check if we are different from old.
422                         LOGGER.info(key+"\n");
423                         if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
424                                 if(!oldValue.equals(key.substring(0,key.indexOf('@')))){
425                                         jsonResult.put(oldValue, jsonArray);
426                                         jsonArray = new JSONArray();
427                                 }
428                         }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ 
429                                 jsonResult.put(oldValue, jsonArray);
430                                 isArray = false;
431                                 jsonArray = new JSONArray();
432                         }
433         
434                         prevKey = presKey;
435                         // 
436                         if(key.contains(".")){
437                                 if(nodeKey==null){
438                                         nodeKey = key.substring(0,key.indexOf('.'));
439                                 }
440                                 if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
441                                         node.put(key.substring(key.indexOf('.')+1), value);
442                                 }else{
443                                         if(node.size()!=0){
444                                                 if(nodeKey.contains("@")){
445                                                         if(arryKey==null){
446                                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
447                                                         }
448                                                         if(nodeKey.endsWith("@0")){
449                                                                 isArray = true;
450                                                                 jsonArray = new JSONArray();
451                                                         }
452                                                         if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
453                                                                 jsonArray.put(decodeContent(node));
454                                                         } 
455                                                         if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){
456                                                                 jsonResult.put(arryKey, jsonArray);
457                                                                 jsonArray = new JSONArray();
458                                                         }
459                                                         arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
460                                                 }else{
461                                                         isArray = false;
462                                                         jsonResult.put(nodeKey, decodeContent(node));
463                                                 }
464                                                 node = nodeFactory.objectNode();
465                                         }
466                                         nodeKey = key.substring(0,key.indexOf('.'));
467                                         if(nodeKey.contains("@")){
468                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
469                                         }
470                                         node.put(key.substring(key.indexOf('.')+1), value);
471                                 }
472                         }else {
473                                 if(node.size()!=0){
474                                         if(nodeKey.contains("@")){
475                                                 if(arryKey==null){
476                                                         arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
477                                                 }
478                                                 if(nodeKey.endsWith("@0")){
479                                                         isArray = true;
480                                                         jsonArray = new JSONArray();
481                                                 }
482                                                 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
483                                                         jsonArray.put(decodeContent(node));
484                                                 }
485                                                 jsonResult.put(arryKey, jsonArray);
486                                                 jsonArray = new JSONArray();
487                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
488                                         }else{
489                                                 isArray = false;
490                                                 jsonResult.put(nodeKey, decodeContent(node));
491                                         }
492                                         node = nodeFactory.objectNode();
493                                 }
494                                 if(key.contains("@")){
495                                         isArray = true;
496                                         if(key.endsWith("@0")|| jsonArray==null){
497                                                 jsonArray = new JSONArray();
498                                         }
499                                 }else if(!key.contains("@")){
500                                         isArray = false;
501                                 }
502                                 if(isArray){
503                                         if(oldValue==null){
504                                                 oldValue = key.substring(0,key.indexOf('@'));
505                                         }
506                                         if(oldValue!=prevKey){
507                                                 oldValue = key.substring(0,key.indexOf('@'));
508                                         }
509                                         if(oldValue.equals(key.substring(0,key.indexOf('@')))){
510                                                 jsonArray.put(value);
511                                         }else{
512                                                 jsonResult.put(oldValue, jsonArray);
513                                                 jsonArray = new JSONArray();
514                                         }
515                                         oldValue = key.substring(0,key.indexOf('@'));
516                                 }else{
517                                         jsonResult.put(key, value);
518                                 }
519                         }
520                 }
521                 if(node.size()>0){
522                         if(nodeKey.contains("@")){
523                                 if(jsonArray==null){
524                                         jsonArray = new JSONArray();
525                                 }
526                                 if(arryKey==null){
527                                         arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
528                                 }
529                                 jsonArray.put(decodeContent(node));
530                                 jsonResult.put(arryKey, jsonArray);
531                                 isArray = false;
532                         }else{
533                                 jsonResult.put(nodeKey, decodeContent(node));
534                         }
535                 }
536                 if(isArray && jsonArray.length() > 0){
537                         jsonResult.put(oldValue, jsonArray);
538                 }
539                 return jsonResult;
540         }
541         
542         @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
543         public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
544                 ObjectMapper mapper = new ObjectMapper();
545                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
546                 JsonNode root = mapper.readTree(request.getReader());
547
548                 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
549                 String  servicename = value.split("-v")[0];
550                 String version = null;
551                 if (value.contains("-v")){
552                         version = value.split("-v")[1];
553                 }
554                 MicroServiceModels returnModel = getAttributeObject(servicename, version);
555                 
556                 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
557                 JSONObject jsonHdDefaultObj = null;
558                 if(returnHeaderDefauls != null){
559                         jsonHdDefaultObj = new JSONObject();
560                         jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
561                         jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
562                         jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
563                         jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
564                         jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
565                 }
566                 String headDefautlsData = "";
567                 if(jsonHdDefaultObj != null){                   
568                         headDefautlsData = jsonHdDefaultObj.toString();
569                 }else{
570                         headDefautlsData = "null";
571                 }
572                 
573                 //Get all keys with "MANY-true" defined in their value from subAttribute 
574                 Set<String> allkeys = null;
575                 if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
576                         JSONObject json = new JSONObject(returnModel.getSub_attributes());      
577                         getAllKeys(json); 
578                         allkeys = allManyTrueKeys;
579                         allManyTrueKeys = new  HashSet <>();
580                         LOGGER.info("allkeys : " + allkeys);
581                 }
582                 
583                 //Get element order info 
584                 String dataOrderInfo = returnModel.getDataOrderInfo();
585                 
586                 String allManyTrueKeys = "";
587                 if(allkeys != null){
588                         allManyTrueKeys = allkeys.toString();
589                 }
590                 
591                 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
592                 
593                 JSONObject jsonObject = new JSONObject(jsonModel);
594                 
595                 JSONObject finalJsonObject = null;
596                 if(allkeys != null){
597                         Iterator<String> iter = allkeys.iterator();
598                         while(iter.hasNext()){
599                                 //Convert to array values for MANY-true keys
600                                 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
601                         }
602                 }
603
604                 if(finalJsonObject != null){
605                     LOGGER.info(finalJsonObject.toString());
606                     jsonModel  = finalJsonObject.toString();
607                 }
608                 
609                 //get all properties with "MANY-true" defined in Ref_attributes
610                 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
611                 if(manyTrueProperties != null){
612                         JSONObject jsonObj = new JSONObject(jsonModel);
613                         for (String s : manyTrueProperties) {
614                                 LOGGER.info(s);
615                                 //convert to array element for MANY-true properties
616                                 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
617                         }
618                         
619                         if(finalJsonObject != null){
620                             LOGGER.info(finalJsonObject.toString());
621                             jsonModel = finalJsonObject.toString();
622                         }
623                 }
624                 
625                 response.setCharacterEncoding("UTF-8");
626                 response.setContentType("application / json");
627                 request.setCharacterEncoding("UTF-8");
628                 List<Object>  list = new ArrayList<>();
629                 PrintWriter out = response.getWriter();
630                 String responseString = mapper.writeValueAsString(returnModel);
631
632                 JSONObject j = null;
633                 
634                 if("".equals(allManyTrueKeys)){
635                         j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData +"}");        
636                 }else{
637                         j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData+ "}"); 
638                 }
639                 list.add(j);
640                 out.write(list.toString());
641                 return null;
642         }
643         
644         @SuppressWarnings({ "unchecked", "rawtypes" })
645         private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
646                 Map<String, String> attributeMap = new HashMap<>();
647                 Map<String, String> refAttributeMap = new HashMap<>();
648                 String attribute = returnModel.getAttributes();
649                 if(attribute != null){
650                         attribute = attribute.trim();
651                 }
652                 String refAttribute = returnModel.getRef_attributes();
653                 if(refAttribute != null){
654                         refAttribute = refAttribute.trim();
655                 }
656                 String enumAttribute = returnModel.getEnumValues();
657                 if(enumAttribute != null){
658                         enumAttribute = enumAttribute.trim();
659                 }
660                 if (!StringUtils.isEmpty(attribute)){
661                         attributeMap = convert(attribute, ",");
662                 }
663                 if (!StringUtils.isEmpty(refAttribute)){
664                         refAttributeMap = convert(refAttribute, ",");
665                 }
666
667                 Gson gson = new Gson();
668                 
669                 String subAttributes = returnModel.getSub_attributes();
670                 if(subAttributes != null){
671                         subAttributes = subAttributes.trim();
672                 }else{
673                         subAttributes = "";
674                 }
675                 
676                 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
677                 
678                 JSONObject object = new JSONObject();
679                 JSONArray array = new JSONArray();
680                 
681                 for (Entry<String, String> keySet : attributeMap.entrySet()){
682                         array = new JSONArray();
683                         String value = keySet.getValue();
684                         if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
685                                 array.put(value);
686                                 object.put(keySet.getKey().trim(), array);
687                         }else {
688                                 object.put(keySet.getKey().trim(), value.trim());
689                         }
690                 }
691                 
692                 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
693                         array = new JSONArray();
694                         String value = keySet.getValue().split(":")[0];
695                         if (gsonObject.containsKey(value)){
696                                 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
697                                         array.put(recursiveReference(value, gsonObject, enumAttribute));
698                                         object.put(keySet.getKey().trim(), array);
699                                 }else {
700                                         object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
701                                 }
702                         }else {
703                                 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
704                                         array.put(value.trim());
705                                         object.put(keySet.getKey().trim(), array);
706                                 }else {
707                                         object.put(keySet.getKey().trim(), value.trim()); 
708                                 }
709                         }
710                 }
711
712                 return object.toString();
713         }
714
715         @SuppressWarnings("unchecked")
716         private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
717                 JSONObject object = new JSONObject();
718                 Map<String, String> map;
719                 Object returnClass = subAttributeMap.get(name);
720                 map = (Map<String, String>) returnClass; 
721                 JSONArray array;
722                 
723                 for( Entry<String, String> m:map.entrySet()){  
724                         String[] splitValue = m.getValue().split(":");
725                         array = new JSONArray();
726                         if (subAttributeMap.containsKey(splitValue[0])){
727                                 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
728                                         array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
729                                         object.put(m.getKey().trim(), array);
730                                 }else {
731                                         object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
732                                 }
733                         } else{
734                                 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
735                                         array.put(splitValue[0].trim());
736                                         object.put(m.getKey().trim(), array);
737                                 }else {
738                                         object.put(m.getKey().trim(), splitValue[0].trim());
739                                 }
740                         }
741                   }  
742                 
743                 return object;
744         }
745         
746         
747         public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
748             return convertToArrayElement(json, new HashSet<>(), keyValue);
749         }
750         
751         private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
752             for (String key : json.keySet()) {
753                 Object obj = json.get(key);
754                 if(key.equals(keyValue.trim())){
755                         if(!(obj instanceof JSONArray)){
756                                 JSONArray newJsonArray = new JSONArray();
757                                 newJsonArray.put(obj);
758                                 json.put(key, newJsonArray);
759                         }
760                         LOGGER.info("key : " + key);
761                         LOGGER.info("obj : " + obj);
762                         LOGGER.info("json.get(key) : " + json.get(key));
763                         LOGGER.info("keyValue : " + keyValue);
764                     keys.addAll(json.keySet());
765                     
766                     return json;
767                 }
768
769                 if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);            
770             }
771
772             return json;
773         }
774         
775         // call this method to get all MANY-true properties 
776         public static Set<String> getManyTrueProperties(String referAttributes){
777                 LOGGER.info("referAttributes : " + referAttributes);
778                 Set<String> manyTrueProperties = new HashSet<>();
779                 
780                 if(referAttributes != null){
781                         String[] referAarray = referAttributes.split(",");
782                         String []element= null;
783                         for(int i=0; i<referAarray.length; i++){
784                                 element = referAarray[i].split("=");      
785                                 if(element.length > 1 && element[1].contains("MANY-true")){
786                                         manyTrueProperties.add(element[0]);
787                                 }
788                         }               
789                 }
790                 
791                 return manyTrueProperties;
792         }
793         
794         //call this method to start the recursive
795         private Set<String> getAllKeys(JSONObject json) {
796             return getAllKeys(json, new HashSet<>());
797         }
798
799         private Set<String> getAllKeys(JSONArray arr) {
800             return getAllKeys(arr, new HashSet<>());
801         }
802
803         private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
804             for (int i = 0; i < arr.length(); i++) {
805                 Object obj = arr.get(i);
806                 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
807                 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
808             }
809
810             return keys;
811         }
812         
813     // this method returns a set of keys with "MANY-true" defined in their value.
814         private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
815             for (String key : json.keySet()) {
816                 Object obj = json.get(key);
817                 if(obj instanceof String && ((String) obj).contains("MANY-true")){
818                         LOGGER.info("key : " + key);
819                         LOGGER.info("obj : " + obj);
820                         allManyTrueKeys.add(key);
821                 }
822                 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
823                 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
824             }
825
826             return keys;
827         }
828
829         
830         @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
831         public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
832                 ObjectMapper mapper = new ObjectMapper();
833                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
834                 JsonNode root = mapper.readTree(request.getReader());
835
836                 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
837                 String  servicename = value.split("-v")[0];
838                 Set<String> returnList = getVersionList(servicename);
839                 
840                 response.setCharacterEncoding("UTF-8");
841                 response.setContentType("application / json");
842                 request.setCharacterEncoding("UTF-8");
843         List<Object>  list = new ArrayList<>();
844                 PrintWriter out = response.getWriter();
845                 String responseString = mapper.writeValueAsString(returnList);
846                 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
847                 list.add(j);
848                 out.write(list.toString());
849                 return null;
850         }
851
852         private Set<String> getVersionList(String name) {       
853                 MicroServiceModels workingModel;
854                 Set<String> list = new HashSet<>();
855                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
856                 for (int i = 0; i < microServiceModelsData.size(); i++) {
857                         workingModel = (MicroServiceModels) microServiceModelsData.get(i);
858                         if (workingModel.getVersion()!=null){
859                                 list.add(workingModel.getVersion());
860                         }else{
861                                 list.add("Default");
862                         }
863                 }
864                 return list;
865         }
866         
867         private MicroServiceModels getAttributeObject(String name, String version) {    
868                 MicroServiceModels workingModel = new MicroServiceModels();
869                 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
870                 for (int i = 0; i < microServiceModelsData.size(); i++) {
871                         workingModel = (MicroServiceModels) microServiceModelsData.get(i);
872                         if(version != null){
873                                 if (workingModel.getVersion()!=null){
874                                         if (workingModel.getVersion().equals(version)){
875                                                 return workingModel;
876                                         }
877                                 }else{
878                                         return workingModel;
879                                 }
880                         }else{
881                                 return workingModel;
882                         }
883                         
884                 }
885                 return workingModel;
886         }
887         
888         private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {  
889                 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName", modelName);
890         }       
891
892         @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
893         public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
894                 try{
895                         Map<String, Object> model = new HashMap<>();
896                         ObjectMapper mapper = new ObjectMapper();
897                         List<String> priorityList = new ArrayList<>();
898                         priorityCount = 10;
899                         for (int i = 1; i < priorityCount; i++) {
900                                 priorityList.add(String.valueOf(i));
901                         }
902                         model.put("priorityDatas", mapper.writeValueAsString(priorityList));
903                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
904                         JSONObject j = new JSONObject(msg);
905                         response.getWriter().write(j.toString());
906                 }
907                 catch (Exception e){
908                         LOGGER.error(e);
909                 }
910         }
911
912         public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
913                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
914                         Object policyData = policyAdapter.getPolicyData();
915                         PolicyType policy = (PolicyType) policyData;
916                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
917                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
918                         policyAdapter.setPolicyName(policyNameValue);
919                         String description = "";
920                         try{
921                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
922                         }catch(Exception e){
923                             LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
924                                 description = policy.getDescription();
925                         }
926                         policyAdapter.setPolicyDescription(description);
927                         // Get the target data under policy.
928                         TargetType target = policy.getTarget();
929                         if (target != null) {
930                                 // Under target we have AnyOFType
931                                 List<AnyOfType> anyOfList = target.getAnyOf();
932                                 if (anyOfList != null) {
933                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
934                                         while (iterAnyOf.hasNext()) {
935                                                 AnyOfType anyOf = iterAnyOf.next();
936                                                 // Under AnyOFType we have AllOFType
937                                                 List<AllOfType> allOfList = anyOf.getAllOf();
938                                                 if (allOfList != null) {
939                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
940                                                         while (iterAllOf.hasNext()) {
941                                                                 AllOfType allOf = iterAllOf.next();
942                                                                 // Under AllOFType we have Match
943                                                                 List<MatchType> matchList = allOf.getMatch();
944                                                                 if (matchList != null) {
945                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
946                                                                         while (matchList.size()>1 && iterMatch.hasNext()) {
947                                                                                 MatchType match = iterMatch.next();
948                                                                                 //
949                                                                                 // Under the match we have attribute value and
950                                                                                 // attributeDesignator. So,finally down to the actual attribute.
951                                                                                 //
952                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
953                                                                                 String value = (String) attributeValue.getContent().get(0);
954                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
955                                                                                 String attributeId = designator.getAttributeId();
956                                                                                 // First match in the target is OnapName, so set that value.
957                                                                                 if ("ONAPName".equals(attributeId)) {
958                                                                                         policyAdapter.setOnapName(value);
959                                                                                 }
960                                                                                 if ("ConfigName".equals(attributeId)){
961                                                                                         policyAdapter.setConfigName(value);
962                                                                                 }
963                                                                                 if ("uuid".equals(attributeId)){
964                                                                                         policyAdapter.setUuid(value);
965                                                                                 }
966                                                                                 if ("location".equals(attributeId)){
967                                                                                         policyAdapter.setLocation(value);
968                                                                                 }
969                                                                                 if ("RiskType".equals(attributeId)){
970                                                                                         policyAdapter.setRiskType(value);
971                                                                                 }
972                                                                                 if ("RiskLevel".equals(attributeId)){
973                                                                                         policyAdapter.setRiskLevel(value);
974                                                                                 }
975                                                                                 if ("guard".equals(attributeId)){
976                                                                                         policyAdapter.setGuard(value);
977                                                                                 }
978                                                                                 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
979                                                                                         PolicyController controller = new PolicyController();
980                                                                                         String newDate = controller.convertDate(value);
981                                                                                         policyAdapter.setTtlDate(newDate);
982                                                                                 }
983                                                                         }
984                                                                         readFile(policyAdapter, entity);
985                                                                 }
986                                                         }
987                                                 }
988                                         }
989                                 }
990                         }
991                 }
992         }
993         
994         public static Map<String, String> convert(String str, String split) {
995                 Map<String, String> map = new HashMap<>();
996                 for(final String entry : str.split(split)) {
997                     String[] parts = entry.split("=");
998                     map.put(parts[0], parts[1]);
999                 }
1000                 return map;
1001         }
1002
1003
1004         @SuppressWarnings("unchecked")
1005         private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1006                 String policyScopeName = null;
1007                 ObjectMapper mapper = new ObjectMapper();
1008                 try {
1009                         DCAEMicroServiceObject msBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1010                         policyScopeName = getPolicyScope(msBody.getPolicyScope());
1011                         policyAdapter.setPolicyScope(policyScopeName);
1012
1013                         policyAdapter.setPriority(msBody.getPriority());
1014
1015                         if (msBody.getVersion()!= null){
1016                                 policyAdapter.setServiceType(msBody.getService());
1017                                 policyAdapter.setVersion(msBody.getVersion());
1018                         }else{
1019                                 policyAdapter.setServiceType(msBody.getService());
1020                         }
1021                         if(msBody.getContent() != null){
1022                                 LinkedHashMap<String, Object>  data = new LinkedHashMap<>();
1023                                 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1024                                 readRecursivlyJSONContent(map, data);
1025                                 policyAdapter.setRuleData(data);
1026                         }
1027
1028                 } catch (Exception e) {
1029                         LOGGER.error(e);
1030                 }
1031
1032         }
1033
1034         @SuppressWarnings({ "rawtypes", "unchecked" }) 
1035         public void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1036                 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1037                         Object key =  iterator.next();
1038                         Object value = map.get(key);
1039                         if(value instanceof LinkedHashMap<?, ?>){
1040                                 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>(); 
1041                                 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1042                                 for( Entry<String, Object> entry : secondObjec.entrySet()){
1043                                         data.put(key+"." + entry.getKey(), entry.getValue());
1044                                 }
1045                         }else if(value instanceof ArrayList){
1046                                 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1047                                 for(int i = 0; i < jsonArrayVal.size(); i++){
1048                                         Object arrayvalue = jsonArrayVal.get(i);
1049                                         if(arrayvalue instanceof LinkedHashMap<?, ?>){
1050                                                 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();   
1051                                                 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1052                                                 for(Entry<String, Object> entry: newData.entrySet()){
1053                                                         data.put(key+"@"+i+"." +entry.getKey(), entry.getValue());
1054                                                 }
1055                                         }else if(arrayvalue instanceof ArrayList){
1056                                                 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1057                                                 for(int j = 0; j < jsonArrayVal1.size(); j++){
1058                                                         Object arrayvalue1 = jsonArrayVal1.get(i);
1059                                                         data.put(key+"@"+j, arrayvalue1.toString());
1060                                                 }       
1061                                         }else{
1062                                                 data.put(key+"@"+i, arrayvalue.toString());
1063                                         }       
1064                                 }
1065                         }else{
1066                                 data.put(key.toString(), value.toString());
1067                         }       
1068                 }
1069         }
1070
1071         public String getPolicyScope(String value) {
1072                 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1073                 if(groupList != null && !groupList.isEmpty()){
1074                         GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1075                         return pScope.getGroupName();           
1076                 }
1077                 return null;
1078         }
1079
1080         //Convert the map values and set into JSON body
1081         public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1082                 Map<String, String> attribute = new HashMap<>();
1083                 StringBuilder temp;
1084                 String key;
1085                 String value;
1086                 for (Entry<String, String> entry : attributesMap.entrySet()) {
1087                         key = entry.getKey();
1088                         value = entry.getValue();
1089                         attribute.put(key, value);
1090                 }
1091                 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1092                         key = entryRef.getKey();
1093                         value = entryRef.getValue();
1094                         attribute.put(key, value);
1095                 }
1096                 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1097                         key = entryList.getKey();
1098                         value = entryList.getValue();
1099                         attribute.put(key, value);
1100                 }
1101                 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1102                         key = arrayList.getKey();
1103                         temp = null;
1104                         for (Object textList : arrayList.getValue()){
1105                                 if (temp == null){
1106                                         temp = new StringBuilder();
1107                                         temp.append("[" + textList);
1108                                 }else{
1109                                         temp.append("," + textList);
1110                                 }
1111                         }
1112                         attribute.put(key, temp+ "]");                  
1113                 }
1114
1115                 return  attribute;
1116         }
1117         
1118         @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1119         public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1120                 modelList = new ArrayList<>();
1121                 dirDependencyList = new ArrayList<>();
1122                 classMap = new LinkedHashMap<>();
1123                 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1124                 boolean zip = false;
1125                 boolean yml= false;
1126                 String errorMsg = "";
1127                 for (FileItem item : items) {
1128                         if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1129                                 this.newModel = new MicroServiceModels();
1130                                 try{
1131                                         File file = new File(item.getName());
1132                                         OutputStream outputStream = new FileOutputStream(file);
1133                                         IOUtils.copy(item.getInputStream(), outputStream);
1134                                         outputStream.close();
1135                                         this.newFile = file.toString();
1136                                         this.newModel.setModelName(this.newFile.split("-v")[0]);
1137                                 
1138                                         if (this.newFile.contains("-v")){
1139                                                 if (item.getName().endsWith(".zip")){
1140                                                         this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1141                                                         zip = true;
1142                                                 }else if(item.getName().endsWith(".yml")){
1143                                                         this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1144                                                         yml = true;
1145                                                 }
1146                                                 else {
1147                                                         this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1148                                                 }
1149                                         }                               
1150                                 }catch(Exception e){
1151                                         LOGGER.error("Upload error : ", e);
1152                                         errorMsg = "Upload error:" + e.getMessage();
1153                                 }
1154                         }
1155                         
1156                 }
1157                 
1158                 if(!errorMsg.isEmpty()){
1159                         
1160                         PrintWriter out = response.getWriter();
1161                         
1162                         response.setCharacterEncoding("UTF-8");
1163                         response.setContentType("application / json");
1164                         request.setCharacterEncoding("UTF-8");
1165
1166                         JSONObject j = new JSONObject();
1167                         j.put("errorMsg", errorMsg);
1168                         out.write(j.toString());
1169                         return;
1170                 }
1171                 
1172                 List<File> fileList = new ArrayList<>();
1173                 MSModelUtils msMLUtils =  new MSModelUtils();
1174                 this.directory = "model";
1175                 if (zip){
1176                         extractFolder(this.newFile);
1177                         fileList = listModelFiles(this.directory);
1178                 }else if (yml==true){
1179                         
1180                         msMLUtils.parseTosca(this.newFile);
1181                         
1182                 }else {
1183                         File file = new File(this.newFile);
1184                         fileList.add(file);
1185                 }
1186                 String modelType= "";
1187                 if(!yml){
1188                         modelType="xmi";
1189                         //Process Main Model file first
1190                         classMap = new LinkedHashMap<>();
1191                         for (File file : fileList) {
1192                                 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1193                         retreiveDependency(file.toString(), true);
1194                     }   
1195                         }
1196                         
1197                         modelList = createList();
1198                         
1199                         cleanUp(this.newFile);
1200                         cleanUp(directory);
1201                 }else{
1202                         modelType="yml";
1203                         modelList.add(this.newModel.getModelName());
1204                         String className=this.newModel.getModelName();
1205                         MSAttributeObject msAttributes= new MSAttributeObject();
1206                         msAttributes.setClassName(className);
1207                         
1208                         LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
1209                         returnAttributeList.put(className, msMLUtils.getAttributeString());
1210                         msAttributes.setAttribute(returnAttributeList);
1211                         
1212                         msAttributes.setSubClass(msMLUtils.getRetmap());
1213                         
1214                         msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
1215                         
1216                         LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
1217
1218                         returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
1219                         msAttributes.setRefAttribute(returnReferenceList);
1220                         
1221                         if(msMLUtils.getListConstraints()!=""){
1222                                 LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
1223                                 String[] listArray=msMLUtils.getListConstraints().split("#");
1224                 for(String str:listArray){
1225                     String[] strArr= str.split("=");
1226                     if(strArr.length>1){
1227                         enumList.put(strArr[0], strArr[1]);
1228                     }
1229                 }
1230                                 msAttributes.setEnumType(enumList);
1231                         }
1232                         
1233                         classMap=new LinkedHashMap<>();
1234                         classMap.put(className, msAttributes);
1235                         
1236                 }
1237                 
1238                 PrintWriter out = response.getWriter();
1239                 
1240                 response.setCharacterEncoding("UTF-8");
1241                 response.setContentType("application / json");
1242                 request.setCharacterEncoding("UTF-8");
1243                 
1244                 ObjectMapper mapper = new ObjectMapper();
1245                 JSONObject j = new JSONObject();
1246                 j.put("classListDatas", modelList);
1247                 j.put("modelDatas", mapper.writeValueAsString(classMap));
1248                 j.put("modelType", modelType);
1249                 j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
1250                 
1251                 out.write(j.toString());
1252         }
1253         
1254         /*
1255          * Unzip file and store in the model directory for processing
1256          */
1257         @SuppressWarnings("rawtypes")
1258         private void extractFolder(String zipFile )  {
1259             int BUFFER = 2048;
1260             File file = new File(zipFile);
1261
1262                 try (ZipFile zip = new ZipFile(file)) {
1263                     String newPath =  "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1264                     this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1265                     checkZipDirectory(this.directory);
1266                     new File(newPath).mkdir();
1267                     Enumeration zipFileEntries = zip.entries();
1268         
1269                     // Process each entry
1270                     while (zipFileEntries.hasMoreElements()){
1271                         // grab a zip file entry
1272                         ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1273                         String currentEntry = entry.getName();
1274                         File destFile = new File("model" + File.separator + currentEntry);
1275                         File destinationParent = destFile.getParentFile();
1276                         
1277                         destinationParent.mkdirs();
1278         
1279                         if (!entry.isDirectory()){
1280                             BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1281                             int currentByte;
1282                             byte[] data = new byte[BUFFER];
1283                             try (FileOutputStream fos = new FileOutputStream(destFile);
1284                                         BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1285                                     while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1286                                         dest.write(data, 0, currentByte);
1287                                     }
1288                                     dest.flush();
1289                             } catch (IOException e) {
1290                                 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1291                                 //
1292                                 // PLD should I throw e?
1293                                 //
1294                                 throw e;
1295                             }
1296                         }
1297         
1298                         if (currentEntry.endsWith(".zip")){
1299                             extractFolder(destFile.getAbsolutePath());
1300                         }
1301                     }
1302             } catch (IOException e) {
1303                 LOGGER.error("Failed to unzip model file " + zipFile, e);
1304                 }
1305         }
1306         
1307         private void retreiveDependency(String workingFile, Boolean modelClass) {
1308                 
1309                 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1310             Map<String, MSAttributeObject> tempMap;
1311             
1312             tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1313             
1314             classMap.putAll(tempMap);
1315             LOGGER.info(tempMap);
1316             
1317             return;     
1318             
1319         }
1320                 
1321         private List<File> listModelFiles(String directoryName) {
1322                 File fileDirectory = new File(directoryName);
1323                 List<File> resultList = new ArrayList<>();
1324                 File[] fList = fileDirectory.listFiles();
1325                 for (File file : fList) {
1326                         if (file.isFile()) {
1327                                 resultList.add(file);
1328                         } else if (file.isDirectory()) {
1329                                 dirDependencyList.add(file.getName());
1330                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1331                         }
1332                 }
1333                 return resultList;
1334         }
1335         
1336     public void cleanUp(String path) {
1337         if (path!=null){
1338             try {
1339                 FileUtils.forceDelete(new File(path));
1340             } catch (IOException e) {
1341                 LOGGER.error("Failed to delete folder " + path, e);
1342             }  
1343         }
1344     }
1345  
1346     public void checkZipDirectory(String zipDirectory) {
1347         Path path = Paths.get(zipDirectory);
1348  
1349         if (Files.exists(path)) {
1350             cleanUp(zipDirectory);
1351         }
1352     }
1353         
1354     private List<String> createList() {
1355         List<String> list = new  ArrayList<>();
1356         for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1357             if (cMap.getValue().isPolicyTempalate()){
1358                 list.add(cMap.getKey());
1359             }
1360             
1361         }
1362         
1363         if (list.isEmpty()){
1364             if (classMap.containsKey(this.newModel.getModelName())){
1365                 list.add(this.newModel.getModelName());
1366             }else {
1367                 list.add("EMPTY");
1368             }
1369         }
1370         return list;
1371     }
1372
1373         public Map<String, String> getAttributesListRefMap() {
1374                 return attributesListRefMap;
1375         }
1376
1377         public Map<String, LinkedList<String>> getArrayTextList() {
1378                 return arrayTextList;
1379         }
1380
1381 }
1382
1383 class DCAEMicroServiceObject {
1384
1385         private String service;
1386         private String location;
1387         private String uuid;
1388         private String policyName;
1389         private String description;
1390         private String configName;
1391         private String templateVersion;
1392         private String version;
1393         private String priority;
1394         private String policyScope;
1395         private String riskType;
1396         private String riskLevel; 
1397         private String guard = null;
1398
1399         public String getGuard() {
1400                 return guard;
1401         }
1402         public void setGuard(String guard) {
1403                 this.guard = guard;
1404         }
1405         public String getRiskType() {
1406                 return riskType;
1407         }
1408         public void setRiskType(String riskType) {
1409                 this.riskType = riskType;
1410         }
1411         public String getRiskLevel() {
1412                 return riskLevel;
1413         }
1414         public void setRiskLevel(String riskLevel) {
1415                 this.riskLevel = riskLevel;
1416         }
1417         public String getPolicyScope() {
1418                 return policyScope;
1419         }
1420         public void setPolicyScope(String policyScope) {
1421                 this.policyScope = policyScope;
1422         }
1423
1424         public String getPriority() {
1425                 return priority;
1426         }
1427         public void setPriority(String priority) {
1428                 this.priority = priority;
1429         }
1430         public String getVersion() {
1431                 return version;
1432         }
1433         public void setVersion(String version) {
1434                 this.version = version;
1435         }
1436         private Object content;
1437
1438
1439         public String getPolicyName() {
1440                 return policyName;
1441         }
1442         public void setPolicyName(String policyName) {
1443                 this.policyName = policyName;
1444         }
1445         public String getDescription() {
1446                 return description;
1447         }
1448         public void setDescription(String description) {
1449                 this.description = description;
1450         }
1451         public String getConfigName() {
1452                 return configName;
1453         }
1454         public void setConfigName(String configName) {
1455                 this.configName = configName;
1456         }
1457         public Object getContent() {
1458                 return content;
1459         }
1460         public void setContent(Object content) {
1461                 this.content = content;
1462         }
1463
1464         public String getService() {
1465                 return service;
1466         }
1467         public void setService(String service) {
1468                 this.service = service;
1469         }
1470         public String getLocation() {
1471                 return location;
1472         }
1473         public void setLocation(String location) {
1474                 this.location = location;
1475         }
1476
1477         public String getUuid() {
1478                 return uuid;
1479         }
1480         public void setUuid(String uuid) {
1481                 this.uuid = uuid;
1482         }
1483         public String getTemplateVersion() {
1484                 return templateVersion;
1485         }
1486         public void setTemplateVersion(String templateVersion) {
1487                 this.templateVersion = templateVersion;
1488         }
1489
1490 }