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 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
195 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
196 ObjectWriter om = new ObjectMapper().writer();
198 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
199 MicroServiceModels returnModel = new MicroServiceModels();
200 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
201 if(policyAdapter.getServiceType() !=null){
202 microServiceObject.setService(policyAdapter.getServiceType());
203 microServiceObject.setVersion(policyAdapter.getVersion());
204 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
206 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
207 if(policyAdapter.getUuid()!=null){
208 microServiceObject.setUuid(policyAdapter.getUuid());
210 if(policyAdapter.getLocation()!=null){
211 microServiceObject.setLocation(policyAdapter.getLocation());
213 if(policyAdapter.getConfigName()!=null){
214 microServiceObject.setConfigName(policyAdapter.getConfigName());
216 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
217 if(policyScopeValue!=null){
218 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
222 if(policyAdapter.getPolicyName()!=null){
223 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
225 if(policyAdapter.getPolicyDescription()!=null){
226 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
228 if (policyAdapter.getPriority()!=null){
229 microServiceObject.setPriority(policyAdapter.getPriority());
231 microServiceObject.setPriority("9999");
234 if (policyAdapter.getRiskLevel()!=null){
235 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
237 if (policyAdapter.getRiskType()!=null){
238 microServiceObject.setRiskType(policyAdapter.getRiskType());
240 if (policyAdapter.getGuard()!=null){
241 microServiceObject.setGuard(policyAdapter.getGuard());
243 microServiceObject.setContent(jsonContent);
246 json = om.writeValueAsString(microServiceObject);
247 } catch (JsonProcessingException e) {
248 LOGGER.error("Error writing out the object", e);
250 LOGGER.info("input json: " + json);
251 LOGGER.info("input jsonContent: " + jsonContent);
252 String cleanJson = cleanUPJson(json);
253 //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
254 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
255 LOGGER.info("tempJson: " + tempJson);
256 cleanJson = removeNullAttributes(tempJson);
257 policyAdapter.setJsonBody(cleanJson);
258 return policyAdapter;
261 private String removeNullAttributes(String cleanJson) {
262 ObjectMapper mapper = new ObjectMapper();
265 JsonNode rootNode = mapper.readTree(cleanJson);
266 JsonNode returnNode = mapper.readTree(cleanJson);
267 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
268 boolean remove = false;
269 JsonObject removed = null;
270 boolean contentChanged = false;
271 while (fieldsIterator.hasNext()) {
272 Map.Entry<String, JsonNode> field = fieldsIterator.next();
273 final String key = field.getKey();
274 final JsonNode value = field.getValue();
275 if("content".equalsIgnoreCase(key)){
276 String contentStr = value.toString();
277 try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
278 JsonObject jsonContent = reader.readObject();
279 removed = removeNull(jsonContent);
280 if(!jsonContent.toString().equals(removed.toString())){
281 contentChanged = true;
285 if (value==null || value.isNull()){
286 ((ObjectNode) returnNode).remove(key);
291 cleanJson = returnNode.toString();
293 if (value==null || value.isNull()){
294 ((ObjectNode) returnNode).remove(key);
299 cleanJson = returnNode.toString();
303 //set modified content to cleanJson
304 JSONObject jObject = new JSONObject(cleanJson);
305 jObject.put("content",removed.toString());
306 cleanJson = cleanUPJson(jObject.toString());
309 } catch (IOException e) {
310 LOGGER.error("Error writing out the JsonNode",e);
315 public static JsonArray removeNull(JsonArray array) {
316 JsonArrayBuilder builder = Json.createArrayBuilder();
318 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
319 JsonValue value = it.next();
320 switch (value.getValueType()) {
322 JsonArray a = removeNull(array.getJsonArray(i));
327 JsonObject object = removeNull(array.getJsonObject(i));
328 if (!object.isEmpty())
332 String s = array.getString(i);
333 if (s != null && !s.isEmpty())
337 builder.add(array.getJsonNumber(i));
341 builder.add(array.getBoolean(i));
347 return builder.build();
350 public static JsonObject removeNull(JsonObject obj) {
351 JsonObjectBuilder builder = Json.createObjectBuilder();
352 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
353 Entry<String, JsonValue> e = it.next();
354 String key = e.getKey();
355 JsonValue value = e.getValue();
356 switch (value.getValueType()) {
358 JsonArray array = removeNull(obj.getJsonArray(key));
359 if (!array.isEmpty())
360 builder.add(key, array);
363 JsonObject object = removeNull(obj.getJsonObject(key));
364 if (!object.isEmpty())
365 builder.add(key, object);
368 String s = obj.getString(key);
369 if (s != null && !s.isEmpty())
373 builder.add(key, obj.getJsonNumber(key));
377 builder.add(key, obj.getBoolean(key));
383 return builder.build();
386 // Second index of dot should be returned.
387 public int stringBetweenDots(String str){
388 String stringToSearch=str;
389 String[]ss=stringToSearch.split("\\.");
393 uniqueKeys.add(ss[2]);
397 return uniqueKeys.size();
400 public void stringBetweenDotsForDataFields(String str){
401 String stringToSearch=str;
402 String[]ss=stringToSearch.split("\\.");
407 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
413 @SuppressWarnings("unchecked")
414 public Map<String, String> load(String fileName) throws IOException {
415 File newConfiguration = new File(fileName);
416 Yaml yaml = new Yaml();
417 Map<Object, Object> yamlMap = null;
418 try(InputStream is = new FileInputStream(newConfiguration)){
419 yamlMap = (Map<Object, Object>) yaml.load(is);
420 } catch (FileNotFoundException e) {
424 StringBuilder sb = new StringBuilder();
425 Map<String, String> settings = new HashMap<>();
426 if (yamlMap == null) {
429 List<String> path = new ArrayList <>();
430 serializeMap(settings, sb, path, yamlMap);
434 public Map<String, String> load(byte[] source) throws IOException {
435 Yaml yaml = new Yaml();
436 @SuppressWarnings("unchecked")
437 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
438 StringBuilder sb = new StringBuilder();
439 Map<String, String> settings = new HashMap <>();
440 if (yamlMap == null) {
443 List<String> path = new ArrayList <>();
444 serializeMap(settings, sb, path, yamlMap);
448 @SuppressWarnings({ "unchecked", "rawtypes" })
449 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
450 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
451 if (entry.getValue() instanceof Map) {
452 path.add((String) entry.getKey());
453 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
454 path.remove(path.size() - 1);
455 } else if (entry.getValue() instanceof List) {
456 path.add((String) entry.getKey());
457 serializeList(settings, sb, path, (List) entry.getValue());
458 path.remove(path.size() - 1);
460 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
465 @SuppressWarnings("unchecked")
466 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
468 for (Object listEle : yamlList) {
469 if (listEle instanceof Map) {
470 path.add(Integer.toString(counter));
471 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
472 path.remove(path.size() - 1);
473 } else if (listEle instanceof List) {
474 path.add(Integer.toString(counter));
475 serializeList(settings, sb, path, (List<String>) listEle);
476 path.remove(path.size() - 1);
478 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
484 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
489 for (String pathEle : path) {
490 sb.append(pathEle).append('.');
493 settings.put(sb.toString(), value.toString());
496 void parseDataAndPolicyNodes(Map<String,String> map){
497 for(String key:map.keySet()){
498 if(key.contains("policy.nodes.Root"))
502 else if(key.contains("policy.nodes")){
503 String wordToFind = "policy.nodes.";
504 int indexForPolicyNode=key.indexOf(wordToFind);
505 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
507 stringBetweenDots(subNodeString);
509 else if(key.contains("policy.data")){
510 String wordToFind="policy.data.";
511 int indexForPolicyNode=key.indexOf(wordToFind);
512 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
514 stringBetweenDotsForDataFields(subNodeString);
519 HashMap<String,String> parseDataNodes(Map<String,String> map){
520 HashMap<String,String> dataMapForJson=new HashMap <>();
521 for(String uniqueDataKey: uniqueDataKeys){
522 if(uniqueDataKey.contains("%")){
523 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
524 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
525 String typeValue=map.get(findType);
526 LOGGER.info(typeValue);
527 if(typeValue != null && typeValue.equalsIgnoreCase(STRING)||
528 typeValue.equalsIgnoreCase(INTEGER)
531 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
532 String defaultValue= map.get(findDefault);
533 LOGGER.info("defaultValue is:"+ defaultValue);
535 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
536 String requiredValue= map.get(findRequired);
537 LOGGER.info("requiredValue is:"+ requiredValue);
539 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
540 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
541 attributeIndividualStringBuilder.append(defaultValue+":required-");
542 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
543 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
545 else if(typeValue != null && typeValue.equalsIgnoreCase(LIST)){
546 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
547 String listValue=map.get(findList);
549 LOGGER.info("Type of list is:"+ listValue);
551 if(listValue.contains(".")){
552 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
553 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
554 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
555 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
558 StringBuilder stringListItems= new StringBuilder();
559 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
560 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
561 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
562 for(int i=0;i<10;i++){
563 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
564 String constraintsValue=map.get(findConstraints);
565 LOGGER.info(constraintsValue);
566 if(constraintsValue==null){
570 dataConstraints.add(constraintsValue);
571 dataListBuffer.append(constraintsValue+",");
574 dataListBuffer.append("]#");
576 LOGGER.info(dataListBuffer);
581 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
582 String userDefinedValue=map.get(findUserDefined);
583 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
584 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
585 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
586 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
591 return dataMapForJson;
594 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
595 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
596 HashMap<String,String> hmSub;
597 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
598 String uniqueDataKey= entry.getKey();
599 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
600 String value= dataMapForJson.get(uniqueDataKey);
601 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
602 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
603 hmSub.put(uniqueDataKeySplit[1], value);
606 hmSub=new HashMap <>();
607 hmSub.put(uniqueDataKeySplit[1], value);
610 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
613 JSONObject mainObject= new JSONObject();
615 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
616 String s=entry.getKey();
617 json= new JSONObject();
618 HashMap<String,String> jsonHm=dataMapKey.get(s);
619 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
620 String key=entryMap.getKey();
621 json.put(key, jsonHm.get(key));
623 mainObject.put(s,json);
625 Iterator<String> keysItr = mainObject.keys();
626 while(keysItr.hasNext()) {
627 String key = keysItr.next();
628 String value = mainObject.get(key).toString();
629 retmap.put(key, value);
632 LOGGER.info("#############################################################################");
633 LOGGER.info(mainObject);
634 LOGGER.info("###############################################################################");
638 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
639 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
640 for(String uniqueKey: uniqueKeys){
641 HashMap<String,String> hm;
643 for(Map.Entry<String,String> entry:map.entrySet()){
644 String key=entry.getKey();
645 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
646 if(mapKey.containsKey(uniqueKey)){
647 hm = mapKey.get(uniqueKey);
648 String keyStr= key.substring(key.lastIndexOf('.')+1);
649 String valueStr= map.get(key);
650 if(("type").equals(keyStr)){
651 if(!key.contains("entry_schema"))
653 hm.put(keyStr,valueStr);
656 hm.put(keyStr,valueStr);
660 hm = new HashMap <>();
661 String keyStr= key.substring(key.lastIndexOf('.')+1);
662 String valueStr= map.get(key);
663 if(("type").equals(keyStr)){
664 if(!key.contains("entry_schema"))
666 hm.put(keyStr,valueStr);
669 hm.put(keyStr,valueStr);
671 mapKey.put(uniqueKey, hm);
679 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
680 StringBuilder attributeStringBuilder= new StringBuilder();
681 StringBuilder referenceStringBuilder= new StringBuilder();
682 StringBuilder listBuffer= new StringBuilder();
683 List<String> constraints= new ArrayList<>();
684 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
685 String keySetString= entry.getKey();
686 HashMap<String,String> keyValues=mapKey.get(keySetString);
687 if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(STRING)||
688 keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(INTEGER)
690 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
691 attributeIndividualStringBuilder.append(keySetString+"=");
692 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
693 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
694 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
695 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
698 else if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(LIST)){
700 Set<String> keys= keyValues.keySet();
701 Iterator<String> itr=keys.iterator();
702 while(itr.hasNext()){
703 String key= itr.next();
704 if((!("type").equals(key) ||("required").equals(key)))
706 String value= keyValues.get(key);
707 //The "." in the value determines if its a string or a user defined type.
708 if (!value.contains(".")){
710 if(StringUtils.isNumeric(key) ){ //only integer key for the value of Constrains
711 constraints.add(keyValues.get(key));
714 //This is user defined string
715 String trimValue=value.substring(value.lastIndexOf('.')+1);
716 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
717 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
718 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
724 if(keyValues.get("type").equalsIgnoreCase(LIST)){
725 if(constraints == null || constraints.isEmpty()){
726 referenceStringBuilder.append(keySetString+"=MANY-true"+",");
730 //User defined Datatype.
731 String value=keyValues.get("type");
732 if(value != null && !value.isEmpty()){
733 String trimValue=value.substring(value.lastIndexOf('.')+1);
734 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
735 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
736 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
738 LOGGER.info("keyValues.get(type) is null/empty");
742 if(constraints!=null && ! constraints.isEmpty()){
744 listBuffer.append(keySetString.toUpperCase()+"=[");
745 for(String str:constraints){
746 listBuffer.append(str+",");
748 listBuffer.append("]#");
749 LOGGER.info(listBuffer);
752 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
753 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
754 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
759 dataListBuffer.append(listBuffer);
762 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
763 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
764 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
765 LOGGER.info("List String is:"+listBuffer);
766 LOGGER.info("Data list buffer is:"+dataListBuffer);
767 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
769 this.listConstraints=dataListBuffer.toString();
770 this.referenceAttributes=referenceStringBuilder.toString();
771 this.attributeString=attributeStringBuilder.toString();
776 public void parseTosca (String fileName){
777 Map<String,String> map= new HashMap<>();
782 parseDataAndPolicyNodes(map);
784 HashMap<String,String> dataMapForJson=parseDataNodes(map);
786 constructJsonForDataFields(dataMapForJson);
788 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
790 createAttributes(mapKey);
792 } catch (IOException e) {
798 private String cleanUPJson(String json) {
799 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
800 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
801 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
803 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
804 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
805 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
806 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
807 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
808 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
809 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
810 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
811 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
812 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
816 private JSONObject decodeContent(JsonNode jsonNode){
817 Iterator<JsonNode> jsonElements = jsonNode.elements();
818 Iterator<String> jsonKeys = jsonNode.fieldNames();
819 Map<String,String> element = new TreeMap<>();
820 while(jsonElements.hasNext() && jsonKeys.hasNext()){
821 element.put(jsonKeys.next(), jsonElements.next().toString());
823 JSONObject jsonResult = new JSONObject();
824 JSONArray jsonArray = null;
825 String oldValue = null;
826 String nodeKey = null;
827 String arryKey = null;
828 Boolean isArray = false;
829 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
830 ObjectNode node = nodeFactory.objectNode();
831 String prevKey = null;
832 String presKey = null;
833 for(String key: element.keySet()){
834 if(key.contains(".")){
835 presKey = key.substring(0,key.indexOf('.'));
836 }else if(key.contains("@")){
837 presKey = key.substring(0,key.indexOf('@'));
841 // first check if we are different from old.
842 LOGGER.info(key+"\n");
843 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
844 if(!oldValue.equals(key.substring(0,key.indexOf('@')))){
845 jsonResult.put(oldValue, jsonArray);
846 jsonArray = new JSONArray();
848 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
849 jsonResult.put(oldValue, jsonArray);
851 jsonArray = new JSONArray();
856 if(key.contains(".")){
858 nodeKey = key.substring(0,key.indexOf('.'));
860 if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
861 node.put(key.substring(key.indexOf('.')+1), element.get(key));
864 if(nodeKey.contains("@")){
866 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
868 if(nodeKey.endsWith("@0")){
870 jsonArray = new JSONArray();
872 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
873 jsonArray.put(decodeContent(node));
875 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){
876 jsonResult.put(arryKey, jsonArray);
877 jsonArray = new JSONArray();
879 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
882 jsonResult.put(nodeKey, decodeContent(node));
884 node = nodeFactory.objectNode();
886 nodeKey = key.substring(0,key.indexOf('.'));
887 if(nodeKey.contains("@")){
888 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
890 node.put(key.substring(key.indexOf('.')+1), element.get(key));
892 }else if(node.size()!=0){
893 if(nodeKey.contains("@")){
895 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
897 if(nodeKey.endsWith("@0")){
899 jsonArray = new JSONArray();
901 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
902 jsonArray.put(decodeContent(node));
904 jsonResult.put(arryKey, jsonArray);
905 jsonArray = new JSONArray();
906 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
909 jsonResult.put(nodeKey, decodeContent(node));
911 node = nodeFactory.objectNode();
912 if(key.contains("@")){
914 if(key.endsWith("@0")|| jsonArray==null){
915 jsonArray = new JSONArray();
917 }else if(!key.contains("@")){
922 oldValue = key.substring(0,key.indexOf('@'));
924 if(oldValue!=prevKey){
925 oldValue = key.substring(0,key.indexOf('@'));
927 if(oldValue.equals(key.substring(0,key.indexOf('@')))){
928 jsonArray.put(element.get(key));
930 jsonResult.put(oldValue, jsonArray);
931 jsonArray = new JSONArray();
933 oldValue = key.substring(0,key.indexOf('@'));
935 jsonResult.put(key, element.get(key));
938 if(key.contains("@")){
940 if(key.endsWith("@0")|| jsonArray==null){
941 jsonArray = new JSONArray();
943 }else if(!key.contains("@")){
948 oldValue = key.substring(0,key.indexOf('@'));
950 if(oldValue!=prevKey){
951 oldValue = key.substring(0,key.indexOf('@'));
953 if(oldValue.equals(key.substring(0,key.indexOf('@')))){
954 jsonArray.put(element.get(key));
956 jsonResult.put(oldValue, jsonArray);
957 jsonArray = new JSONArray();
959 oldValue = key.substring(0,key.indexOf('@'));
961 jsonResult.put(key, element.get(key));
966 if(nodeKey.contains("@")){
968 jsonArray = new JSONArray();
971 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
973 jsonArray.put(decodeContent(node));
974 jsonResult.put(arryKey, jsonArray);
977 jsonResult.put(nodeKey, decodeContent(node));
980 if(isArray && jsonArray.length() > 0){
981 jsonResult.put(oldValue, jsonArray);
986 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
987 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
988 ObjectMapper mapper = new ObjectMapper();
989 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
990 JsonNode root = mapper.readTree(request.getReader());
992 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
993 String servicename = value.split("-v")[0];
994 String version = null;
995 if (value.contains("-v")){
996 version = value.split("-v")[1];
998 MicroServiceModels returnModel = getAttributeObject(servicename, version);
1001 //Get all keys with "MANY-true" defined in their value from subAttribute
1002 Set<String> allkeys = null;
1003 if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
1004 JSONObject json = new JSONObject(returnModel.getSub_attributes());
1006 allkeys = allManyTrueKeys;
1007 allManyTrueKeys = new HashSet <>();
1008 LOGGER.info("allkeys : " + allkeys);
1011 String allManyTrueKeys = "";
1012 if(allkeys != null){
1013 allManyTrueKeys = allkeys.toString();
1016 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
1018 JSONObject jsonObject = new JSONObject(jsonModel);
1020 JSONObject finalJsonObject = null;
1021 if(allkeys != null){
1022 Iterator<String> iter = allkeys.iterator();
1023 while(iter.hasNext()){
1024 //Convert to array values for MANY-true keys
1025 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
1029 if(finalJsonObject != null){
1030 LOGGER.info(finalJsonObject.toString());
1031 jsonModel = finalJsonObject.toString();
1034 //get all properties with "MANY-true" defined in Ref_attributes
1035 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
1036 if(manyTrueProperties != null){
1037 JSONObject jsonObj = new JSONObject(jsonModel);
1038 for (String s : manyTrueProperties) {
1040 //convert to array element for MANY-true properties
1041 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
1044 if(finalJsonObject != null){
1045 LOGGER.info(finalJsonObject.toString());
1046 jsonModel = finalJsonObject.toString();
1050 response.setCharacterEncoding("UTF-8");
1051 response.setContentType("application / json");
1052 request.setCharacterEncoding("UTF-8");
1053 List<Object> list = new ArrayList<>();
1054 PrintWriter out = response.getWriter();
1055 String responseString = mapper.writeValueAsString(returnModel);
1056 JSONObject j = null;
1057 if("".equals(allManyTrueKeys)){
1058 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
1060 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+ "}");
1063 out.write(list.toString());
1067 @SuppressWarnings({ "unchecked", "rawtypes" })
1068 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
1069 Map<String, String> attributeMap = new HashMap<>();
1070 Map<String, String> refAttributeMap = new HashMap<>();
1071 String attribute = returnModel.getAttributes();
1072 if(attribute != null){
1073 attribute = attribute.trim();
1075 String refAttribute = returnModel.getRef_attributes();
1076 if(refAttribute != null){
1077 refAttribute = refAttribute.trim();
1079 String enumAttribute = returnModel.getEnumValues();
1080 if(enumAttribute != null){
1081 enumAttribute = enumAttribute.trim();
1083 if (!StringUtils.isEmpty(attribute)){
1084 attributeMap = convert(attribute, ",");
1086 if (!StringUtils.isEmpty(refAttribute)){
1087 refAttributeMap = convert(refAttribute, ",");
1090 Gson gson = new Gson();
1092 String subAttributes = returnModel.getSub_attributes();
1093 if(subAttributes != null){
1094 subAttributes = subAttributes.trim();
1098 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1100 JSONObject object = new JSONObject();
1103 for (Entry<String, String> keySet : attributeMap.entrySet()){
1104 array = new JSONArray();
1105 String value = keySet.getValue();
1106 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1108 object.put(keySet.getKey().trim(), array);
1110 object.put(keySet.getKey().trim(), value.trim());
1114 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1115 array = new JSONArray();
1116 String value = keySet.getValue().split(":")[0];
1117 if (gsonObject.containsKey(value)){
1118 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1119 array.put(recursiveReference(value, gsonObject, enumAttribute));
1120 object.put(keySet.getKey().trim(), array);
1122 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1125 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1126 array.put(value.trim());
1127 object.put(keySet.getKey().trim(), array);
1129 object.put(keySet.getKey().trim(), value.trim());
1136 return object.toString();
1139 @SuppressWarnings("unchecked")
1140 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1141 JSONObject object = new JSONObject();
1142 Map<String, String> map;
1143 Object returnClass = subAttributeMap.get(name);
1144 map = (Map<String, String>) returnClass;
1147 for( Entry<String, String> m:map.entrySet()){
1148 String[] splitValue = m.getValue().split(":");
1149 array = new JSONArray();
1150 if (subAttributeMap.containsKey(splitValue[0])){
1151 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1152 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1153 object.put(m.getKey().trim(), array);
1155 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1158 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1159 array.put(splitValue[0].trim());
1160 object.put(m.getKey().trim(), array);
1162 object.put(m.getKey().trim(), splitValue[0].trim());
1171 public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1172 return convertToArrayElement(json, new HashSet<>(), keyValue);
1175 private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1176 for (String key : json.keySet()) {
1177 Object obj = json.get(key);
1178 if(key.equals(keyValue.trim())){
1179 if(!(obj instanceof JSONArray)){
1180 JSONArray newJsonArray = new JSONArray();
1181 newJsonArray.put(obj);
1182 json.put(key, newJsonArray);
1184 LOGGER.info("key : " + key);
1185 LOGGER.info("obj : " + obj);
1186 LOGGER.info("json.get(key) : " + json.get(key));
1187 LOGGER.info("keyValue : " + keyValue);
1188 keys.addAll(json.keySet());
1193 if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);
1199 // call this method to get all MANY-true properties
1200 public static Set<String> getManyTrueProperties(String referAttributes){
1201 LOGGER.info("referAttributes : " + referAttributes);
1202 Set<String> manyTrueProperties = new HashSet<>();
1204 if(referAttributes != null){
1205 String[] referAarray = referAttributes.split(",");
1206 String []element= null;
1207 for(int i=0; i<referAarray.length; i++){
1208 element = referAarray[i].split("=");
1209 if(element.length > 1 && element[1].contains("MANY-true")){
1210 manyTrueProperties.add(element[0]);
1215 return manyTrueProperties;
1218 //call this method to start the recursive
1219 private Set<String> getAllKeys(JSONObject json) {
1220 return getAllKeys(json, new HashSet<>());
1223 private Set<String> getAllKeys(JSONArray arr) {
1224 return getAllKeys(arr, new HashSet<>());
1227 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1228 for (int i = 0; i < arr.length(); i++) {
1229 Object obj = arr.get(i);
1230 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
1231 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
1236 // this method returns a set of keys with "MANY-true" defined in their value.
1237 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1238 for (String key : json.keySet()) {
1239 Object obj = json.get(key);
1240 if(obj instanceof String && ((String) obj).contains("MANY-true")){
1241 LOGGER.info("key : " + key);
1242 LOGGER.info("obj : " + obj);
1243 allManyTrueKeys.add(key);
1245 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
1246 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
1253 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1254 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1255 ObjectMapper mapper = new ObjectMapper();
1256 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1257 JsonNode root = mapper.readTree(request.getReader());
1259 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1260 String servicename = value.split("-v")[0];
1261 Set<String> returnList = getVersionList(servicename);
1263 response.setCharacterEncoding("UTF-8");
1264 response.setContentType("application / json");
1265 request.setCharacterEncoding("UTF-8");
1266 List<Object> list = new ArrayList<>();
1267 PrintWriter out = response.getWriter();
1268 String responseString = mapper.writeValueAsString(returnList);
1269 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1271 out.write(list.toString());
1275 private Set<String> getVersionList(String name) {
1276 MicroServiceModels workingModel;
1277 Set<String> list = new HashSet<>();
1278 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1279 for (int i = 0; i < microServiceModelsData.size(); i++) {
1280 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1281 if (workingModel.getVersion()!=null){
1282 list.add(workingModel.getVersion());
1284 list.add("Default");
1290 private MicroServiceModels getAttributeObject(String name, String version) {
1291 MicroServiceModels workingModel = new MicroServiceModels();
1292 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1293 for (int i = 0; i < microServiceModelsData.size(); i++) {
1294 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1295 if(version != null){
1296 if (workingModel.getVersion()!=null){
1297 if (workingModel.getVersion().equals(version)){
1298 return workingModel;
1301 return workingModel;
1304 return workingModel;
1308 return workingModel;
1311 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1312 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1314 Map<String, Object> model = new HashMap<>();
1315 ObjectMapper mapper = new ObjectMapper();
1316 List<String> priorityList = new ArrayList<>();
1318 for (int i = 1; i < priorityCount; i++) {
1319 priorityList.add(String.valueOf(i));
1321 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1322 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1323 JSONObject j = new JSONObject(msg);
1324 response.getWriter().write(j.toString());
1326 catch (Exception e){
1331 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1332 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1333 Object policyData = policyAdapter.getPolicyData();
1334 PolicyType policy = (PolicyType) policyData;
1335 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1336 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1337 policyAdapter.setPolicyName(policyNameValue);
1338 String description = "";
1340 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1341 }catch(Exception e){
1342 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1343 description = policy.getDescription();
1345 policyAdapter.setPolicyDescription(description);
1346 // Get the target data under policy.
1347 TargetType target = policy.getTarget();
1348 if (target != null) {
1349 // Under target we have AnyOFType
1350 List<AnyOfType> anyOfList = target.getAnyOf();
1351 if (anyOfList != null) {
1352 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1353 while (iterAnyOf.hasNext()) {
1354 AnyOfType anyOf = iterAnyOf.next();
1355 // Under AnyOFType we have AllOFType
1356 List<AllOfType> allOfList = anyOf.getAllOf();
1357 if (allOfList != null) {
1358 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1359 while (iterAllOf.hasNext()) {
1360 AllOfType allOf = iterAllOf.next();
1361 // Under AllOFType we have Match
1362 List<MatchType> matchList = allOf.getMatch();
1363 if (matchList != null) {
1364 Iterator<MatchType> iterMatch = matchList.iterator();
1365 while (matchList.size()>1 && iterMatch.hasNext()) {
1366 MatchType match = iterMatch.next();
1368 // Under the match we have attribute value and
1369 // attributeDesignator. So,finally down to the actual attribute.
1371 AttributeValueType attributeValue = match.getAttributeValue();
1372 String value = (String) attributeValue.getContent().get(0);
1373 AttributeDesignatorType designator = match.getAttributeDesignator();
1374 String attributeId = designator.getAttributeId();
1375 // First match in the target is OnapName, so set that value.
1376 if (attributeId.equals("ONAPName")) {
1377 policyAdapter.setOnapName(value);
1379 if (attributeId.equals("ConfigName")){
1380 policyAdapter.setConfigName(value);
1382 if (attributeId.equals("uuid")){
1383 policyAdapter.setUuid(value);
1385 if (attributeId.equals("location")){
1386 policyAdapter.setLocation(value);
1388 if (attributeId.equals("RiskType")){
1389 policyAdapter.setRiskType(value);
1391 if (attributeId.equals("RiskLevel")){
1392 policyAdapter.setRiskLevel(value);
1394 if (attributeId.equals("guard")){
1395 policyAdapter.setGuard(value);
1397 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1398 PolicyController controller = new PolicyController();
1399 String newDate = controller.convertDate(value);
1400 policyAdapter.setTtlDate(newDate);
1403 readFile(policyAdapter, entity);
1413 public static Map<String, String> convert(String str, String split) {
1414 Map<String, String> map = new HashMap<>();
1415 for(final String entry : str.split(split)) {
1416 String[] parts = entry.split("=");
1417 map.put(parts[0], parts[1]);
1423 @SuppressWarnings("unchecked")
1424 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1425 String policyScopeName = null;
1426 ObjectMapper mapper = new ObjectMapper();
1428 DCAEMicroServiceObject msBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1429 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1430 policyAdapter.setPolicyScope(policyScopeName);
1432 policyAdapter.setPriority(msBody.getPriority());
1434 if (msBody.getVersion()!= null){
1435 policyAdapter.setServiceType(msBody.getService());
1436 policyAdapter.setVersion(msBody.getVersion());
1438 policyAdapter.setServiceType(msBody.getService());
1440 if(msBody.getContent() != null){
1441 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1442 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1443 readRecursivlyJSONContent(map, data);
1444 policyAdapter.setRuleData(data);
1447 } catch (Exception e) {
1453 @SuppressWarnings({ "rawtypes", "unchecked" })
1454 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1455 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1456 Object key = iterator.next();
1457 Object value = map.get(key);
1458 if(value instanceof LinkedHashMap<?, ?>){
1459 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1460 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1461 for(String objKey: secondObjec.keySet()){
1462 data.put(key+"." +objKey, secondObjec.get(objKey));
1464 }else if(value instanceof ArrayList){
1465 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1466 for(int i = 0; i < jsonArrayVal.size(); i++){
1467 Object arrayvalue = jsonArrayVal.get(i);
1468 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1469 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1470 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1471 for(String objKey: newData.keySet()){
1472 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1474 }else if(arrayvalue instanceof ArrayList){
1475 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1476 for(int j = 0; j < jsonArrayVal1.size(); j++){
1477 Object arrayvalue1 = jsonArrayVal1.get(i);
1478 data.put(key+"@"+j, arrayvalue1.toString());
1481 data.put(key+"@"+i, arrayvalue.toString());
1485 data.put(key.toString(), value.toString());
1490 private String getPolicyScope(String value) {
1491 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1492 if(groupList != null && !groupList.isEmpty()){
1493 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1494 return pScope.getGroupName();
1499 //Convert the map values and set into JSON body
1500 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1501 Map<String, String> attribute = new HashMap<>();
1502 StringBuilder temp = null;
1505 for (Entry<String, String> entry : attributesMap.entrySet()) {
1506 key = entry.getKey();
1507 value = entry.getValue();
1508 attribute.put(key, value);
1510 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1511 key = entryRef.getKey();
1512 value = entryRef.getValue();
1513 attribute.put(key, value);
1515 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1516 key = entryList.getKey();
1517 value = entryList.getValue();
1518 attribute.put(key, value);
1520 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1521 key = arrayList.getKey();
1523 for (Object textList : arrayList.getValue()){
1525 temp = new StringBuilder();
1526 temp.append("[" + textList);
1528 temp.append("," + textList);
1531 attribute.put(key, temp+ "]");
1537 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1538 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1539 modelList = new ArrayList<>();
1540 dirDependencyList = new ArrayList<>();
1541 classMap = new HashMap<>();
1542 retmap = new HashMap<>();
1543 uniqueKeys= new HashSet<>();
1544 uniqueDataKeys= new HashSet<>();
1545 dataListBuffer=new StringBuilder();
1546 dataConstraints= new ArrayList <>();
1547 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1548 boolean zip = false;
1550 String errorMsg = "";
1551 for (FileItem item : items) {
1552 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1553 this.newModel = new MicroServiceModels();
1555 File file = new File(item.getName());
1556 OutputStream outputStream = new FileOutputStream(file);
1557 IOUtils.copy(item.getInputStream(), outputStream);
1558 outputStream.close();
1559 this.newFile = file.toString();
1560 this.newModel.setModelName(this.newFile.split("-v")[0]);
1562 if (this.newFile.contains("-v")){
1563 if (item.getName().endsWith(".zip")){
1564 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1566 }else if(item.getName().endsWith(".yml")){
1567 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1571 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1574 }catch(Exception e){
1575 LOGGER.error("Upload error : ", e);
1576 errorMsg = "Upload error:" + e.getMessage();
1582 if(!errorMsg.isEmpty()){
1584 PrintWriter out = response.getWriter();
1586 response.setCharacterEncoding("UTF-8");
1587 response.setContentType("application / json");
1588 request.setCharacterEncoding("UTF-8");
1590 JSONObject j = new JSONObject();
1591 j.put("errorMsg", errorMsg);
1592 out.write(j.toString());
1596 List<File> fileList = new ArrayList<>();
1597 this.directory = "model";
1599 extractFolder(this.newFile);
1600 fileList = listModelFiles(this.directory);
1602 parseTosca(this.newFile);
1604 File file = new File(this.newFile);
1607 String modelType= "";
1610 //Process Main Model file first
1611 classMap = new HashMap<>();
1612 for (File file : fileList) {
1613 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1614 retreiveDependency(file.toString(), true);
1618 modelList = createList();
1620 cleanUp(this.newFile);
1624 modelList.add(this.newModel.getModelName());
1625 String className=this.newModel.getModelName();
1626 MSAttributeObject msAttributes= new MSAttributeObject();
1627 msAttributes.setClassName(className);
1629 HashMap<String, String> returnAttributeList =new HashMap<>();
1630 returnAttributeList.put(className, this.attributeString);
1631 msAttributes.setAttribute(returnAttributeList);
1633 msAttributes.setSubClass(this.retmap);
1635 HashMap<String, String> returnReferenceList =new HashMap<>();
1636 returnReferenceList.put(className, this.referenceAttributes);
1637 msAttributes.setRefAttribute(returnReferenceList);
1639 if(this.listConstraints!=""){
1640 HashMap<String, String> enumList =new HashMap<>();
1641 String[] listArray=this.listConstraints.split("#");
1642 for(String str:listArray){
1643 String[] strArr= str.split("=");
1644 if(strArr.length>1){
1645 enumList.put(strArr[0], strArr[1]);
1648 msAttributes.setEnumType(enumList);
1651 classMap=new HashMap<>();
1652 classMap.put(className, msAttributes);
1656 PrintWriter out = response.getWriter();
1658 response.setCharacterEncoding("UTF-8");
1659 response.setContentType("application / json");
1660 request.setCharacterEncoding("UTF-8");
1662 ObjectMapper mapper = new ObjectMapper();
1663 JSONObject j = new JSONObject();
1664 j.put("classListDatas", modelList);
1665 j.put("modelDatas", mapper.writeValueAsString(classMap));
1666 j.put("modelType", modelType);
1667 out.write(j.toString());
1671 * Unzip file and store in the model directory for processing
1673 @SuppressWarnings("rawtypes")
1674 private void extractFolder(String zipFile ) {
1676 File file = new File(zipFile);
1680 zip = new ZipFile(file);
1681 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1682 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1683 checkZipDirectory(this.directory);
1684 new File(newPath).mkdir();
1685 Enumeration zipFileEntries = zip.entries();
1687 // Process each entry
1688 while (zipFileEntries.hasMoreElements()){
1689 // grab a zip file entry
1690 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1691 String currentEntry = entry.getName();
1692 File destFile = new File("model" + File.separator + currentEntry);
1693 File destinationParent = destFile.getParentFile();
1695 destinationParent.mkdirs();
1697 if (!entry.isDirectory()){
1698 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1700 byte data[] = new byte[BUFFER];
1701 FileOutputStream fos = new FileOutputStream(destFile);
1702 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1703 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1704 dest.write(data, 0, currentByte);
1711 if (currentEntry.endsWith(".zip")){
1712 extractFolder(destFile.getAbsolutePath());
1715 } catch (IOException e) {
1716 LOGGER.error("Failed to unzip model file " + zipFile, e);
1721 } catch (IOException e) {
1722 LOGGER.error("Exception Occured While closing zipfile " + e);
1727 private void retreiveDependency(String workingFile, Boolean modelClass) {
1729 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1730 HashMap<String, MSAttributeObject> tempMap;
1732 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1734 classMap.putAll(tempMap);
1735 LOGGER.info(tempMap);
1741 private List<File> listModelFiles(String directoryName) {
1742 File directory = new File(directoryName);
1743 List<File> resultList = new ArrayList<>();
1744 File[] fList = directory.listFiles();
1745 for (File file : fList) {
1746 if (file.isFile()) {
1747 resultList.add(file);
1748 } else if (file.isDirectory()) {
1749 dirDependencyList.add(file.getName());
1750 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1756 private void cleanUp(String path) {
1759 FileUtils.forceDelete(new File(path));
1760 } catch (IOException e) {
1761 LOGGER.error("Failed to delete folder " + path, e);
1766 private void checkZipDirectory(String zipDirectory) {
1767 Path path = Paths.get(zipDirectory);
1769 if (Files.exists(path)) {
1770 cleanUp(zipDirectory);
1774 private List<String> createList() {
1775 List<String> list = new ArrayList<>();
1776 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1777 if (cMap.getValue().isPolicyTempalate()){
1778 list.add(cMap.getKey());
1783 if (list.isEmpty()){
1784 if (classMap.containsKey(this.newModel.getModelName())){
1785 list.add(this.newModel.getModelName());
1793 public Map<String, String> getAttributesListRefMap() {
1794 return attributesListRefMap;
1797 public Map<String, LinkedList<String>> getArrayTextList() {
1798 return arrayTextList;
1803 class DCAEMicroServiceObject {
1805 private String service;
1806 private String location;
1807 private String uuid;
1808 private String policyName;
1809 private String description;
1810 private String configName;
1811 private String templateVersion;
1812 private String version;
1813 private String priority;
1814 private String policyScope;
1815 private String riskType;
1816 private String riskLevel;
1817 private String guard = null;
1819 public String getGuard() {
1822 public void setGuard(String guard) {
1825 public String getRiskType() {
1828 public void setRiskType(String riskType) {
1829 this.riskType = riskType;
1831 public String getRiskLevel() {
1834 public void setRiskLevel(String riskLevel) {
1835 this.riskLevel = riskLevel;
1837 public String getPolicyScope() {
1840 public void setPolicyScope(String policyScope) {
1841 this.policyScope = policyScope;
1844 public String getPriority() {
1847 public void setPriority(String priority) {
1848 this.priority = priority;
1850 public String getVersion() {
1853 public void setVersion(String version) {
1854 this.version = version;
1856 private Object content;
1859 public String getPolicyName() {
1862 public void setPolicyName(String policyName) {
1863 this.policyName = policyName;
1865 public String getDescription() {
1868 public void setDescription(String description) {
1869 this.description = description;
1871 public String getConfigName() {
1874 public void setConfigName(String configName) {
1875 this.configName = configName;
1877 public Object getContent() {
1880 public void setContent(Object content) {
1881 this.content = content;
1884 public String getService() {
1887 public void setService(String service) {
1888 this.service = service;
1890 public String getLocation() {
1893 public void setLocation(String location) {
1894 this.location = location;
1897 public String getUuid() {
1900 public void setUuid(String uuid) {
1903 public String getTemplateVersion() {
1904 return templateVersion;
1906 public void setTemplateVersion(String templateVersion) {
1907 this.templateVersion = templateVersion;