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(){
165 protected PolicyRestAdapter policyAdapter = null;
166 private int priorityCount;
167 private Map<String, String> attributesListRefMap = new HashMap<>();
168 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
170 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
172 String jsonContent = null;
174 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
176 String tempJson = root.get("policyJSON").toString();
178 //---replace empty value with the value below before calling decodeContent method.
179 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
180 LOGGER.info("dummyValue:" + dummyValue);
181 tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
182 ObjectMapper mapper = new ObjectMapper();
183 JsonNode tempJsonNode = mapper.readTree(tempJson);
184 jsonContent = decodeContent(tempJsonNode).toString();
185 constructJson(policyData, jsonContent, dummyValue);
187 LOGGER.error("Error while decoding microservice content", e);
193 private GroupPolicyScopeList getPolicyObject(String policyScope) {
194 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
197 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
198 ObjectWriter om = new ObjectMapper().writer();
200 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
201 MicroServiceModels returnModel = new MicroServiceModels();
202 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
203 if(policyAdapter.getServiceType() !=null){
204 microServiceObject.setService(policyAdapter.getServiceType());
205 microServiceObject.setVersion(policyAdapter.getVersion());
206 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
208 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
209 if(policyAdapter.getUuid()!=null){
210 microServiceObject.setUuid(policyAdapter.getUuid());
212 if(policyAdapter.getLocation()!=null){
213 microServiceObject.setLocation(policyAdapter.getLocation());
215 if(policyAdapter.getConfigName()!=null){
216 microServiceObject.setConfigName(policyAdapter.getConfigName());
218 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
219 if(policyScopeValue!=null){
220 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
224 if(policyAdapter.getPolicyName()!=null){
225 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
227 if(policyAdapter.getPolicyDescription()!=null){
228 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
230 if (policyAdapter.getPriority()!=null){
231 microServiceObject.setPriority(policyAdapter.getPriority());
233 microServiceObject.setPriority("9999");
236 if (policyAdapter.getRiskLevel()!=null){
237 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
239 if (policyAdapter.getRiskType()!=null){
240 microServiceObject.setRiskType(policyAdapter.getRiskType());
242 if (policyAdapter.getGuard()!=null){
243 microServiceObject.setGuard(policyAdapter.getGuard());
245 microServiceObject.setContent(jsonContent);
248 json = om.writeValueAsString(microServiceObject);
249 } catch (JsonProcessingException e) {
250 LOGGER.error("Error writing out the object", e);
252 LOGGER.info("input json: " + json);
253 LOGGER.info("input jsonContent: " + jsonContent);
254 String cleanJson = cleanUPJson(json);
255 //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
256 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
257 LOGGER.info("tempJson: " + tempJson);
258 cleanJson = removeNullAttributes(tempJson);
259 policyAdapter.setJsonBody(cleanJson);
260 return policyAdapter;
263 private String removeNullAttributes(String cleanJson) {
264 ObjectMapper mapper = new ObjectMapper();
267 JsonNode rootNode = mapper.readTree(cleanJson);
268 JsonNode returnNode = mapper.readTree(cleanJson);
269 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
270 boolean remove = false;
271 JsonObject removed = null;
272 boolean contentChanged = false;
273 while (fieldsIterator.hasNext()) {
274 Map.Entry<String, JsonNode> field = fieldsIterator.next();
275 final String key = field.getKey();
276 final JsonNode value = field.getValue();
277 if("content".equalsIgnoreCase(key)){
278 String contentStr = value.toString();
279 try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
280 JsonObject jsonContent = reader.readObject();
281 removed = removeNull(jsonContent);
282 if(!jsonContent.toString().equals(removed.toString())){
283 contentChanged = true;
287 if (value==null || value.isNull()){
288 ((ObjectNode) returnNode).remove(key);
293 cleanJson = returnNode.toString();
295 if (value==null || value.isNull()){
296 ((ObjectNode) returnNode).remove(key);
301 cleanJson = returnNode.toString();
305 //set modified content to cleanJson
306 JSONObject jObject = new JSONObject(cleanJson);
307 jObject.put("content",removed.toString());
308 cleanJson = cleanUPJson(jObject.toString());
311 } catch (IOException e) {
312 LOGGER.error("Error writing out the JsonNode",e);
317 public static JsonArray removeNull(JsonArray array) {
318 JsonArrayBuilder builder = Json.createArrayBuilder();
320 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
321 JsonValue value = it.next();
322 switch (value.getValueType()) {
324 JsonArray a = removeNull(array.getJsonArray(i));
329 JsonObject object = removeNull(array.getJsonObject(i));
330 if (!object.isEmpty())
334 String s = array.getString(i);
335 if (s != null && !s.isEmpty())
339 builder.add(array.getJsonNumber(i));
343 builder.add(array.getBoolean(i));
349 return builder.build();
352 public static JsonObject removeNull(JsonObject obj) {
353 JsonObjectBuilder builder = Json.createObjectBuilder();
354 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
355 Entry<String, JsonValue> e = it.next();
356 String key = e.getKey();
357 JsonValue value = e.getValue();
358 switch (value.getValueType()) {
360 JsonArray array = removeNull(obj.getJsonArray(key));
361 if (!array.isEmpty())
362 builder.add(key, array);
365 JsonObject object = removeNull(obj.getJsonObject(key));
366 if (!object.isEmpty())
367 builder.add(key, object);
370 String s = obj.getString(key);
371 if (s != null && !s.isEmpty())
375 builder.add(key, obj.getJsonNumber(key));
379 builder.add(key, obj.getBoolean(key));
385 return builder.build();
388 // Second index of dot should be returned.
389 public int stringBetweenDots(String str){
390 String stringToSearch=str;
391 String[]ss=stringToSearch.split("\\.");
395 uniqueKeys.add(ss[2]);
399 return uniqueKeys.size();
402 public void stringBetweenDotsForDataFields(String str){
403 String stringToSearch=str;
404 String[]ss=stringToSearch.split("\\.");
409 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
415 @SuppressWarnings("unchecked")
416 public Map<String, String> load(String fileName) throws IOException {
417 File newConfiguration = new File(fileName);
418 Yaml yaml = new Yaml();
419 Map<Object, Object> yamlMap = null;
420 try(InputStream is = new FileInputStream(newConfiguration)){
421 yamlMap = (Map<Object, Object>) yaml.load(is);
422 } catch (FileNotFoundException e) {
426 StringBuilder sb = new StringBuilder();
427 Map<String, String> settings = new HashMap<>();
428 if (yamlMap == null) {
431 List<String> path = new ArrayList <>();
432 serializeMap(settings, sb, path, yamlMap);
436 public Map<String, String> load(byte[] source) {
437 Yaml yaml = new Yaml();
438 @SuppressWarnings("unchecked")
439 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
440 StringBuilder sb = new StringBuilder();
441 Map<String, String> settings = new HashMap <>();
442 if (yamlMap == null) {
445 List<String> path = new ArrayList <>();
446 serializeMap(settings, sb, path, yamlMap);
450 @SuppressWarnings({ "unchecked", "rawtypes" })
451 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
452 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
453 if (entry.getValue() instanceof Map) {
454 path.add((String) entry.getKey());
455 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
456 path.remove(path.size() - 1);
457 } else if (entry.getValue() instanceof List) {
458 path.add((String) entry.getKey());
459 serializeList(settings, sb, path, (List) entry.getValue());
460 path.remove(path.size() - 1);
462 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
467 @SuppressWarnings("unchecked")
468 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
470 for (Object listEle : yamlList) {
471 if (listEle instanceof Map) {
472 path.add(Integer.toString(counter));
473 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
474 path.remove(path.size() - 1);
475 } else if (listEle instanceof List) {
476 path.add(Integer.toString(counter));
477 serializeList(settings, sb, path, (List<String>) listEle);
478 path.remove(path.size() - 1);
480 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
486 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
491 for (String pathEle : path) {
492 sb.append(pathEle).append('.');
495 settings.put(sb.toString(), value.toString());
498 void parseDataAndPolicyNodes(Map<String,String> map){
499 for(String key:map.keySet()){
500 if(key.contains("policy.nodes.Root"))
504 else if(key.contains("policy.nodes")){
505 String wordToFind = "policy.nodes.";
506 int indexForPolicyNode=key.indexOf(wordToFind);
507 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
509 stringBetweenDots(subNodeString);
511 else if(key.contains("policy.data")){
512 String wordToFind="policy.data.";
513 int indexForPolicyNode=key.indexOf(wordToFind);
514 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
516 stringBetweenDotsForDataFields(subNodeString);
521 HashMap<String,String> parseDataNodes(Map<String,String> map){
522 HashMap<String,String> dataMapForJson=new HashMap <>();
523 for(String uniqueDataKey: uniqueDataKeys){
524 if(uniqueDataKey.contains("%")){
525 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
526 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
527 String typeValue=map.get(findType);
528 LOGGER.info(typeValue);
529 if(typeValue != null && typeValue.equalsIgnoreCase(STRING)||
530 typeValue.equalsIgnoreCase(INTEGER)
533 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
534 String defaultValue= map.get(findDefault);
535 LOGGER.info("defaultValue is:"+ defaultValue);
537 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
538 String requiredValue= map.get(findRequired);
539 LOGGER.info("requiredValue is:"+ requiredValue);
541 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
542 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
543 attributeIndividualStringBuilder.append(defaultValue+":required-");
544 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
545 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
547 else if(typeValue != null && typeValue.equalsIgnoreCase(LIST)){
548 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
549 String listValue=map.get(findList);
551 LOGGER.info("Type of list is:"+ listValue);
553 if(listValue.contains(".")){
554 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
555 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
556 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
557 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
560 StringBuilder stringListItems= new StringBuilder();
561 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
562 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
563 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
564 for(int i=0;i<10;i++){
565 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
566 String constraintsValue=map.get(findConstraints);
567 LOGGER.info(constraintsValue);
568 if(constraintsValue==null){
572 dataConstraints.add(constraintsValue);
573 dataListBuffer.append(constraintsValue+",");
576 dataListBuffer.append("]#");
578 LOGGER.info(dataListBuffer);
583 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
584 String userDefinedValue=map.get(findUserDefined);
585 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
586 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
587 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
588 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
593 return dataMapForJson;
596 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
597 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
598 HashMap<String,String> hmSub;
599 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
600 String uniqueDataKey= entry.getKey();
601 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
602 String value= dataMapForJson.get(uniqueDataKey);
603 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
604 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
605 hmSub.put(uniqueDataKeySplit[1], value);
608 hmSub=new HashMap <>();
609 hmSub.put(uniqueDataKeySplit[1], value);
612 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
615 JSONObject mainObject= new JSONObject();
617 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
618 String s=entry.getKey();
619 json= new JSONObject();
620 HashMap<String,String> jsonHm=dataMapKey.get(s);
621 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
622 String key=entryMap.getKey();
623 json.put(key, jsonHm.get(key));
625 mainObject.put(s,json);
627 Iterator<String> keysItr = mainObject.keys();
628 while(keysItr.hasNext()) {
629 String key = keysItr.next();
630 String value = mainObject.get(key).toString();
631 retmap.put(key, value);
634 LOGGER.info("#############################################################################");
635 LOGGER.info(mainObject);
636 LOGGER.info("###############################################################################");
640 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
641 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
642 for(String uniqueKey: uniqueKeys){
643 HashMap<String,String> hm;
645 for(Map.Entry<String,String> entry:map.entrySet()){
646 String key=entry.getKey();
647 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
648 if(mapKey.containsKey(uniqueKey)){
649 hm = mapKey.get(uniqueKey);
650 String keyStr= key.substring(key.lastIndexOf('.')+1);
651 String valueStr= map.get(key);
652 if(("type").equals(keyStr)){
653 if(!key.contains("entry_schema"))
655 hm.put(keyStr,valueStr);
658 hm.put(keyStr,valueStr);
662 hm = new HashMap <>();
663 String keyStr= key.substring(key.lastIndexOf('.')+1);
664 String valueStr= map.get(key);
665 if(("type").equals(keyStr)){
666 if(!key.contains("entry_schema"))
668 hm.put(keyStr,valueStr);
671 hm.put(keyStr,valueStr);
673 mapKey.put(uniqueKey, hm);
681 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
682 StringBuilder attributeStringBuilder= new StringBuilder();
683 StringBuilder referenceStringBuilder= new StringBuilder();
684 StringBuilder listBuffer= new StringBuilder();
685 List<String> constraints= new ArrayList<>();
686 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
687 String keySetString= entry.getKey();
688 HashMap<String,String> keyValues=mapKey.get(keySetString);
689 if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(STRING)||
690 keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(INTEGER)
692 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
693 attributeIndividualStringBuilder.append(keySetString+"=");
694 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
695 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
696 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
697 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
700 else if(keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(LIST)){
702 Set<String> keys= keyValues.keySet();
703 Iterator<String> itr=keys.iterator();
704 boolean isDefinedType = false;
705 while(itr.hasNext()){
706 String key= itr.next();
707 if(!("type").equals(key) ||("required").equals(key))
709 String value= keyValues.get(key);
710 //The "." in the value determines if its a string or a user defined type.
711 if (!value.contains(".")){
713 if(StringUtils.isNumeric(key) ){ //only integer key for the value of Constrains
714 constraints.add(keyValues.get(key));
717 //This is user defined type
718 String trimValue=value.substring(value.lastIndexOf('.')+1);
719 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
720 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
721 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
722 isDefinedType = true;
728 if(!isDefinedType && keyValues.get("type").equalsIgnoreCase(LIST) &&
729 (constraints == null || constraints.isEmpty()) ) { //type is list but no constraints defined.
730 referenceStringBuilder.append(keySetString+"=MANY-true"+",");
733 //User defined Datatype.
734 String value=keyValues.get("type");
735 if(value != null && !value.isEmpty()){
736 String trimValue=value.substring(value.lastIndexOf('.')+1);
737 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
738 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
739 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
741 LOGGER.info("keyValues.get(type) is null/empty");
745 if(constraints!=null && ! constraints.isEmpty()){
747 listBuffer.append(keySetString.toUpperCase()+"=[");
748 for(String str:constraints){
749 listBuffer.append(str+",");
751 listBuffer.append("]#");
752 LOGGER.info(listBuffer);
755 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
756 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
757 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
762 dataListBuffer.append(listBuffer);
765 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
766 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
767 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
768 LOGGER.info("List String is:"+listBuffer);
769 LOGGER.info("Data list buffer is:"+dataListBuffer);
770 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
772 this.listConstraints=dataListBuffer.toString();
773 this.referenceAttributes=referenceStringBuilder.toString();
774 this.attributeString=attributeStringBuilder.toString();
779 public void parseTosca (String fileName){
780 Map<String,String> map= new HashMap<>();
785 parseDataAndPolicyNodes(map);
787 HashMap<String,String> dataMapForJson=parseDataNodes(map);
789 constructJsonForDataFields(dataMapForJson);
791 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
793 createAttributes(mapKey);
795 } catch (IOException e) {
801 private String cleanUPJson(String json) {
802 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
803 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
804 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
806 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
807 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
808 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
809 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
810 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
811 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
812 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
813 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
814 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
815 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
819 private JSONObject decodeContent(JsonNode jsonNode){
820 Iterator<JsonNode> jsonElements = jsonNode.elements();
821 Iterator<String> jsonKeys = jsonNode.fieldNames();
822 Map<String,String> element = new TreeMap<>();
823 while(jsonElements.hasNext() && jsonKeys.hasNext()){
824 element.put(jsonKeys.next(), jsonElements.next().toString());
826 JSONObject jsonResult = new JSONObject();
827 JSONArray jsonArray = null;
828 String oldValue = null;
829 String nodeKey = null;
830 String arryKey = null;
831 Boolean isArray = false;
832 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
833 ObjectNode node = nodeFactory.objectNode();
834 String prevKey = null;
836 for(Entry<String, String> entry: element.entrySet()){
837 String key = entry.getKey();
838 String value = entry.getValue();
839 if(key.contains(".")){
840 presKey = key.substring(0,key.indexOf('.'));
841 }else if(key.contains("@")){
842 presKey = key.substring(0,key.indexOf('@'));
846 // first check if we are different from old.
847 LOGGER.info(key+"\n");
848 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
849 if(!oldValue.equals(key.substring(0,key.indexOf('@')))){
850 jsonResult.put(oldValue, jsonArray);
851 jsonArray = new JSONArray();
853 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
854 jsonResult.put(oldValue, jsonArray);
856 jsonArray = new JSONArray();
861 if(key.contains(".")){
863 nodeKey = key.substring(0,key.indexOf('.'));
865 if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
866 node.put(key.substring(key.indexOf('.')+1), value);
869 if(nodeKey.contains("@")){
871 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
873 if(nodeKey.endsWith("@0")){
875 jsonArray = new JSONArray();
877 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
878 jsonArray.put(decodeContent(node));
880 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){
881 jsonResult.put(arryKey, jsonArray);
882 jsonArray = new JSONArray();
884 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
887 jsonResult.put(nodeKey, decodeContent(node));
889 node = nodeFactory.objectNode();
891 nodeKey = key.substring(0,key.indexOf('.'));
892 if(nodeKey.contains("@")){
893 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
895 node.put(key.substring(key.indexOf('.')+1), value);
899 if(nodeKey.contains("@")){
901 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
903 if(nodeKey.endsWith("@0")){
905 jsonArray = new JSONArray();
907 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
908 jsonArray.put(decodeContent(node));
910 jsonResult.put(arryKey, jsonArray);
911 jsonArray = new JSONArray();
912 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
915 jsonResult.put(nodeKey, decodeContent(node));
917 node = nodeFactory.objectNode();
919 if(key.contains("@")){
921 if(key.endsWith("@0")|| jsonArray==null){
922 jsonArray = new JSONArray();
924 }else if(!key.contains("@")){
929 oldValue = key.substring(0,key.indexOf('@'));
931 if(oldValue!=prevKey){
932 oldValue = key.substring(0,key.indexOf('@'));
934 if(oldValue.equals(key.substring(0,key.indexOf('@')))){
935 jsonArray.put(value);
937 jsonResult.put(oldValue, jsonArray);
938 jsonArray = new JSONArray();
940 oldValue = key.substring(0,key.indexOf('@'));
942 jsonResult.put(key, value);
947 if(nodeKey.contains("@")){
949 jsonArray = new JSONArray();
952 arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
954 jsonArray.put(decodeContent(node));
955 jsonResult.put(arryKey, jsonArray);
958 jsonResult.put(nodeKey, decodeContent(node));
961 if(isArray && jsonArray.length() > 0){
962 jsonResult.put(oldValue, jsonArray);
967 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
968 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
969 ObjectMapper mapper = new ObjectMapper();
970 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
971 JsonNode root = mapper.readTree(request.getReader());
973 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
974 String servicename = value.split("-v")[0];
975 String version = null;
976 if (value.contains("-v")){
977 version = value.split("-v")[1];
979 MicroServiceModels returnModel = getAttributeObject(servicename, version);
982 //Get all keys with "MANY-true" defined in their value from subAttribute
983 Set<String> allkeys = null;
984 if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
985 JSONObject json = new JSONObject(returnModel.getSub_attributes());
987 allkeys = allManyTrueKeys;
988 allManyTrueKeys = new HashSet <>();
989 LOGGER.info("allkeys : " + allkeys);
992 String allManyTrueKeys = "";
994 allManyTrueKeys = allkeys.toString();
997 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
999 JSONObject jsonObject = new JSONObject(jsonModel);
1001 JSONObject finalJsonObject = null;
1002 if(allkeys != null){
1003 Iterator<String> iter = allkeys.iterator();
1004 while(iter.hasNext()){
1005 //Convert to array values for MANY-true keys
1006 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
1010 if(finalJsonObject != null){
1011 LOGGER.info(finalJsonObject.toString());
1012 jsonModel = finalJsonObject.toString();
1015 //get all properties with "MANY-true" defined in Ref_attributes
1016 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
1017 if(manyTrueProperties != null){
1018 JSONObject jsonObj = new JSONObject(jsonModel);
1019 for (String s : manyTrueProperties) {
1021 //convert to array element for MANY-true properties
1022 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
1025 if(finalJsonObject != null){
1026 LOGGER.info(finalJsonObject.toString());
1027 jsonModel = finalJsonObject.toString();
1031 response.setCharacterEncoding("UTF-8");
1032 response.setContentType("application / json");
1033 request.setCharacterEncoding("UTF-8");
1034 List<Object> list = new ArrayList<>();
1035 PrintWriter out = response.getWriter();
1036 String responseString = mapper.writeValueAsString(returnModel);
1038 if("".equals(allManyTrueKeys)){
1039 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
1041 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+ "}");
1044 out.write(list.toString());
1048 @SuppressWarnings({ "unchecked", "rawtypes" })
1049 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
1050 Map<String, String> attributeMap = new HashMap<>();
1051 Map<String, String> refAttributeMap = new HashMap<>();
1052 String attribute = returnModel.getAttributes();
1053 if(attribute != null){
1054 attribute = attribute.trim();
1056 String refAttribute = returnModel.getRef_attributes();
1057 if(refAttribute != null){
1058 refAttribute = refAttribute.trim();
1060 String enumAttribute = returnModel.getEnumValues();
1061 if(enumAttribute != null){
1062 enumAttribute = enumAttribute.trim();
1064 if (!StringUtils.isEmpty(attribute)){
1065 attributeMap = convert(attribute, ",");
1067 if (!StringUtils.isEmpty(refAttribute)){
1068 refAttributeMap = convert(refAttribute, ",");
1071 Gson gson = new Gson();
1073 String subAttributes = returnModel.getSub_attributes();
1074 if(subAttributes != null){
1075 subAttributes = subAttributes.trim();
1079 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1081 JSONObject object = new JSONObject();
1084 for (Entry<String, String> keySet : attributeMap.entrySet()){
1085 array = new JSONArray();
1086 String value = keySet.getValue();
1087 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
1089 object.put(keySet.getKey().trim(), array);
1091 object.put(keySet.getKey().trim(), value.trim());
1095 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1096 array = new JSONArray();
1097 String value = keySet.getValue().split(":")[0];
1098 if (gsonObject.containsKey(value)){
1099 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
1100 array.put(recursiveReference(value, gsonObject, enumAttribute));
1101 object.put(keySet.getKey().trim(), array);
1103 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1106 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
1107 array.put(value.trim());
1108 object.put(keySet.getKey().trim(), array);
1110 object.put(keySet.getKey().trim(), value.trim());
1117 return object.toString();
1120 @SuppressWarnings("unchecked")
1121 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1122 JSONObject object = new JSONObject();
1123 Map<String, String> map;
1124 Object returnClass = subAttributeMap.get(name);
1125 map = (Map<String, String>) returnClass;
1128 for( Entry<String, String> m:map.entrySet()){
1129 String[] splitValue = m.getValue().split(":");
1130 array = new JSONArray();
1131 if (subAttributeMap.containsKey(splitValue[0])){
1132 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
1133 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1134 object.put(m.getKey().trim(), array);
1136 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1139 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
1140 array.put(splitValue[0].trim());
1141 object.put(m.getKey().trim(), array);
1143 object.put(m.getKey().trim(), splitValue[0].trim());
1152 public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1153 return convertToArrayElement(json, new HashSet<>(), keyValue);
1156 private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1157 for (String key : json.keySet()) {
1158 Object obj = json.get(key);
1159 if(key.equals(keyValue.trim())){
1160 if(!(obj instanceof JSONArray)){
1161 JSONArray newJsonArray = new JSONArray();
1162 newJsonArray.put(obj);
1163 json.put(key, newJsonArray);
1165 LOGGER.info("key : " + key);
1166 LOGGER.info("obj : " + obj);
1167 LOGGER.info("json.get(key) : " + json.get(key));
1168 LOGGER.info("keyValue : " + keyValue);
1169 keys.addAll(json.keySet());
1174 if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);
1180 // call this method to get all MANY-true properties
1181 public static Set<String> getManyTrueProperties(String referAttributes){
1182 LOGGER.info("referAttributes : " + referAttributes);
1183 Set<String> manyTrueProperties = new HashSet<>();
1185 if(referAttributes != null){
1186 String[] referAarray = referAttributes.split(",");
1188 for(int i=0; i<referAarray.length; i++){
1189 element = referAarray[i].split("=");
1190 if(element.length > 1 && element[1].contains("MANY-true")){
1191 manyTrueProperties.add(element[0]);
1196 return manyTrueProperties;
1199 //call this method to start the recursive
1200 private Set<String> getAllKeys(JSONObject json) {
1201 return getAllKeys(json, new HashSet<>());
1204 private Set<String> getAllKeys(JSONArray arr) {
1205 return getAllKeys(arr, new HashSet<>());
1208 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1209 for (int i = 0; i < arr.length(); i++) {
1210 Object obj = arr.get(i);
1211 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
1212 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
1217 // this method returns a set of keys with "MANY-true" defined in their value.
1218 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1219 for (String key : json.keySet()) {
1220 Object obj = json.get(key);
1221 if(obj instanceof String && ((String) obj).contains("MANY-true")){
1222 LOGGER.info("key : " + key);
1223 LOGGER.info("obj : " + obj);
1224 allManyTrueKeys.add(key);
1226 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
1227 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
1234 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1235 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1236 ObjectMapper mapper = new ObjectMapper();
1237 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1238 JsonNode root = mapper.readTree(request.getReader());
1240 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1241 String servicename = value.split("-v")[0];
1242 Set<String> returnList = getVersionList(servicename);
1244 response.setCharacterEncoding("UTF-8");
1245 response.setContentType("application / json");
1246 request.setCharacterEncoding("UTF-8");
1247 List<Object> list = new ArrayList<>();
1248 PrintWriter out = response.getWriter();
1249 String responseString = mapper.writeValueAsString(returnList);
1250 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1252 out.write(list.toString());
1256 private Set<String> getVersionList(String name) {
1257 MicroServiceModels workingModel;
1258 Set<String> list = new HashSet<>();
1259 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1260 for (int i = 0; i < microServiceModelsData.size(); i++) {
1261 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1262 if (workingModel.getVersion()!=null){
1263 list.add(workingModel.getVersion());
1265 list.add("Default");
1271 private MicroServiceModels getAttributeObject(String name, String version) {
1272 MicroServiceModels workingModel = new MicroServiceModels();
1273 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1274 for (int i = 0; i < microServiceModelsData.size(); i++) {
1275 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1276 if(version != null){
1277 if (workingModel.getVersion()!=null){
1278 if (workingModel.getVersion().equals(version)){
1279 return workingModel;
1282 return workingModel;
1285 return workingModel;
1289 return workingModel;
1292 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1293 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1295 Map<String, Object> model = new HashMap<>();
1296 ObjectMapper mapper = new ObjectMapper();
1297 List<String> priorityList = new ArrayList<>();
1299 for (int i = 1; i < priorityCount; i++) {
1300 priorityList.add(String.valueOf(i));
1302 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1303 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1304 JSONObject j = new JSONObject(msg);
1305 response.getWriter().write(j.toString());
1307 catch (Exception e){
1312 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1313 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1314 Object policyData = policyAdapter.getPolicyData();
1315 PolicyType policy = (PolicyType) policyData;
1316 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1317 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1318 policyAdapter.setPolicyName(policyNameValue);
1319 String description = "";
1321 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1322 }catch(Exception e){
1323 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1324 description = policy.getDescription();
1326 policyAdapter.setPolicyDescription(description);
1327 // Get the target data under policy.
1328 TargetType target = policy.getTarget();
1329 if (target != null) {
1330 // Under target we have AnyOFType
1331 List<AnyOfType> anyOfList = target.getAnyOf();
1332 if (anyOfList != null) {
1333 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1334 while (iterAnyOf.hasNext()) {
1335 AnyOfType anyOf = iterAnyOf.next();
1336 // Under AnyOFType we have AllOFType
1337 List<AllOfType> allOfList = anyOf.getAllOf();
1338 if (allOfList != null) {
1339 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1340 while (iterAllOf.hasNext()) {
1341 AllOfType allOf = iterAllOf.next();
1342 // Under AllOFType we have Match
1343 List<MatchType> matchList = allOf.getMatch();
1344 if (matchList != null) {
1345 Iterator<MatchType> iterMatch = matchList.iterator();
1346 while (matchList.size()>1 && iterMatch.hasNext()) {
1347 MatchType match = iterMatch.next();
1349 // Under the match we have attribute value and
1350 // attributeDesignator. So,finally down to the actual attribute.
1352 AttributeValueType attributeValue = match.getAttributeValue();
1353 String value = (String) attributeValue.getContent().get(0);
1354 AttributeDesignatorType designator = match.getAttributeDesignator();
1355 String attributeId = designator.getAttributeId();
1356 // First match in the target is OnapName, so set that value.
1357 if ("ONAPName".equals(attributeId)) {
1358 policyAdapter.setOnapName(value);
1360 if ("ConfigName".equals(attributeId)){
1361 policyAdapter.setConfigName(value);
1363 if ("uuid".equals(attributeId)){
1364 policyAdapter.setUuid(value);
1366 if ("location".equals(attributeId)){
1367 policyAdapter.setLocation(value);
1369 if ("RiskType".equals(attributeId)){
1370 policyAdapter.setRiskType(value);
1372 if ("RiskLevel".equals(attributeId)){
1373 policyAdapter.setRiskLevel(value);
1375 if ("guard".equals(attributeId)){
1376 policyAdapter.setGuard(value);
1378 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
1379 PolicyController controller = new PolicyController();
1380 String newDate = controller.convertDate(value);
1381 policyAdapter.setTtlDate(newDate);
1384 readFile(policyAdapter, entity);
1394 public static Map<String, String> convert(String str, String split) {
1395 Map<String, String> map = new HashMap<>();
1396 for(final String entry : str.split(split)) {
1397 String[] parts = entry.split("=");
1398 map.put(parts[0], parts[1]);
1404 @SuppressWarnings("unchecked")
1405 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1406 String policyScopeName = null;
1407 ObjectMapper mapper = new ObjectMapper();
1409 DCAEMicroServiceObject msBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1410 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1411 policyAdapter.setPolicyScope(policyScopeName);
1413 policyAdapter.setPriority(msBody.getPriority());
1415 if (msBody.getVersion()!= null){
1416 policyAdapter.setServiceType(msBody.getService());
1417 policyAdapter.setVersion(msBody.getVersion());
1419 policyAdapter.setServiceType(msBody.getService());
1421 if(msBody.getContent() != null){
1422 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1423 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1424 readRecursivlyJSONContent(map, data);
1425 policyAdapter.setRuleData(data);
1428 } catch (Exception e) {
1434 @SuppressWarnings({ "rawtypes", "unchecked" })
1435 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1436 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1437 Object key = iterator.next();
1438 Object value = map.get(key);
1439 if(value instanceof LinkedHashMap<?, ?>){
1440 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1441 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1442 for( Entry<String, Object> entry : secondObjec.entrySet()){
1443 data.put(key+"." + entry.getKey(), entry.getValue());
1445 }else if(value instanceof ArrayList){
1446 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1447 for(int i = 0; i < jsonArrayVal.size(); i++){
1448 Object arrayvalue = jsonArrayVal.get(i);
1449 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1450 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1451 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1452 for(Entry<String, Object> entry: newData.entrySet()){
1453 data.put(key+"@"+i+"." +entry.getKey(), entry.getValue());
1455 }else if(arrayvalue instanceof ArrayList){
1456 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1457 for(int j = 0; j < jsonArrayVal1.size(); j++){
1458 Object arrayvalue1 = jsonArrayVal1.get(i);
1459 data.put(key+"@"+j, arrayvalue1.toString());
1462 data.put(key+"@"+i, arrayvalue.toString());
1466 data.put(key.toString(), value.toString());
1471 private String getPolicyScope(String value) {
1472 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1473 if(groupList != null && !groupList.isEmpty()){
1474 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1475 return pScope.getGroupName();
1480 //Convert the map values and set into JSON body
1481 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1482 Map<String, String> attribute = new HashMap<>();
1486 for (Entry<String, String> entry : attributesMap.entrySet()) {
1487 key = entry.getKey();
1488 value = entry.getValue();
1489 attribute.put(key, value);
1491 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1492 key = entryRef.getKey();
1493 value = entryRef.getValue();
1494 attribute.put(key, value);
1496 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1497 key = entryList.getKey();
1498 value = entryList.getValue();
1499 attribute.put(key, value);
1501 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1502 key = arrayList.getKey();
1504 for (Object textList : arrayList.getValue()){
1506 temp = new StringBuilder();
1507 temp.append("[" + textList);
1509 temp.append("," + textList);
1512 attribute.put(key, temp+ "]");
1518 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1519 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1520 modelList = new ArrayList<>();
1521 dirDependencyList = new ArrayList<>();
1522 classMap = new HashMap<>();
1523 retmap = new HashMap<>();
1524 uniqueKeys= new HashSet<>();
1525 uniqueDataKeys= new HashSet<>();
1526 dataListBuffer=new StringBuilder();
1527 dataConstraints= new ArrayList <>();
1528 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1529 boolean zip = false;
1531 String errorMsg = "";
1532 for (FileItem item : items) {
1533 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1534 this.newModel = new MicroServiceModels();
1536 File file = new File(item.getName());
1537 OutputStream outputStream = new FileOutputStream(file);
1538 IOUtils.copy(item.getInputStream(), outputStream);
1539 outputStream.close();
1540 this.newFile = file.toString();
1541 this.newModel.setModelName(this.newFile.split("-v")[0]);
1543 if (this.newFile.contains("-v")){
1544 if (item.getName().endsWith(".zip")){
1545 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1547 }else if(item.getName().endsWith(".yml")){
1548 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1552 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1555 }catch(Exception e){
1556 LOGGER.error("Upload error : ", e);
1557 errorMsg = "Upload error:" + e.getMessage();
1563 if(!errorMsg.isEmpty()){
1565 PrintWriter out = response.getWriter();
1567 response.setCharacterEncoding("UTF-8");
1568 response.setContentType("application / json");
1569 request.setCharacterEncoding("UTF-8");
1571 JSONObject j = new JSONObject();
1572 j.put("errorMsg", errorMsg);
1573 out.write(j.toString());
1577 List<File> fileList = new ArrayList<>();
1578 this.directory = "model";
1580 extractFolder(this.newFile);
1581 fileList = listModelFiles(this.directory);
1583 parseTosca(this.newFile);
1585 File file = new File(this.newFile);
1591 //Process Main Model file first
1592 classMap = new HashMap<>();
1593 for (File file : fileList) {
1594 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1595 retreiveDependency(file.toString(), true);
1599 modelList = createList();
1601 cleanUp(this.newFile);
1605 modelList.add(this.newModel.getModelName());
1606 String className=this.newModel.getModelName();
1607 MSAttributeObject msAttributes= new MSAttributeObject();
1608 msAttributes.setClassName(className);
1610 HashMap<String, String> returnAttributeList =new HashMap<>();
1611 returnAttributeList.put(className, this.attributeString);
1612 msAttributes.setAttribute(returnAttributeList);
1614 msAttributes.setSubClass(this.retmap);
1616 HashMap<String, String> returnReferenceList =new HashMap<>();
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);
1659 try (ZipFile zip = new ZipFile(file)) {
1660 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1661 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1662 checkZipDirectory(this.directory);
1663 new File(newPath).mkdir();
1664 Enumeration zipFileEntries = zip.entries();
1666 // Process each entry
1667 while (zipFileEntries.hasMoreElements()){
1668 // grab a zip file entry
1669 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1670 String currentEntry = entry.getName();
1671 File destFile = new File("model" + File.separator + currentEntry);
1672 File destinationParent = destFile.getParentFile();
1674 destinationParent.mkdirs();
1676 if (!entry.isDirectory()){
1677 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1679 byte[] data = new byte[BUFFER];
1680 try (FileOutputStream fos = new FileOutputStream(destFile);
1681 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1682 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1683 dest.write(data, 0, currentByte);
1686 } catch (IOException e) {
1687 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1689 // PLD should I throw e?
1695 if (currentEntry.endsWith(".zip")){
1696 extractFolder(destFile.getAbsolutePath());
1699 } catch (IOException e) {
1700 LOGGER.error("Failed to unzip model file " + zipFile, e);
1704 private void retreiveDependency(String workingFile, Boolean modelClass) {
1706 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1707 Map<String, MSAttributeObject> tempMap;
1709 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1711 classMap.putAll(tempMap);
1712 LOGGER.info(tempMap);
1718 private List<File> listModelFiles(String directoryName) {
1719 File directory = new File(directoryName);
1720 List<File> resultList = new ArrayList<>();
1721 File[] fList = directory.listFiles();
1722 for (File file : fList) {
1723 if (file.isFile()) {
1724 resultList.add(file);
1725 } else if (file.isDirectory()) {
1726 dirDependencyList.add(file.getName());
1727 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1733 private void cleanUp(String path) {
1736 FileUtils.forceDelete(new File(path));
1737 } catch (IOException e) {
1738 LOGGER.error("Failed to delete folder " + path, e);
1743 private void checkZipDirectory(String zipDirectory) {
1744 Path path = Paths.get(zipDirectory);
1746 if (Files.exists(path)) {
1747 cleanUp(zipDirectory);
1751 private List<String> createList() {
1752 List<String> list = new ArrayList<>();
1753 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1754 if (cMap.getValue().isPolicyTempalate()){
1755 list.add(cMap.getKey());
1760 if (list.isEmpty()){
1761 if (classMap.containsKey(this.newModel.getModelName())){
1762 list.add(this.newModel.getModelName());
1770 public Map<String, String> getAttributesListRefMap() {
1771 return attributesListRefMap;
1774 public Map<String, LinkedList<String>> getArrayTextList() {
1775 return arrayTextList;
1780 class DCAEMicroServiceObject {
1782 private String service;
1783 private String location;
1784 private String uuid;
1785 private String policyName;
1786 private String description;
1787 private String configName;
1788 private String templateVersion;
1789 private String version;
1790 private String priority;
1791 private String policyScope;
1792 private String riskType;
1793 private String riskLevel;
1794 private String guard = null;
1796 public String getGuard() {
1799 public void setGuard(String guard) {
1802 public String getRiskType() {
1805 public void setRiskType(String riskType) {
1806 this.riskType = riskType;
1808 public String getRiskLevel() {
1811 public void setRiskLevel(String riskLevel) {
1812 this.riskLevel = riskLevel;
1814 public String getPolicyScope() {
1817 public void setPolicyScope(String policyScope) {
1818 this.policyScope = policyScope;
1821 public String getPriority() {
1824 public void setPriority(String priority) {
1825 this.priority = priority;
1827 public String getVersion() {
1830 public void setVersion(String version) {
1831 this.version = version;
1833 private Object content;
1836 public String getPolicyName() {
1839 public void setPolicyName(String policyName) {
1840 this.policyName = policyName;
1842 public String getDescription() {
1845 public void setDescription(String description) {
1846 this.description = description;
1848 public String getConfigName() {
1851 public void setConfigName(String configName) {
1852 this.configName = configName;
1854 public Object getContent() {
1857 public void setContent(Object content) {
1858 this.content = content;
1861 public String getService() {
1864 public void setService(String service) {
1865 this.service = service;
1867 public String getLocation() {
1870 public void setLocation(String location) {
1871 this.location = location;
1874 public String getUuid() {
1877 public void setUuid(String uuid) {
1880 public String getTemplateVersion() {
1881 return templateVersion;
1883 public void setTemplateVersion(String templateVersion) {
1884 this.templateVersion = templateVersion;