2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedInputStream;
25 import java.io.BufferedOutputStream;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.io.StringReader;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.LinkedHashMap;
45 import java.util.LinkedList;
46 import java.util.List;
48 import java.util.Map.Entry;
50 import java.util.TreeMap;
51 import java.util.UUID;
52 import java.util.zip.ZipEntry;
53 import java.util.zip.ZipFile;
55 import javax.json.Json;
56 import javax.json.JsonArray;
57 import javax.json.JsonArrayBuilder;
58 import javax.json.JsonObject;
59 import javax.json.JsonObjectBuilder;
60 import javax.json.JsonReader;
61 import javax.json.JsonValue;
62 import javax.servlet.http.HttpServletRequest;
63 import javax.servlet.http.HttpServletResponse;
65 import org.apache.commons.compress.utils.IOUtils;
66 import org.apache.commons.fileupload.FileItem;
67 import org.apache.commons.fileupload.FileUploadException;
68 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
69 import org.apache.commons.fileupload.servlet.ServletFileUpload;
70 import org.apache.commons.io.FileUtils;
71 import org.apache.commons.lang.StringUtils;
72 import org.json.JSONArray;
73 import org.json.JSONObject;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.rest.XACMLRestProperties;
77 import org.onap.policy.rest.adapter.PolicyRestAdapter;
78 import org.onap.policy.rest.dao.CommonClassDao;
79 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
80 import org.onap.policy.rest.jpa.MicroServiceModels;
81 import org.onap.policy.rest.jpa.PolicyEntity;
82 import org.onap.policy.rest.util.MSAttributeObject;
83 import org.onap.policy.rest.util.MSModelUtils;
84 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
85 import org.onap.portalsdk.core.controller.RestrictedBaseController;
86 import org.onap.portalsdk.core.web.support.JsonMessage;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.springframework.http.MediaType;
89 import org.springframework.stereotype.Controller;
90 import org.springframework.web.bind.annotation.RequestMapping;
91 import org.springframework.web.servlet.ModelAndView;
92 import org.yaml.snakeyaml.Yaml;
94 import com.att.research.xacml.util.XACMLProperties;
95 import com.fasterxml.jackson.core.JsonProcessingException;
96 import com.fasterxml.jackson.databind.DeserializationFeature;
97 import com.fasterxml.jackson.databind.JsonNode;
98 import com.fasterxml.jackson.databind.ObjectMapper;
99 import com.fasterxml.jackson.databind.ObjectWriter;
100 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
101 import com.fasterxml.jackson.databind.node.ObjectNode;
102 import com.google.gson.Gson;
104 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
106 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
107 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
108 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
109 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
110 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
114 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
115 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
117 private static CommonClassDao commonClassDao;
119 public static CommonClassDao getCommonClassDao() {
120 return commonClassDao;
123 public static void setCommonClassDao(CommonClassDao commonClassDao) {
124 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
127 private MicroServiceModels newModel;
128 private String newFile;
129 private String directory;
130 private List<String> modelList = new ArrayList<>();
131 private List<String> dirDependencyList = new ArrayList<>();
132 private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
133 //Tosca Model related Datastructure.
134 String referenceAttributes;
135 String attributeString;
136 String listConstraints;
137 String subAttributeString;
138 HashMap<String, Object> retmap = new HashMap<>();
139 Set<String> uniqueKeys= new HashSet<>();
140 Set<String> uniqueDataKeys= new HashSet<>();
141 StringBuilder dataListBuffer=new StringBuilder();
142 List<String> dataConstraints= new ArrayList <>();
143 Set<String> allManyTrueKeys= new HashSet <>();
145 public static final String DATATYPE = "data_types.policy.data.";
146 public static final String PROPERTIES=".properties.";
147 public static final String TYPE=".type";
148 public static final String STRING="string";
149 public static final String INTEGER="integer";
150 public static final String LIST="list";
151 public static final String DEFAULT=".default";
152 public static final String REQUIRED=".required";
153 public static final String MANYFALSE=":MANY-false";
157 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
158 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
161 public CreateDcaeMicroServiceController(){}
163 protected PolicyRestAdapter policyAdapter = null;
164 private int priorityCount;
165 private Map<String, String> attributesListRefMap = new HashMap<>();
166 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
168 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
170 String jsonContent = null;
172 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
174 String tempJson = root.get("policyJSON").toString();
176 //---replace empty value with the value below before calling decodeContent method.
177 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
178 LOGGER.info("dummyValue:" + dummyValue);
179 tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
180 ObjectMapper mapper = new ObjectMapper();
181 JsonNode tempJsonNode = mapper.readTree(tempJson);
182 jsonContent = decodeContent(tempJsonNode).toString();
183 constructJson(policyData, jsonContent, dummyValue);
185 LOGGER.error("Error while decoding microservice content", e);
191 private GroupPolicyScopeList getPolicyObject(String policyScope) {
192 GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
196 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
197 ObjectWriter om = new ObjectMapper().writer();
199 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
200 MicroServiceModels returnModel = new MicroServiceModels();
201 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
202 if(policyAdapter.getServiceType() !=null){
203 microServiceObject.setService(policyAdapter.getServiceType());
204 microServiceObject.setVersion(policyAdapter.getVersion());
205 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
207 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
208 if(policyAdapter.getUuid()!=null){
209 microServiceObject.setUuid(policyAdapter.getUuid());
211 if(policyAdapter.getLocation()!=null){
212 microServiceObject.setLocation(policyAdapter.getLocation());
214 if(policyAdapter.getConfigName()!=null){
215 microServiceObject.setConfigName(policyAdapter.getConfigName());
217 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
218 if(policyScopeValue!=null){
219 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
223 if(policyAdapter.getPolicyName()!=null){
224 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
226 if(policyAdapter.getPolicyDescription()!=null){
227 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
229 if (policyAdapter.getPriority()!=null){
230 microServiceObject.setPriority(policyAdapter.getPriority());
232 microServiceObject.setPriority("9999");
235 if (policyAdapter.getRiskLevel()!=null){
236 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
238 if (policyAdapter.getRiskType()!=null){
239 microServiceObject.setRiskType(policyAdapter.getRiskType());
241 if (policyAdapter.getGuard()!=null){
242 microServiceObject.setGuard(policyAdapter.getGuard());
244 microServiceObject.setContent(jsonContent);
247 json = om.writeValueAsString(microServiceObject);
248 } catch (JsonProcessingException e) {
249 LOGGER.error("Error writing out the object", e);
251 LOGGER.info("input json: " + json);
252 LOGGER.info("input jsonContent: " + jsonContent);
253 String cleanJson = cleanUPJson(json);
254 //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
255 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
256 LOGGER.info("tempJson: " + tempJson);
257 cleanJson = removeNullAttributes(tempJson);
258 policyAdapter.setJsonBody(cleanJson);
259 return policyAdapter;
262 private String removeNullAttributes(String cleanJson) {
263 ObjectMapper mapper = new ObjectMapper();
266 JsonNode rootNode = mapper.readTree(cleanJson);
267 JsonNode returnNode = mapper.readTree(cleanJson);
268 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
269 boolean remove = false;
270 JsonObject removed = null;
271 boolean contentChanged = false;
272 while (fieldsIterator.hasNext()) {
273 Map.Entry<String, JsonNode> field = fieldsIterator.next();
274 final String key = field.getKey();
275 final JsonNode value = field.getValue();
276 if("content".equalsIgnoreCase(key)){
277 String contentStr = value.toString();
278 try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
279 JsonObject jsonContent = reader.readObject();
280 removed = removeNull(jsonContent);
281 if(!jsonContent.toString().equals(removed.toString())){
282 contentChanged = true;
286 if (value==null || value.isNull()){
287 ((ObjectNode) returnNode).remove(key);
292 cleanJson = returnNode.toString();
294 if (value==null || value.isNull()){
295 ((ObjectNode) returnNode).remove(key);
300 cleanJson = returnNode.toString();
304 //set modified content to cleanJson
305 JSONObject jObject = new JSONObject(cleanJson);
306 jObject.put("content",removed.toString());
307 cleanJson = cleanUPJson(jObject.toString());
310 } catch (IOException e) {
311 LOGGER.error("Error writing out the JsonNode",e);
316 public static JsonArray removeNull(JsonArray array) {
317 JsonArrayBuilder builder = Json.createArrayBuilder();
319 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
320 JsonValue value = it.next();
321 switch (value.getValueType()) {
323 JsonArray a = removeNull(array.getJsonArray(i));
328 JsonObject object = removeNull(array.getJsonObject(i));
329 if (!object.isEmpty())
333 String s = array.getString(i);
334 if (s != null && !s.isEmpty())
338 builder.add(array.getJsonNumber(i));
342 builder.add(array.getBoolean(i));
348 return builder.build();
351 public static JsonObject removeNull(JsonObject obj) {
352 JsonObjectBuilder builder = Json.createObjectBuilder();
353 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
354 Entry<String, JsonValue> e = it.next();
355 String key = e.getKey();
356 JsonValue value = e.getValue();
357 switch (value.getValueType()) {
359 JsonArray array = removeNull(obj.getJsonArray(key));
360 if (!array.isEmpty())
361 builder.add(key, array);
364 JsonObject object = removeNull(obj.getJsonObject(key));
365 if (!object.isEmpty())
366 builder.add(key, object);
369 String s = obj.getString(key);
370 if (s != null && !s.isEmpty())
374 builder.add(key, obj.getJsonNumber(key));
378 builder.add(key, obj.getBoolean(key));
384 return builder.build();
387 // Second index of dot should be returned.
388 public int stringBetweenDots(String str){
389 String stringToSearch=str;
390 String[]ss=stringToSearch.split("\\.");
394 uniqueKeys.add(ss[2]);
398 return uniqueKeys.size();
401 public void stringBetweenDotsForDataFields(String str){
402 String stringToSearch=str;
403 String[]ss=stringToSearch.split("\\.");
408 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
414 @SuppressWarnings("unchecked")
415 public Map<String, String> load(String fileName) throws IOException {
416 File newConfiguration = new File(fileName);
417 Yaml yaml = new Yaml();
418 Map<Object, Object> yamlMap = null;
419 try(InputStream is = new FileInputStream(newConfiguration)){
420 yamlMap = (Map<Object, Object>) yaml.load(is);
421 } catch (FileNotFoundException e) {
425 StringBuilder sb = new StringBuilder();
426 Map<String, String> settings = new HashMap<>();
427 if (yamlMap == null) {
430 List<String> path = new ArrayList <>();
431 serializeMap(settings, sb, path, yamlMap);
435 public Map<String, String> load(byte[] source) throws IOException {
436 Yaml yaml = new Yaml();
437 @SuppressWarnings("unchecked")
438 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
439 StringBuilder sb = new StringBuilder();
440 Map<String, String> settings = new HashMap <>();
441 if (yamlMap == null) {
444 List<String> path = new ArrayList <>();
445 serializeMap(settings, sb, path, yamlMap);
449 @SuppressWarnings({ "unchecked", "rawtypes" })
450 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
451 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
452 if (entry.getValue() instanceof Map) {
453 path.add((String) entry.getKey());
454 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
455 path.remove(path.size() - 1);
456 } else if (entry.getValue() instanceof List) {
457 path.add((String) entry.getKey());
458 serializeList(settings, sb, path, (List) entry.getValue());
459 path.remove(path.size() - 1);
461 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
466 @SuppressWarnings("unchecked")
467 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
469 for (Object listEle : yamlList) {
470 if (listEle instanceof Map) {
471 path.add(Integer.toString(counter));
472 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
473 path.remove(path.size() - 1);
474 } else if (listEle instanceof List) {
475 path.add(Integer.toString(counter));
476 serializeList(settings, sb, path, (List<String>) listEle);
477 path.remove(path.size() - 1);
479 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
485 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
490 for (String pathEle : path) {
491 sb.append(pathEle).append('.');
494 settings.put(sb.toString(), value.toString());
497 void parseDataAndPolicyNodes(Map<String,String> map){
498 for(String key:map.keySet()){
499 if(key.contains("policy.nodes.Root"))
503 else if(key.contains("policy.nodes")){
504 String wordToFind = "policy.nodes.";
505 int indexForPolicyNode=key.indexOf(wordToFind);
506 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
508 stringBetweenDots(subNodeString);
510 else if(key.contains("policy.data")){
511 String wordToFind="policy.data.";
512 int indexForPolicyNode=key.indexOf(wordToFind);
513 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
515 stringBetweenDotsForDataFields(subNodeString);
520 HashMap<String,String> parseDataNodes(Map<String,String> map){
521 HashMap<String,String> dataMapForJson=new HashMap <>();
522 for(String uniqueDataKey: uniqueDataKeys){
523 if(uniqueDataKey.contains("%")){
524 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
525 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
526 String typeValue=map.get(findType);
527 LOGGER.info(typeValue);
528 if(typeValue != null && typeValue.equalsIgnoreCase(STRING)||
529 typeValue.equalsIgnoreCase(INTEGER)
532 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
533 String defaultValue= map.get(findDefault);
534 LOGGER.info("defaultValue is:"+ defaultValue);
536 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
537 String requiredValue= map.get(findRequired);
538 LOGGER.info("requiredValue is:"+ requiredValue);
540 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
541 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
542 attributeIndividualStringBuilder.append(defaultValue+":required-");
543 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
544 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
546 else if(typeValue != null && typeValue.equalsIgnoreCase(LIST)){
547 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
548 String listValue=map.get(findList);
550 LOGGER.info("Type of list is:"+ listValue);
552 if(listValue.contains(".")){
553 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
554 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
555 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
556 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
559 StringBuilder stringListItems= new StringBuilder();
560 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
561 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
562 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
563 for(int i=0;i<10;i++){
564 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
565 String constraintsValue=map.get(findConstraints);
566 LOGGER.info(constraintsValue);
567 if(constraintsValue==null){
571 dataConstraints.add(constraintsValue);
572 dataListBuffer.append(constraintsValue+",");
575 dataListBuffer.append("]#");
577 LOGGER.info(dataListBuffer);
582 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
583 String userDefinedValue=map.get(findUserDefined);
584 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
585 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
586 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
587 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
592 return dataMapForJson;
595 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
596 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
597 HashMap<String,String> hmSub;
598 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
599 String uniqueDataKey= entry.getKey();
600 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
601 String value= dataMapForJson.get(uniqueDataKey);
602 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
603 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
604 hmSub.put(uniqueDataKeySplit[1], value);
607 hmSub=new HashMap <>();
608 hmSub.put(uniqueDataKeySplit[1], value);
611 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
614 JSONObject mainObject= new JSONObject();
616 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
617 String s=entry.getKey();
618 json= new JSONObject();
619 HashMap<String,String> jsonHm=dataMapKey.get(s);
620 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
621 String key=entryMap.getKey();
622 json.put(key, jsonHm.get(key));
624 mainObject.put(s,json);
626 Iterator<String> keysItr = mainObject.keys();
627 while(keysItr.hasNext()) {
628 String key = keysItr.next();
629 String value = mainObject.get(key).toString();
630 retmap.put(key, value);
633 LOGGER.info("#############################################################################");
634 LOGGER.info(mainObject);
635 LOGGER.info("###############################################################################");
639 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
640 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
641 for(String uniqueKey: uniqueKeys){
642 HashMap<String,String> hm;
644 for(Map.Entry<String,String> entry:map.entrySet()){
645 String key=entry.getKey();
646 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
647 if(mapKey.containsKey(uniqueKey)){
648 hm = mapKey.get(uniqueKey);
649 String keyStr= key.substring(key.lastIndexOf('.')+1);
650 String valueStr= map.get(key);
651 if(("type").equals(keyStr)){
652 if(!key.contains("entry_schema"))
654 hm.put(keyStr,valueStr);
657 hm.put(keyStr,valueStr);
661 hm = new HashMap <>();
662 String keyStr= key.substring(key.lastIndexOf('.')+1);
663 String valueStr= map.get(key);
664 if(("type").equals(keyStr)){
665 if(!key.contains("entry_schema"))
667 hm.put(keyStr,valueStr);
670 hm.put(keyStr,valueStr);
672 mapKey.put(uniqueKey, hm);
680 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
681 StringBuilder attributeStringBuilder= new StringBuilder();
682 StringBuilder referenceStringBuilder= new StringBuilder();
683 StringBuilder listBuffer= new StringBuilder();
684 List<String> constraints= new ArrayList<>();
685 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
686 String keySetString= entry.getKey();
687 HashMap<String,String> keyValues=mapKey.get(keySetString);
688 if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(STRING)||
689 keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(INTEGER)
691 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
692 attributeIndividualStringBuilder.append(keySetString+"=");
693 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
694 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
695 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
696 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
699 else if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(LIST)){
701 Set<String> keys= keyValues.keySet();
702 Iterator<String> itr=keys.iterator();
703 while(itr.hasNext()){
704 String key= itr.next();
705 if((!("type").equals(key) ||("required").equals(key)))
707 String value= keyValues.get(key);
708 //The "." in the value determines if its a string or a user defined type.
709 if (!value.contains(".")){
711 constraints.add(keyValues.get(key));
713 //This is userdefined string
714 String trimValue=value.substring(value.lastIndexOf('.')+1);
715 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
716 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
717 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
723 //User defined Datatype.
724 String value=keyValues.get("type");
725 if(value != null && !value.isEmpty()){
726 String trimValue=value.substring(value.lastIndexOf('.')+1);
727 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
728 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
729 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
731 LOGGER.info("keyValues.get(type) is null/empty");
735 if(constraints!=null &&constraints.isEmpty()==false){
737 listBuffer.append(keySetString.toUpperCase()+"=[");
738 for(String str:constraints){
739 listBuffer.append(str+",");
741 listBuffer.append("]#");
742 LOGGER.info(listBuffer);
745 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
746 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
747 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
752 dataListBuffer.append(listBuffer);
755 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
756 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
757 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
758 LOGGER.info("List String is:"+listBuffer);
759 LOGGER.info("Data list buffer is:"+dataListBuffer);
760 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
762 this.listConstraints=dataListBuffer.toString();
763 this.referenceAttributes=referenceStringBuilder.toString();
764 this.attributeString=attributeStringBuilder.toString();
769 public void parseTosca (String fileName){
770 Map<String,String> map= new HashMap<>();
775 parseDataAndPolicyNodes(map);
777 HashMap<String,String> dataMapForJson=parseDataNodes(map);
779 constructJsonForDataFields(dataMapForJson);
781 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
783 createAttributes(mapKey);
785 } catch (IOException e) {
791 private String cleanUPJson(String json) {
792 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
793 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
794 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
796 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
797 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
798 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
799 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
800 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
801 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
802 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
803 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
804 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
805 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
809 private JSONObject decodeContent(JsonNode jsonNode){
810 Iterator<JsonNode> jsonElements = jsonNode.elements();
811 Iterator<String> jsonKeys = jsonNode.fieldNames();
812 Map<String,String> element = new TreeMap<>();
813 while(jsonElements.hasNext() && jsonKeys.hasNext()){
814 element.put(jsonKeys.next(), jsonElements.next().toString());
816 JSONObject jsonResult = new JSONObject();
817 JSONArray jsonArray = null;
818 String oldValue = null;
819 String nodeKey = null;
820 String arryKey = null;
821 Boolean isArray = false;
822 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
823 ObjectNode node = nodeFactory.objectNode();
824 String prevKey = null;
825 String presKey = null;
826 for(String key: element.keySet()){
827 if(key.contains(".")){
828 presKey = key.substring(0,key.indexOf("."));
829 }else if(key.contains("@")){
830 presKey = key.substring(0,key.indexOf("@"));
834 // first check if we are different from old.
835 LOGGER.info(key+"\n");
836 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
837 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
838 jsonResult.put(oldValue, jsonArray);
839 jsonArray = new JSONArray();
841 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
842 jsonResult.put(oldValue, jsonArray);
844 jsonArray = new JSONArray();
849 if(key.contains(".")){
851 nodeKey = key.substring(0,key.indexOf("."));
853 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
854 node.put(key.substring(key.indexOf(".")+1), element.get(key));
857 if(nodeKey.contains("@")){
859 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
861 if(nodeKey.endsWith("@0")){
863 jsonArray = new JSONArray();
865 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
866 jsonArray.put(decodeContent(node));
868 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){
869 jsonResult.put(arryKey, jsonArray);
870 jsonArray = new JSONArray();
872 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
875 jsonResult.put(nodeKey, decodeContent(node));
877 node = nodeFactory.objectNode();
879 nodeKey = key.substring(0,key.indexOf("."));
880 if(nodeKey.contains("@")){
881 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
883 node.put(key.substring(key.indexOf(".")+1), element.get(key));
885 }else if(node.size()!=0){
886 if(nodeKey.contains("@")){
888 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
890 if(nodeKey.endsWith("@0")){
892 jsonArray = new JSONArray();
894 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
895 jsonArray.put(decodeContent(node));
897 jsonResult.put(arryKey, jsonArray);
898 jsonArray = new JSONArray();
899 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
902 jsonResult.put(nodeKey, decodeContent(node));
904 node = nodeFactory.objectNode();
905 if(key.contains("@")){
907 if(key.endsWith("@0")|| jsonArray==null){
908 jsonArray = new JSONArray();
910 }else if(!key.contains("@")){
915 oldValue = key.substring(0,key.indexOf("@"));
917 if(oldValue!=prevKey){
918 oldValue = key.substring(0,key.indexOf("@"));
920 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
921 jsonArray.put(element.get(key));
923 jsonResult.put(oldValue, jsonArray);
924 jsonArray = new JSONArray();
926 oldValue = key.substring(0,key.indexOf("@"));
928 jsonResult.put(key, element.get(key));
931 if(key.contains("@")){
933 if(key.endsWith("@0")|| jsonArray==null){
934 jsonArray = new JSONArray();
936 }else if(!key.contains("@")){
941 oldValue = key.substring(0,key.indexOf("@"));
943 if(oldValue!=prevKey){
944 oldValue = key.substring(0,key.indexOf("@"));
946 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
947 jsonArray.put(element.get(key));
949 jsonResult.put(oldValue, jsonArray);
950 jsonArray = new JSONArray();
952 oldValue = key.substring(0,key.indexOf("@"));
954 jsonResult.put(key, element.get(key));
959 if(nodeKey.contains("@")){
961 jsonArray = new JSONArray();
964 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
966 jsonArray.put(decodeContent(node));
967 jsonResult.put(arryKey, jsonArray);
970 jsonResult.put(nodeKey, decodeContent(node));
973 if(isArray && jsonArray.length() > 0){
974 jsonResult.put(oldValue, jsonArray);
979 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
980 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
981 ObjectMapper mapper = new ObjectMapper();
982 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
983 JsonNode root = mapper.readTree(request.getReader());
985 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
986 String servicename = value.toString().split("-v")[0];
987 String version = null;
988 if (value.toString().contains("-v")){
989 version = value.toString().split("-v")[1];
991 MicroServiceModels returnModel = getAttributeObject(servicename, version);
994 //Get all keys with "MANY-true" defined in their value from subAttribute
995 Set<String> allkeys = null;
996 if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
997 JSONObject json = new JSONObject(returnModel.getSub_attributes());
999 allkeys = allManyTrueKeys;
1000 allManyTrueKeys = new HashSet <>();
1001 LOGGER.info("allkeys : " + allkeys);
1004 String allManyTrueKeys = "";
1005 if(allkeys != null){
1006 allManyTrueKeys = allkeys.toString();
1009 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
1011 JSONObject jsonObject = new JSONObject(jsonModel);
1013 JSONObject finalJsonObject = null;
1014 if(allkeys != null){
1015 Iterator<String> iter = allkeys.iterator();
1016 while(iter.hasNext()){
1017 //convert to array values for MANY-true keys
1018 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
1022 if(finalJsonObject != null){
1023 LOGGER.info(finalJsonObject.toString());
1024 jsonModel = finalJsonObject.toString();
1027 //get all properties with "MANY-true" defined in Ref_attributes
1028 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
1029 if(manyTrueProperties != null){
1030 JSONObject jsonObj = new JSONObject(jsonModel);
1031 for (String s : manyTrueProperties) {
1033 //convert to array element for MANY-true properties
1034 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
1037 if(finalJsonObject != null){
1038 LOGGER.info(finalJsonObject.toString());
1039 jsonModel = finalJsonObject.toString();
1043 response.setCharacterEncoding("UTF-8");
1044 response.setContentType("application / json");
1045 request.setCharacterEncoding("UTF-8");
1046 List<Object> list = new ArrayList<>();
1047 PrintWriter out = response.getWriter();
1048 String responseString = mapper.writeValueAsString(returnModel);
1049 JSONObject j = null;
1050 if("".equals(allManyTrueKeys)){
1051 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
1053 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+ "}");
1056 out.write(list.toString());
1060 @SuppressWarnings({ "unchecked", "rawtypes" })
1061 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
1062 Map<String, String> attributeMap = new HashMap<>();
1063 Map<String, String> refAttributeMap = new HashMap<>();
1064 String attribute = returnModel.getAttributes();
1065 if(attribute != null){
1066 attribute = attribute.trim();
1068 String refAttribute = returnModel.getRef_attributes();
1069 if(refAttribute != null){
1070 refAttribute = refAttribute.trim();
1072 String enumAttribute = returnModel.getEnumValues();
1073 if(enumAttribute != null){
1074 enumAttribute = enumAttribute.trim();
1076 if (!StringUtils.isEmpty(attribute)){
1077 attributeMap = convert(attribute, ",");
1079 if (!StringUtils.isEmpty(refAttribute)){
1080 refAttributeMap = convert(refAttribute, ",");
1083 Gson gson = new Gson();
1085 String subAttributes = returnModel.getSub_attributes();
1086 if(subAttributes != null){
1087 subAttributes = subAttributes.trim();
1091 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1093 JSONObject object = new JSONObject();
1094 JSONArray array = new JSONArray();
1096 for (Entry<String, String> keySet : attributeMap.entrySet()){
1097 array = new JSONArray();
1098 String value = keySet.getValue();
1099 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1101 object.put(keySet.getKey().trim(), array);
1103 object.put(keySet.getKey().trim(), value.trim());
1107 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1108 array = new JSONArray();
1109 String value = keySet.getValue().split(":")[0];
1110 if (gsonObject.containsKey(value)){
1111 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1112 array.put(recursiveReference(value, gsonObject, enumAttribute));
1113 object.put(keySet.getKey().trim(), array);
1115 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1118 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1119 array.put(value.trim());
1120 object.put(keySet.getKey().trim(), array);
1122 object.put(keySet.getKey().trim(), value.trim());
1129 return object.toString();
1132 @SuppressWarnings("unchecked")
1133 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1134 JSONObject object = new JSONObject();
1135 Map<String, String> map = new HashMap<>();
1136 Object returnClass = subAttributeMap.get(name);
1137 map = (Map<String, String>) returnClass;
1138 JSONArray array = new JSONArray();
1140 for( Entry<String, String> m:map.entrySet()){
1141 String[] splitValue = m.getValue().split(":");
1142 array = new JSONArray();
1143 if (subAttributeMap.containsKey(splitValue[0])){
1144 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1145 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1146 object.put(m.getKey().trim(), array);
1148 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1151 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1152 array.put(splitValue[0].trim());
1153 object.put(m.getKey().trim(), array);
1155 object.put(m.getKey().trim(), splitValue[0].trim());
1164 public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1165 return convertToArrayElement(json, new HashSet<>(), keyValue);
1168 private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1169 for (String key : json.keySet()) {
1170 Object obj = json.get(key);
1171 if(key.equals(keyValue.trim())){
1172 if(!(obj instanceof JSONArray)){
1173 JSONArray newJsonArray = new JSONArray();
1174 newJsonArray.put(obj);
1175 json.put(key, newJsonArray);
1177 LOGGER.info("key : " + key);
1178 LOGGER.info("obj : " + obj);
1179 LOGGER.info("json.get(key) : " + json.get(key));
1180 LOGGER.info("keyValue : " + keyValue);
1181 keys.addAll(json.keySet());
1186 if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);
1192 // call this method to get all MANY-true properties
1193 public static Set<String> getManyTrueProperties(String referAttributes){
1194 LOGGER.info("referAttributes : " + referAttributes);
1195 Set<String> manyTrueProperties = new HashSet<>();
1197 if(referAttributes != null){
1198 String[] referAarray = referAttributes.split(",");
1199 String []element= null;
1200 for(int i=0; i<referAarray.length; i++){
1201 element = referAarray[i].split("=");
1202 if(element.length > 1 && element[1].contains("MANY-true")){
1203 manyTrueProperties.add(element[0]);
1208 return manyTrueProperties;
1211 //call this method to start the recursive
1212 private Set<String> getAllKeys(JSONObject json) {
1213 return getAllKeys(json, new HashSet<>());
1216 private Set<String> getAllKeys(JSONArray arr) {
1217 return getAllKeys(arr, new HashSet<>());
1220 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1221 for (int i = 0; i < arr.length(); i++) {
1222 Object obj = arr.get(i);
1223 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
1224 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
1229 // this method returns a set of keys with "MANY-true" defined in their value.
1230 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1231 for (String key : json.keySet()) {
1232 Object obj = json.get(key);
1233 if(obj instanceof String && ((String) obj).contains("MANY-true")){
1234 LOGGER.info("key : " + key);
1235 LOGGER.info("obj : " + obj);
1236 allManyTrueKeys.add(key);
1238 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
1239 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
1246 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1247 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1248 ObjectMapper mapper = new ObjectMapper();
1249 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1250 JsonNode root = mapper.readTree(request.getReader());
1252 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1253 String servicename = value.toString().split("-v")[0];
1254 Set<String> returnList = getVersionList(servicename);
1256 response.setCharacterEncoding("UTF-8");
1257 response.setContentType("application / json");
1258 request.setCharacterEncoding("UTF-8");
1259 List<Object> list = new ArrayList<>();
1260 PrintWriter out = response.getWriter();
1261 String responseString = mapper.writeValueAsString(returnList);
1262 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1264 out.write(list.toString());
1268 private Set<String> getVersionList(String name) {
1269 MicroServiceModels workingModel = new MicroServiceModels();
1270 Set<String> list = new HashSet<>();
1271 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1272 for (int i = 0; i < microServiceModelsData.size(); i++) {
1273 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1274 if (workingModel.getVersion()!=null){
1275 list.add(workingModel.getVersion());
1277 list.add("Default");
1283 private MicroServiceModels getAttributeObject(String name, String version) {
1284 MicroServiceModels workingModel = new MicroServiceModels();
1285 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1286 for (int i = 0; i < microServiceModelsData.size(); i++) {
1287 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1288 if(version != null){
1289 if (workingModel.getVersion()!=null){
1290 if (workingModel.getVersion().equals(version)){
1291 return workingModel;
1294 return workingModel;
1297 return workingModel;
1301 return workingModel;
1304 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1305 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1307 Map<String, Object> model = new HashMap<>();
1308 ObjectMapper mapper = new ObjectMapper();
1309 List<String> priorityList = new ArrayList<>();
1311 for (int i = 1; i < priorityCount; i++) {
1312 priorityList.add(String.valueOf(i));
1314 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1315 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1316 JSONObject j = new JSONObject(msg);
1317 response.getWriter().write(j.toString());
1319 catch (Exception e){
1324 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1325 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1326 Object policyData = policyAdapter.getPolicyData();
1327 PolicyType policy = (PolicyType) policyData;
1328 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1329 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1330 policyAdapter.setPolicyName(policyNameValue);
1331 String description = "";
1333 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1334 }catch(Exception e){
1335 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1336 description = policy.getDescription();
1338 policyAdapter.setPolicyDescription(description);
1339 // Get the target data under policy.
1340 TargetType target = policy.getTarget();
1341 if (target != null) {
1342 // Under target we have AnyOFType
1343 List<AnyOfType> anyOfList = target.getAnyOf();
1344 if (anyOfList != null) {
1345 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1346 while (iterAnyOf.hasNext()) {
1347 AnyOfType anyOf = iterAnyOf.next();
1348 // Under AnyOFType we have AllOFType
1349 List<AllOfType> allOfList = anyOf.getAllOf();
1350 if (allOfList != null) {
1351 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1352 while (iterAllOf.hasNext()) {
1353 AllOfType allOf = iterAllOf.next();
1354 // Under AllOFType we have Match
1355 List<MatchType> matchList = allOf.getMatch();
1356 if (matchList != null) {
1357 Iterator<MatchType> iterMatch = matchList.iterator();
1358 while (matchList.size()>1 && iterMatch.hasNext()) {
1359 MatchType match = iterMatch.next();
1361 // Under the match we have attribute value and
1362 // attributeDesignator. So,finally down to the actual attribute.
1364 AttributeValueType attributeValue = match.getAttributeValue();
1365 String value = (String) attributeValue.getContent().get(0);
1366 AttributeDesignatorType designator = match.getAttributeDesignator();
1367 String attributeId = designator.getAttributeId();
1368 // First match in the target is OnapName, so set that value.
1369 if (attributeId.equals("ONAPName")) {
1370 policyAdapter.setOnapName(value);
1372 if (attributeId.equals("ConfigName")){
1373 policyAdapter.setConfigName(value);
1375 if (attributeId.equals("uuid")){
1376 policyAdapter.setUuid(value);
1378 if (attributeId.equals("location")){
1379 policyAdapter.setLocation(value);
1381 if (attributeId.equals("RiskType")){
1382 policyAdapter.setRiskType(value);
1384 if (attributeId.equals("RiskLevel")){
1385 policyAdapter.setRiskLevel(value);
1387 if (attributeId.equals("guard")){
1388 policyAdapter.setGuard(value);
1390 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1391 PolicyController controller = new PolicyController();
1392 String newDate = controller.convertDate(value);
1393 policyAdapter.setTtlDate(newDate);
1396 readFile(policyAdapter, entity);
1406 public static Map<String, String> convert(String str, String split) {
1407 Map<String, String> map = new HashMap<>();
1408 for(final String entry : str.split(split)) {
1409 String[] parts = entry.split("=");
1410 map.put(parts[0], parts[1]);
1416 @SuppressWarnings("unchecked")
1417 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1418 String policyScopeName = null;
1419 ObjectMapper mapper = new ObjectMapper();
1421 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1422 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1423 policyAdapter.setPolicyScope(policyScopeName);
1425 policyAdapter.setPriority(msBody.getPriority());
1427 if (msBody.getVersion()!= null){
1428 policyAdapter.setServiceType(msBody.getService());
1429 policyAdapter.setVersion(msBody.getVersion());
1431 policyAdapter.setServiceType(msBody.getService());
1433 if(msBody.getContent() != null){
1434 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1435 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1436 readRecursivlyJSONContent(map, data);
1437 policyAdapter.setRuleData(data);
1440 } catch (Exception e) {
1446 @SuppressWarnings({ "rawtypes", "unchecked" })
1447 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1448 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1449 Object key = iterator.next();
1450 Object value = map.get(key);
1451 if(value instanceof LinkedHashMap<?, ?>){
1452 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1453 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1454 for(String objKey: secondObjec.keySet()){
1455 data.put(key+"." +objKey, secondObjec.get(objKey));
1457 }else if(value instanceof ArrayList){
1458 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1459 for(int i = 0; i < jsonArrayVal.size(); i++){
1460 Object arrayvalue = jsonArrayVal.get(i);
1461 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1462 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1463 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1464 for(String objKey: newData.keySet()){
1465 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1467 }else if(arrayvalue instanceof ArrayList){
1468 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1469 for(int j = 0; j < jsonArrayVal1.size(); j++){
1470 Object arrayvalue1 = jsonArrayVal1.get(i);
1471 data.put(key+"@"+j, arrayvalue1.toString());
1474 data.put(key+"@"+i, arrayvalue.toString());
1478 data.put(key.toString(), value.toString());
1483 private String getPolicyScope(String value) {
1484 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1485 if(groupList != null && !groupList.isEmpty()){
1486 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1487 return pScope.getGroupName();
1492 //Convert the map values and set into JSON body
1493 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1494 Map<String, String> attribute = new HashMap<>();
1498 for (Entry<String, String> entry : attributesMap.entrySet()) {
1499 key = entry.getKey();
1500 value = entry.getValue();
1501 attribute.put(key, value);
1503 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1504 key = entryRef.getKey();
1505 value = entryRef.getValue().toString();
1506 attribute.put(key, value);
1508 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1509 key = entryList.getKey();
1510 value = entryList.getValue().toString();
1511 attribute.put(key, value);
1513 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1514 key = arrayList.getKey();
1516 for (Object textList : arrayList.getValue()){
1518 temp = "[" + textList;
1520 temp = temp + "," + textList;
1523 attribute.put(key, temp+ "]");
1529 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1530 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1531 modelList = new ArrayList<>();
1532 dirDependencyList = new ArrayList<>();
1533 classMap = new HashMap<>();
1534 retmap = new HashMap<>();
1535 uniqueKeys= new HashSet<>();
1536 uniqueDataKeys= new HashSet<>();
1537 dataListBuffer=new StringBuilder();
1538 dataConstraints= new ArrayList <>();
1539 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1540 boolean zip = false;
1542 String errorMsg = "";
1543 for (FileItem item : items) {
1544 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1545 this.newModel = new MicroServiceModels();
1547 File file = new File(item.getName());
1548 OutputStream outputStream = new FileOutputStream(file);
1549 IOUtils.copy(item.getInputStream(), outputStream);
1550 outputStream.close();
1551 this.newFile = file.toString();
1552 this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
1554 if (this.newFile.toString().contains("-v")){
1555 if (item.getName().endsWith(".zip")){
1556 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
1558 }else if(item.getName().endsWith(".yml")){
1559 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
1563 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
1566 errorMsg = "Upload error: The file name should contain '-v', such as xxx-v1802.yml";
1569 }catch(Exception e){
1570 LOGGER.error("Upload error : ", e);
1571 errorMsg = "Upload error:" + e.getMessage();
1576 List<File> fileList = new ArrayList<>();
1577 this.directory = "model";
1579 extractFolder(this.newFile);
1580 fileList = listModelFiles(this.directory);
1581 }else if (yml==true){
1582 parseTosca(this.newFile);
1584 File file = new File(this.newFile);
1587 String modelType= "";
1590 //Process Main Model file first
1591 classMap = new HashMap<>();
1592 for (File file : fileList) {
1593 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1594 retreiveDependency(file.toString(), true);
1598 modelList = createList();
1600 cleanUp(this.newFile);
1604 modelList.add(this.newModel.getModelName());
1605 String className=this.newModel.getModelName();
1606 MSAttributeObject msAttributes= new MSAttributeObject();
1607 msAttributes.setClassName(className);
1609 HashMap<String, String> returnAttributeList =new HashMap<>();
1610 returnAttributeList.put(className, this.attributeString);
1611 msAttributes.setAttribute(returnAttributeList);
1613 msAttributes.setSubClass(this.retmap);
1615 HashMap<String, String> returnReferenceList =new HashMap<>();
1616 //String[] referenceArray=this.referenceAttributes.split("=");
1617 returnReferenceList.put(className, this.referenceAttributes);
1618 msAttributes.setRefAttribute(returnReferenceList);
1620 if(this.listConstraints!=""){
1621 HashMap<String, String> enumList =new HashMap<>();
1622 String[] listArray=this.listConstraints.split("#");
1623 for(String str:listArray){
1624 String[] strArr= str.split("=");
1625 if(strArr.length>1){
1626 enumList.put(strArr[0], strArr[1]);
1629 msAttributes.setEnumType(enumList);
1632 classMap=new HashMap<>();
1633 classMap.put(className, msAttributes);
1637 PrintWriter out = response.getWriter();
1639 response.setCharacterEncoding("UTF-8");
1640 response.setContentType("application / json");
1641 request.setCharacterEncoding("UTF-8");
1643 ObjectMapper mapper = new ObjectMapper();
1644 JSONObject j = new JSONObject();
1645 j.put("classListDatas", modelList);
1646 j.put("modelDatas", mapper.writeValueAsString(classMap));
1647 j.put("modelType", modelType);
1648 out.write(j.toString());
1652 * Unzip file and store in the model directory for processing
1654 @SuppressWarnings("rawtypes")
1655 private void extractFolder(String zipFile ) {
1657 File file = new File(zipFile);
1661 zip = new ZipFile(file);
1662 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1663 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1664 checkZipDirectory(this.directory);
1665 new File(newPath).mkdir();
1666 Enumeration zipFileEntries = zip.entries();
1668 // Process each entry
1669 while (zipFileEntries.hasMoreElements()){
1670 // grab a zip file entry
1671 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1672 String currentEntry = entry.getName();
1673 File destFile = new File("model" + File.separator + currentEntry);
1674 File destinationParent = destFile.getParentFile();
1676 destinationParent.mkdirs();
1678 if (!entry.isDirectory()){
1679 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1681 byte data[] = new byte[BUFFER];
1682 FileOutputStream fos = new FileOutputStream(destFile);
1683 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1684 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1685 dest.write(data, 0, currentByte);
1692 if (currentEntry.endsWith(".zip")){
1693 extractFolder(destFile.getAbsolutePath());
1696 } catch (IOException e) {
1697 LOGGER.error("Failed to unzip model file " + zipFile, e);
1702 } catch (IOException e) {
1703 LOGGER.error("Exception Occured While closing zipfile " + e);
1708 private void retreiveDependency(String workingFile, Boolean modelClass) {
1710 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1711 HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
1713 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1715 classMap.putAll(tempMap);
1716 LOGGER.info(tempMap);
1722 private List<File> listModelFiles(String directoryName) {
1723 File directory = new File(directoryName);
1724 List<File> resultList = new ArrayList<>();
1725 File[] fList = directory.listFiles();
1726 for (File file : fList) {
1727 if (file.isFile()) {
1728 resultList.add(file);
1729 } else if (file.isDirectory()) {
1730 dirDependencyList.add(file.getName());
1731 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1737 private void cleanUp(String path) {
1740 FileUtils.forceDelete(new File(path));
1741 } catch (IOException e) {
1742 LOGGER.error("Failed to delete folder " + path, e);
1747 private void checkZipDirectory(String zipDirectory) {
1748 Path path = Paths.get(zipDirectory);
1750 if (Files.exists(path)) {
1751 cleanUp(zipDirectory);
1755 private List<String> createList() {
1756 List<String> list = new ArrayList<>();
1757 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1758 if (cMap.getValue().isPolicyTempalate()){
1759 list.add(cMap.getKey());
1764 if (list.isEmpty()){
1765 if (classMap.containsKey(this.newModel.getModelName())){
1766 list.add(this.newModel.getModelName());
1774 public Map<String, String> getAttributesListRefMap() {
1775 return attributesListRefMap;
1778 public Map<String, LinkedList<String>> getArrayTextList() {
1779 return arrayTextList;
1784 class DCAEMicroServiceObject {
1786 private String service;
1787 private String location;
1788 private String uuid;
1789 private String policyName;
1790 private String description;
1791 private String configName;
1792 private String templateVersion;
1793 private String version;
1794 private String priority;
1795 private String policyScope;
1796 private String riskType;
1797 private String riskLevel;
1798 private String guard = null;
1800 public String getGuard() {
1803 public void setGuard(String guard) {
1806 public String getRiskType() {
1809 public void setRiskType(String riskType) {
1810 this.riskType = riskType;
1812 public String getRiskLevel() {
1815 public void setRiskLevel(String riskLevel) {
1816 this.riskLevel = riskLevel;
1818 public String getPolicyScope() {
1821 public void setPolicyScope(String policyScope) {
1822 this.policyScope = policyScope;
1825 public String getPriority() {
1828 public void setPriority(String priority) {
1829 this.priority = priority;
1831 public String getVersion() {
1834 public void setVersion(String version) {
1835 this.version = version;
1837 private Object content;
1840 public String getPolicyName() {
1843 public void setPolicyName(String policyName) {
1844 this.policyName = policyName;
1846 public String getDescription() {
1849 public void setDescription(String description) {
1850 this.description = description;
1852 public String getConfigName() {
1855 public void setConfigName(String configName) {
1856 this.configName = configName;
1858 public Object getContent() {
1861 public void setContent(Object content) {
1862 this.content = content;
1865 public String getService() {
1868 public void setService(String service) {
1869 this.service = service;
1871 public String getLocation() {
1874 public void setLocation(String location) {
1875 this.location = location;
1878 public String getUuid() {
1881 public void setUuid(String uuid) {
1884 public String getTemplateVersion() {
1885 return templateVersion;
1887 public void setTemplateVersion(String templateVersion) {
1888 this.templateVersion = templateVersion;