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.controller.PolicyController;
77 import org.onap.policy.rest.XACMLRestProperties;
78 import org.onap.policy.rest.adapter.PolicyRestAdapter;
79 import org.onap.policy.rest.dao.CommonClassDao;
80 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
81 import org.onap.policy.rest.jpa.MicroServiceModels;
82 import org.onap.policy.rest.jpa.PolicyEntity;
83 import org.onap.policy.rest.util.MSAttributeObject;
84 import org.onap.policy.rest.util.MSModelUtils;
85 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
86 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
87 import org.openecomp.portalsdk.core.web.support.JsonMessage;
88 import org.springframework.beans.factory.annotation.Autowired;
89 import org.springframework.http.MediaType;
90 import org.springframework.stereotype.Controller;
91 import org.springframework.web.bind.annotation.RequestMapping;
92 import org.springframework.web.servlet.ModelAndView;
93 import org.yaml.snakeyaml.Yaml;
95 import com.att.research.xacml.util.XACMLProperties;
96 import com.fasterxml.jackson.core.JsonProcessingException;
97 import com.fasterxml.jackson.databind.DeserializationFeature;
98 import com.fasterxml.jackson.databind.JsonNode;
99 import com.fasterxml.jackson.databind.ObjectMapper;
100 import com.fasterxml.jackson.databind.ObjectWriter;
101 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
102 import com.fasterxml.jackson.databind.node.ObjectNode;
103 import com.google.gson.Gson;
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
106 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
107 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
108 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
109 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
110 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
111 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
115 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
116 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
118 private static CommonClassDao commonClassDao;
120 public static CommonClassDao getCommonClassDao() {
121 return commonClassDao;
124 public static void setCommonClassDao(CommonClassDao commonClassDao) {
125 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
128 private MicroServiceModels newModel;
129 private String newFile;
130 private String directory;
131 private List<String> modelList = new ArrayList<>();
132 private List<String> dirDependencyList = new ArrayList<>();
133 private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
134 //Tosca Model related Datastructure.
135 String referenceAttributes;
136 String attributeString;
137 String listConstraints;
138 String subAttributeString;
139 HashMap<String, Object> retmap = new HashMap<>();
140 Set<String> uniqueKeys= new HashSet<>();
141 Set<String> uniqueDataKeys= new HashSet<>();
142 StringBuilder dataListBuffer=new StringBuilder();
143 List<String> dataConstraints= new ArrayList <>();
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 tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
179 ObjectMapper mapper = new ObjectMapper();
180 JsonNode tempJsonNode = mapper.readTree(tempJson);
181 jsonContent = decodeContent(tempJsonNode).toString();
182 constructJson(policyData, jsonContent, dummyValue);
184 LOGGER.error("Error while decoding microservice content", e);
190 private GroupPolicyScopeList getPolicyObject(String policyScope) {
191 GroupPolicyScopeList groupList= (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 jsonReader = Json.createReader(new StringReader(contentStr))) {
278 JsonObject jsonContent = jsonReader.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();
295 //set modified content to cleanJson
296 JSONObject jObject = new JSONObject(cleanJson);
297 jObject.put("content",removed.toString());
298 cleanJson = cleanUPJson(jObject.toString());
301 } catch (IOException e) {
302 LOGGER.error("Error writing out the JsonNode",e);
307 public static JsonArray removeNull(JsonArray array) {
308 JsonArrayBuilder builder = Json.createArrayBuilder();
310 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
311 JsonValue value = it.next();
312 switch (value.getValueType()) {
314 JsonArray a = removeNull(array.getJsonArray(i));
319 JsonObject object = removeNull(array.getJsonObject(i));
320 if (!object.isEmpty())
324 String s = array.getString(i);
325 if (s != null && !s.isEmpty())
329 builder.add(array.getJsonNumber(i));
333 builder.add(array.getBoolean(i));
339 return builder.build();
342 public static JsonObject removeNull(JsonObject obj) {
343 JsonObjectBuilder builder = Json.createObjectBuilder();
344 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
345 Entry<String, JsonValue> e = it.next();
346 String key = e.getKey();
347 JsonValue value = e.getValue();
348 switch (value.getValueType()) {
350 JsonArray array = removeNull(obj.getJsonArray(key));
351 if (!array.isEmpty())
352 builder.add(key, array);
355 JsonObject object = removeNull(obj.getJsonObject(key));
356 if (!object.isEmpty())
357 builder.add(key, object);
360 String s = obj.getString(key);
361 if (s != null && !s.isEmpty())
365 builder.add(key, obj.getJsonNumber(key));
369 builder.add(key, obj.getBoolean(key));
375 return builder.build();
378 // Second index of dot should be returned.
379 public int stringBetweenDots(String str){
380 String stringToSearch=str;
381 String[]ss=stringToSearch.split("\\.");
385 uniqueKeys.add(ss[2]);
389 return uniqueKeys.size();
392 public void stringBetweenDotsForDataFields(String str){
393 String stringToSearch=str;
394 String[]ss=stringToSearch.split("\\.");
399 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
405 public Map<String, String> load(String fileName) throws IOException {
406 File newConfiguration = new File(fileName);
407 InputStream is = null;
409 is = new FileInputStream(newConfiguration);
410 } catch (FileNotFoundException e) {
414 Yaml yaml = new Yaml();
415 @SuppressWarnings("unchecked")
416 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is);
417 StringBuilder sb = new StringBuilder();
418 Map<String, String> settings = new HashMap<>();
419 if (yamlMap == null) {
422 List<String> path = new ArrayList <>();
423 serializeMap(settings, sb, path, yamlMap);
427 public Map<String, String> load(byte[] source) throws IOException {
428 Yaml yaml = new Yaml();
429 @SuppressWarnings("unchecked")
430 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
431 StringBuilder sb = new StringBuilder();
432 Map<String, String> settings = new HashMap <>();
433 if (yamlMap == null) {
436 List<String> path = new ArrayList <>();
437 serializeMap(settings, sb, path, yamlMap);
441 @SuppressWarnings({ "unchecked", "rawtypes" })
442 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
443 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
444 if (entry.getValue() instanceof Map) {
445 path.add((String) entry.getKey());
446 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
447 path.remove(path.size() - 1);
448 } else if (entry.getValue() instanceof List) {
449 path.add((String) entry.getKey());
450 serializeList(settings, sb, path, (List) entry.getValue());
451 path.remove(path.size() - 1);
453 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
458 @SuppressWarnings("unchecked")
459 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
461 for (Object listEle : yamlList) {
462 if (listEle instanceof Map) {
463 path.add(Integer.toString(counter));
464 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
465 path.remove(path.size() - 1);
466 } else if (listEle instanceof List) {
467 path.add(Integer.toString(counter));
468 serializeList(settings, sb, path, (List<String>) listEle);
469 path.remove(path.size() - 1);
471 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
477 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
482 for (String pathEle : path) {
483 sb.append(pathEle).append('.');
486 settings.put(sb.toString(), value.toString());
489 void parseDataAndPolicyNodes(Map<String,String> map){
490 for(String key:map.keySet()){
491 if(key.contains("policy.nodes.Root"))
495 else if(key.contains("policy.nodes")){
496 String wordToFind = "policy.nodes.";
497 int indexForPolicyNode=key.indexOf(wordToFind);
498 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
500 stringBetweenDots(subNodeString);
502 else if(key.contains("policy.data")){
503 String wordToFind="policy.data.";
504 int indexForPolicyNode=key.indexOf(wordToFind);
505 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
507 stringBetweenDotsForDataFields(subNodeString);
512 HashMap<String,String> parseDataNodes(Map<String,String> map){
513 HashMap<String,String> dataMapForJson=new HashMap <>();
514 for(String uniqueDataKey: uniqueDataKeys){
515 if(uniqueDataKey.contains("%")){
516 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
517 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
518 String typeValue=map.get(findType);
519 LOGGER.info(typeValue);
520 if(typeValue.equalsIgnoreCase(STRING)||
521 typeValue.equalsIgnoreCase(INTEGER)
524 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
525 String defaultValue= map.get(findDefault);
526 LOGGER.info("defaultValue is:"+ defaultValue);
528 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
529 String requiredValue= map.get(findRequired);
530 LOGGER.info("requiredValue is:"+ requiredValue);
532 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
533 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
534 attributeIndividualStringBuilder.append(defaultValue+":required-");
535 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
536 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
538 else if(typeValue.equalsIgnoreCase(LIST)){
539 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
540 String listValue=map.get(findList);
542 LOGGER.info("Type of list is:"+ listValue);
544 if(listValue.contains(".")){
545 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
546 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
547 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
548 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
551 StringBuilder stringListItems= new StringBuilder();
552 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
553 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
554 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
555 for(int i=0;i<10;i++){
556 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
557 String constraintsValue=map.get(findConstraints);
558 LOGGER.info(constraintsValue);
559 if(constraintsValue==null){
563 dataConstraints.add(constraintsValue);
564 dataListBuffer.append(constraintsValue+",");
567 dataListBuffer.append("]#");
569 LOGGER.info(dataListBuffer);
574 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
575 String userDefinedValue=map.get(findUserDefined);
576 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
577 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
578 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
579 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
584 return dataMapForJson;
587 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
588 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
589 HashMap<String,String> hmSub;
590 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
591 String uniqueDataKey= entry.getKey();
592 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
593 String value= dataMapForJson.get(uniqueDataKey);
594 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
595 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
596 hmSub.put(uniqueDataKeySplit[1], value);
599 hmSub=new HashMap <>();
600 hmSub.put(uniqueDataKeySplit[1], value);
603 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
606 JSONObject mainObject= new JSONObject();
608 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
609 String s=entry.getKey();
610 json= new JSONObject();
611 HashMap<String,String> jsonHm=dataMapKey.get(s);
612 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
613 String key=entryMap.getKey();
614 json.put(key, jsonHm.get(key));
616 mainObject.put(s,json);
618 Iterator<String> keysItr = mainObject.keys();
619 while(keysItr.hasNext()) {
620 String key = keysItr.next();
621 String value = mainObject.get(key).toString();
622 retmap.put(key, value);
625 LOGGER.info("#############################################################################");
626 LOGGER.info(mainObject);
627 LOGGER.info("###############################################################################");
631 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
632 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
633 for(String uniqueKey: uniqueKeys){
634 HashMap<String,String> hm;
636 for(Map.Entry<String,String> entry:map.entrySet()){
637 String key=entry.getKey();
638 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
639 if(mapKey.containsKey(uniqueKey)){
640 hm = mapKey.get(uniqueKey);
641 String keyStr= key.substring(key.lastIndexOf('.')+1);
642 String valueStr= map.get(key);
643 if(("type").equals(keyStr)){
644 if(!key.contains("entry_schema"))
646 hm.put(keyStr,valueStr);
649 hm.put(keyStr,valueStr);
653 hm = new HashMap <>();
654 String keyStr= key.substring(key.lastIndexOf('.')+1);
655 String valueStr= map.get(key);
656 if(("type").equals(keyStr)){
657 if(!key.contains("entry_schema"))
659 hm.put(keyStr,valueStr);
662 hm.put(keyStr,valueStr);
664 mapKey.put(uniqueKey, hm);
672 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
673 StringBuilder attributeStringBuilder= new StringBuilder();
674 StringBuilder referenceStringBuilder= new StringBuilder();
675 StringBuilder listBuffer= new StringBuilder();
676 List<String> constraints= new ArrayList<>();
677 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
678 String keySetString= entry.getKey();
679 HashMap<String,String> keyValues=mapKey.get(keySetString);
680 if(keyValues.get("type").equalsIgnoreCase(STRING)||
681 keyValues.get("type").equalsIgnoreCase(INTEGER)
683 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
684 attributeIndividualStringBuilder.append(keySetString+"=");
685 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
686 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
687 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
688 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
691 else if(keyValues.get("type").equalsIgnoreCase(LIST)){
693 Set<String> keys= keyValues.keySet();
694 Iterator<String> itr=keys.iterator();
695 while(itr.hasNext()){
696 String key= itr.next();
697 if((!("type").equals(key) ||("required").equals(key)))
699 String value= keyValues.get(key);
700 //The "." in the value determines if its a string or a user defined type.
701 if (!value.contains(".")){
703 constraints.add(keyValues.get(key));
705 //This is userdefined string
706 String trimValue=value.substring(value.lastIndexOf('.')+1);
707 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
708 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
709 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
715 //User defined Datatype.
716 String value=keyValues.get("type");
717 String trimValue=value.substring(value.lastIndexOf('.')+1);
718 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
719 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
720 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
723 if(constraints!=null &&constraints.isEmpty()==false){
725 listBuffer.append(keySetString.toUpperCase()+"=[");
726 for(String str:constraints){
727 listBuffer.append(str+",");
729 listBuffer.append("]#");
730 LOGGER.info(listBuffer);
733 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
734 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
735 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
740 dataListBuffer.append(listBuffer);
743 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
744 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
745 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
746 LOGGER.info("List String is:"+listBuffer);
747 LOGGER.info("Data list buffer is:"+dataListBuffer);
748 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
750 this.listConstraints=dataListBuffer.toString();
751 this.referenceAttributes=referenceStringBuilder.toString();
752 this.attributeString=attributeStringBuilder.toString();
757 public void parseTosca (String fileName){
758 Map<String,String> map= new HashMap<>();
763 parseDataAndPolicyNodes(map);
765 HashMap<String,String> dataMapForJson=parseDataNodes(map);
767 constructJsonForDataFields(dataMapForJson);
769 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
771 createAttributes(mapKey);
773 } catch (IOException e) {
779 private String cleanUPJson(String json) {
780 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
781 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
782 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
784 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
785 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
786 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
787 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
788 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
789 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
790 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
791 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
792 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
793 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
797 private JSONObject decodeContent(JsonNode jsonNode){
798 Iterator<JsonNode> jsonElements = jsonNode.elements();
799 Iterator<String> jsonKeys = jsonNode.fieldNames();
800 Map<String,String> element = new TreeMap<>();
801 while(jsonElements.hasNext() && jsonKeys.hasNext()){
802 element.put(jsonKeys.next(), jsonElements.next().toString());
804 JSONObject jsonResult = new JSONObject();
805 JSONArray jsonArray = null;
806 String oldValue = null;
807 String nodeKey = null;
808 String arryKey = null;
809 Boolean isArray = false;
810 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
811 ObjectNode node = nodeFactory.objectNode();
812 String prevKey = null;
813 String presKey = null;
814 for(String key: element.keySet()){
815 if(key.contains(".")){
816 presKey = key.substring(0,key.indexOf("."));
817 }else if(key.contains("@")){
818 presKey = key.substring(0,key.indexOf("@"));
822 // first check if we are different from old.
823 LOGGER.info(key+"\n");
824 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
825 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
826 jsonResult.put(oldValue, jsonArray);
827 jsonArray = new JSONArray();
829 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
830 jsonResult.put(oldValue, jsonArray);
832 jsonArray = new JSONArray();
837 if(key.contains(".")){
839 nodeKey = key.substring(0,key.indexOf("."));
841 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
842 node.put(key.substring(key.indexOf(".")+1), element.get(key));
845 if(nodeKey.contains("@")){
847 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
849 if(nodeKey.endsWith("@0")){
851 jsonArray = new JSONArray();
853 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
854 jsonArray.put(decodeContent(node));
856 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){
857 jsonResult.put(arryKey, jsonArray);
858 jsonArray = new JSONArray();
860 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
863 jsonResult.put(nodeKey, decodeContent(node));
865 node = nodeFactory.objectNode();
867 nodeKey = key.substring(0,key.indexOf("."));
868 if(nodeKey.contains("@")){
869 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
871 node.put(key.substring(key.indexOf(".")+1), element.get(key));
873 }else if(node.size()!=0){
874 if(nodeKey.contains("@")){
876 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
878 if(nodeKey.endsWith("@0")){
880 jsonArray = new JSONArray();
882 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
883 jsonArray.put(decodeContent(node));
885 jsonResult.put(arryKey, jsonArray);
886 jsonArray = new JSONArray();
887 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
890 jsonResult.put(nodeKey, decodeContent(node));
892 node = nodeFactory.objectNode();
893 if(key.contains("@")){
895 if(key.endsWith("@0")|| jsonArray==null){
896 jsonArray = new JSONArray();
898 }else if(!key.contains("@")){
903 oldValue = key.substring(0,key.indexOf("@"));
905 if(oldValue!=prevKey){
906 oldValue = key.substring(0,key.indexOf("@"));
908 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
909 jsonArray.put(element.get(key));
911 jsonResult.put(oldValue, jsonArray);
912 jsonArray = new JSONArray();
914 oldValue = key.substring(0,key.indexOf("@"));
916 jsonResult.put(key, element.get(key));
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(element.get(key));
937 jsonResult.put(oldValue, jsonArray);
938 jsonArray = new JSONArray();
940 oldValue = key.substring(0,key.indexOf("@"));
942 jsonResult.put(key, element.get(key));
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.toString().split("-v")[0];
975 String version = null;
976 if (value.toString().contains("-v")){
977 version = value.toString().split("-v")[1];
979 MicroServiceModels returnModel = getAttributeObject(servicename, version);
981 String jsonModel = createMicroSeriveJson(returnModel);
983 response.setCharacterEncoding("UTF-8");
984 response.setContentType("application / json");
985 request.setCharacterEncoding("UTF-8");
986 List<Object> list = new ArrayList<>();
987 PrintWriter out = response.getWriter();
988 String responseString = mapper.writeValueAsString(returnModel);
989 JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
991 out.write(list.toString());
995 @SuppressWarnings({ "unchecked", "rawtypes" })
996 private String createMicroSeriveJson(MicroServiceModels returnModel) {
997 Map<String, String> attributeMap = new HashMap<>();
998 Map<String, String> refAttributeMap = new HashMap<>();
999 String attribute = returnModel.getAttributes();
1000 if(attribute != null){
1001 attribute = attribute.trim();
1003 String refAttribute = returnModel.getRef_attributes();
1004 if(refAttribute != null){
1005 refAttribute = refAttribute.trim();
1007 String enumAttribute = returnModel.getEnumValues();
1008 if(enumAttribute != null){
1009 enumAttribute = enumAttribute.trim();
1011 if (!StringUtils.isEmpty(attribute)){
1012 attributeMap = convert(attribute, ",");
1014 if (!StringUtils.isEmpty(refAttribute)){
1015 refAttributeMap = convert(refAttribute, ",");
1018 Gson gson = new Gson();
1020 String subAttributes = returnModel.getSub_attributes();
1021 if(subAttributes != null){
1022 subAttributes = subAttributes.trim();
1026 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1028 JSONObject object = new JSONObject();
1029 JSONArray array = new JSONArray();
1031 for (Entry<String, String> keySet : attributeMap.entrySet()){
1032 array = new JSONArray();
1033 String value = keySet.getValue();
1034 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1036 object.put(keySet.getKey().trim(), array);
1038 object.put(keySet.getKey().trim(), value.trim());
1042 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1043 array = new JSONArray();
1044 String value = keySet.getValue().split(":")[0];
1045 if (gsonObject.containsKey(value)){
1046 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1047 array.put(recursiveReference(value, gsonObject, enumAttribute));
1048 object.put(keySet.getKey().trim(), array);
1050 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1053 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1054 array.put(value.trim());
1055 object.put(keySet.getKey().trim(), array);
1057 object.put(keySet.getKey().trim(), value.trim());
1062 return object.toString();
1065 @SuppressWarnings("unchecked")
1066 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1067 JSONObject object = new JSONObject();
1068 Map<String, String> map = new HashMap<>();
1069 Object returnClass = subAttributeMap.get(name);
1070 map = (Map<String, String>) returnClass;
1071 JSONArray array = new JSONArray();
1073 for( Entry<String, String> m:map.entrySet()){
1074 String[] splitValue = m.getValue().split(":");
1075 array = new JSONArray();
1076 if (subAttributeMap.containsKey(splitValue[0])){
1077 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1078 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1079 object.put(m.getKey().trim(), array);
1081 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1084 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1085 array.put(splitValue[0].trim());
1086 object.put(m.getKey().trim(), array);
1088 object.put(m.getKey().trim(), splitValue[0].trim());
1097 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1098 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1099 ObjectMapper mapper = new ObjectMapper();
1100 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1101 JsonNode root = mapper.readTree(request.getReader());
1103 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1104 String servicename = value.toString().split("-v")[0];
1105 Set<String> returnList = getVersionList(servicename);
1107 response.setCharacterEncoding("UTF-8");
1108 response.setContentType("application / json");
1109 request.setCharacterEncoding("UTF-8");
1110 List<Object> list = new ArrayList<>();
1111 PrintWriter out = response.getWriter();
1112 String responseString = mapper.writeValueAsString(returnList);
1113 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1115 out.write(list.toString());
1119 private Set<String> getVersionList(String name) {
1120 MicroServiceModels workingModel = new MicroServiceModels();
1121 Set<String> list = new HashSet<>();
1122 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1123 for (int i = 0; i < microServiceModelsData.size(); i++) {
1124 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1125 if (workingModel.getVersion()!=null){
1126 list.add(workingModel.getVersion());
1128 list.add("Default");
1134 private MicroServiceModels getAttributeObject(String name, String version) {
1135 MicroServiceModels workingModel = new MicroServiceModels();
1136 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1137 for (int i = 0; i < microServiceModelsData.size(); i++) {
1138 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1139 if(version != null){
1140 if (workingModel.getVersion()!=null){
1141 if (workingModel.getVersion().equals(version)){
1142 return workingModel;
1145 return workingModel;
1148 return workingModel;
1152 return workingModel;
1155 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1156 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1158 Map<String, Object> model = new HashMap<>();
1159 ObjectMapper mapper = new ObjectMapper();
1160 List<String> priorityList = new ArrayList<>();
1162 for (int i = 1; i < priorityCount; i++) {
1163 priorityList.add(String.valueOf(i));
1165 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1166 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1167 JSONObject j = new JSONObject(msg);
1168 response.getWriter().write(j.toString());
1170 catch (Exception e){
1175 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1176 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1177 Object policyData = policyAdapter.getPolicyData();
1178 PolicyType policy = (PolicyType) policyData;
1179 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1180 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1181 policyAdapter.setPolicyName(policyNameValue);
1182 String description = "";
1184 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1185 }catch(Exception e){
1186 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1187 description = policy.getDescription();
1189 policyAdapter.setPolicyDescription(description);
1190 // Get the target data under policy.
1191 TargetType target = policy.getTarget();
1192 if (target != null) {
1193 // Under target we have AnyOFType
1194 List<AnyOfType> anyOfList = target.getAnyOf();
1195 if (anyOfList != null) {
1196 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1197 while (iterAnyOf.hasNext()) {
1198 AnyOfType anyOf = iterAnyOf.next();
1199 // Under AnyOFType we have AllOFType
1200 List<AllOfType> allOfList = anyOf.getAllOf();
1201 if (allOfList != null) {
1202 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1203 while (iterAllOf.hasNext()) {
1204 AllOfType allOf = iterAllOf.next();
1205 // Under AllOFType we have Match
1206 List<MatchType> matchList = allOf.getMatch();
1207 if (matchList != null) {
1208 Iterator<MatchType> iterMatch = matchList.iterator();
1209 while (matchList.size()>1 && iterMatch.hasNext()) {
1210 MatchType match = iterMatch.next();
1212 // Under the match we have attribute value and
1213 // attributeDesignator. So,finally down to the actual attribute.
1215 AttributeValueType attributeValue = match.getAttributeValue();
1216 String value = (String) attributeValue.getContent().get(0);
1217 AttributeDesignatorType designator = match.getAttributeDesignator();
1218 String attributeId = designator.getAttributeId();
1219 // First match in the target is OnapName, so set that value.
1220 if (attributeId.equals("ONAPName")) {
1221 policyAdapter.setOnapName(value);
1223 if (attributeId.equals("ConfigName")){
1224 policyAdapter.setConfigName(value);
1226 if (attributeId.equals("uuid")){
1227 policyAdapter.setUuid(value);
1229 if (attributeId.equals("location")){
1230 policyAdapter.setLocation(value);
1232 if (attributeId.equals("RiskType")){
1233 policyAdapter.setRiskType(value);
1235 if (attributeId.equals("RiskLevel")){
1236 policyAdapter.setRiskLevel(value);
1238 if (attributeId.equals("guard")){
1239 policyAdapter.setGuard(value);
1241 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1242 PolicyController controller = new PolicyController();
1243 String newDate = controller.convertDate(value);
1244 policyAdapter.setTtlDate(newDate);
1247 readFile(policyAdapter, entity);
1257 public static Map<String, String> convert(String str, String split) {
1258 Map<String, String> map = new HashMap<>();
1259 for(final String entry : str.split(split)) {
1260 String[] parts = entry.split("=");
1261 map.put(parts[0], parts[1]);
1267 @SuppressWarnings("unchecked")
1268 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1269 String policyScopeName = null;
1270 ObjectMapper mapper = new ObjectMapper();
1272 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1273 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1274 policyAdapter.setPolicyScope(policyScopeName);
1276 policyAdapter.setPriority(msBody.getPriority());
1278 if (msBody.getVersion()!= null){
1279 policyAdapter.setServiceType(msBody.getService());
1280 policyAdapter.setVersion(msBody.getVersion());
1282 policyAdapter.setServiceType(msBody.getService());
1284 if(msBody.getContent() != null){
1285 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1286 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1287 readRecursivlyJSONContent(map, data);
1288 policyAdapter.setRuleData(data);
1291 } catch (Exception e) {
1297 @SuppressWarnings({ "rawtypes", "unchecked" })
1298 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1299 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1300 Object key = iterator.next();
1301 Object value = map.get(key);
1302 if(value instanceof LinkedHashMap<?, ?>){
1303 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1304 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1305 for(String objKey: secondObjec.keySet()){
1306 data.put(key+"." +objKey, secondObjec.get(objKey));
1308 }else if(value instanceof ArrayList){
1309 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1310 for(int i = 0; i < jsonArrayVal.size(); i++){
1311 Object arrayvalue = jsonArrayVal.get(i);
1312 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1313 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1314 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1315 for(String objKey: newData.keySet()){
1316 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1318 }else if(arrayvalue instanceof ArrayList){
1319 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1320 for(int j = 0; j < jsonArrayVal1.size(); j++){
1321 Object arrayvalue1 = jsonArrayVal1.get(i);
1322 data.put(key+"@"+j, arrayvalue1.toString());
1325 data.put(key+"@"+i, arrayvalue.toString());
1329 data.put(key.toString(), value.toString());
1334 private String getPolicyScope(String value) {
1335 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1336 if(groupList != null && !groupList.isEmpty()){
1337 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1338 return pScope.getGroupName();
1343 //Convert the map values and set into JSON body
1344 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1345 Map<String, String> attribute = new HashMap<>();
1349 for (Entry<String, String> entry : attributesMap.entrySet()) {
1350 key = entry.getKey();
1351 value = entry.getValue();
1352 attribute.put(key, value);
1354 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1355 key = entryRef.getKey();
1356 value = entryRef.getValue().toString();
1357 attribute.put(key, value);
1359 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1360 key = entryList.getKey();
1361 value = entryList.getValue().toString();
1362 attribute.put(key, value);
1364 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1365 key = arrayList.getKey();
1367 for (Object textList : arrayList.getValue()){
1369 temp = "[" + textList;
1371 temp = temp + "," + textList;
1374 attribute.put(key, temp+ "]");
1380 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1381 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1382 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1383 boolean zip = false;
1385 for (FileItem item : items) {
1386 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1387 this.newModel = new MicroServiceModels();
1389 File file = new File(item.getName());
1390 OutputStream outputStream = new FileOutputStream(file);
1391 IOUtils.copy(item.getInputStream(), outputStream);
1392 outputStream.close();
1393 this.newFile = file.toString();
1394 this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
1396 if (this.newFile.toString().contains("-v")){
1397 if (item.getName().endsWith(".zip")){
1398 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
1400 }else if(item.getName().endsWith(".yml")){
1401 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
1405 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
1409 }catch(Exception e){
1410 LOGGER.error("Upload error : " + e);
1415 List<File> fileList = new ArrayList<>();;
1416 this.directory = "model";
1418 extractFolder(this.newFile);
1419 fileList = listModelFiles(this.directory);
1420 }else if (yml==true){
1421 parseTosca(this.newFile);
1423 File file = new File(this.newFile);
1426 String modelType= "";
1429 //Process Main Model file first
1430 classMap = new HashMap<>();
1431 for (File file : fileList) {
1432 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1433 retreiveDependency(file.toString(), true);
1437 modelList = createList();
1439 cleanUp(this.newFile);
1443 modelList.add(this.newModel.getModelName());
1444 String className=this.newModel.getModelName();
1445 MSAttributeObject msAttributes= new MSAttributeObject();
1446 msAttributes.setClassName(className);
1448 HashMap<String, String> returnAttributeList =new HashMap<>();
1449 returnAttributeList.put(className, this.attributeString);
1450 msAttributes.setAttribute(returnAttributeList);
1452 msAttributes.setSubClass(this.retmap);
1454 HashMap<String, String> returnReferenceList =new HashMap<>();
1455 //String[] referenceArray=this.referenceAttributes.split("=");
1456 returnReferenceList.put(className, this.referenceAttributes);
1457 msAttributes.setRefAttribute(returnReferenceList);
1459 if(this.listConstraints!=""){
1460 HashMap<String, String> enumList =new HashMap<>();
1461 String[] listArray=this.listConstraints.split("#");
1462 for(String str:listArray){
1463 String[] strArr= str.split("=");
1464 if(strArr.length>1){
1465 enumList.put(strArr[0], strArr[1]);
1468 msAttributes.setEnumType(enumList);
1471 classMap=new HashMap<>();
1472 classMap.put(className, msAttributes);
1476 PrintWriter out = response.getWriter();
1478 response.setCharacterEncoding("UTF-8");
1479 response.setContentType("application / json");
1480 request.setCharacterEncoding("UTF-8");
1482 ObjectMapper mapper = new ObjectMapper();
1483 JSONObject j = new JSONObject();
1484 j.put("classListDatas", modelList);
1485 j.put("modelDatas", mapper.writeValueAsString(classMap));
1486 j.put("modelType", modelType);
1487 out.write(j.toString());
1491 * Unzip file and store in the model directory for processing
1493 @SuppressWarnings("rawtypes")
1494 private void extractFolder(String zipFile ) {
1496 File file = new File(zipFile);
1500 zip = new ZipFile(file);
1501 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1502 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1503 checkZipDirectory(this.directory);
1504 new File(newPath).mkdir();
1505 Enumeration zipFileEntries = zip.entries();
1507 // Process each entry
1508 while (zipFileEntries.hasMoreElements()){
1509 // grab a zip file entry
1510 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1511 String currentEntry = entry.getName();
1512 File destFile = new File("model" + File.separator + currentEntry);
1513 File destinationParent = destFile.getParentFile();
1515 destinationParent.mkdirs();
1517 if (!entry.isDirectory()){
1518 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1520 byte data[] = new byte[BUFFER];
1521 FileOutputStream fos = new FileOutputStream(destFile);
1522 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1523 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1524 dest.write(data, 0, currentByte);
1531 if (currentEntry.endsWith(".zip")){
1532 extractFolder(destFile.getAbsolutePath());
1535 } catch (IOException e) {
1536 LOGGER.error("Failed to unzip model file " + zipFile, e);
1541 } catch (IOException e) {
1542 LOGGER.error("Exception Occured While closing zipfile " + e);
1547 private void retreiveDependency(String workingFile, Boolean modelClass) {
1549 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1550 HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
1552 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1554 classMap.putAll(tempMap);
1555 LOGGER.info(tempMap);
1561 private List<File> listModelFiles(String directoryName) {
1562 File directory = new File(directoryName);
1563 List<File> resultList = new ArrayList<>();
1564 File[] fList = directory.listFiles();
1565 for (File file : fList) {
1566 if (file.isFile()) {
1567 resultList.add(file);
1568 } else if (file.isDirectory()) {
1569 dirDependencyList.add(file.getName());
1570 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1576 private void cleanUp(String path) {
1579 FileUtils.forceDelete(new File(path));
1580 } catch (IOException e) {
1581 LOGGER.error("Failed to delete folder " + path, e);
1586 private void checkZipDirectory(String zipDirectory) {
1587 Path path = Paths.get(zipDirectory);
1589 if (Files.exists(path)) {
1590 cleanUp(zipDirectory);
1594 private List<String> createList() {
1595 List<String> list = new ArrayList<>();
1596 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1597 if (cMap.getValue().isPolicyTempalate()){
1598 list.add(cMap.getKey());
1603 if (list.isEmpty()){
1604 if (classMap.containsKey(this.newModel.getModelName())){
1605 list.add(this.newModel.getModelName());
1613 public Map<String, String> getAttributesListRefMap() {
1614 return attributesListRefMap;
1617 public Map<String, LinkedList<String>> getArrayTextList() {
1618 return arrayTextList;
1623 class DCAEMicroServiceObject {
1625 private String service;
1626 private String location;
1627 private String uuid;
1628 private String policyName;
1629 private String description;
1630 private String configName;
1631 private String templateVersion;
1632 private String version;
1633 private String priority;
1634 private String policyScope;
1635 private String riskType;
1636 private String riskLevel;
1637 private String guard = null;
1639 public String getGuard() {
1642 public void setGuard(String guard) {
1645 public String getRiskType() {
1648 public void setRiskType(String riskType) {
1649 this.riskType = riskType;
1651 public String getRiskLevel() {
1654 public void setRiskLevel(String riskLevel) {
1655 this.riskLevel = riskLevel;
1657 public String getPolicyScope() {
1660 public void setPolicyScope(String policyScope) {
1661 this.policyScope = policyScope;
1664 public String getPriority() {
1667 public void setPriority(String priority) {
1668 this.priority = priority;
1670 public String getVersion() {
1673 public void setVersion(String version) {
1674 this.version = version;
1676 private Object content;
1679 public String getPolicyName() {
1682 public void setPolicyName(String policyName) {
1683 this.policyName = policyName;
1685 public String getDescription() {
1688 public void setDescription(String description) {
1689 this.description = description;
1691 public String getConfigName() {
1694 public void setConfigName(String configName) {
1695 this.configName = configName;
1697 public Object getContent() {
1700 public void setContent(Object content) {
1701 this.content = content;
1704 public String getService() {
1707 public void setService(String service) {
1708 this.service = service;
1710 public String getLocation() {
1713 public void setLocation(String location) {
1714 this.location = location;
1717 public String getUuid() {
1720 public void setUuid(String uuid) {
1723 public String getTemplateVersion() {
1724 return templateVersion;
1726 public void setTemplateVersion(String templateVersion) {
1727 this.templateVersion = templateVersion;