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