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.JsonValue;
61 import javax.servlet.http.HttpServletRequest;
62 import javax.servlet.http.HttpServletResponse;
64 import org.apache.commons.compress.utils.IOUtils;
65 import org.apache.commons.fileupload.FileItem;
66 import org.apache.commons.fileupload.FileUploadException;
67 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
68 import org.apache.commons.fileupload.servlet.ServletFileUpload;
69 import org.apache.commons.io.FileUtils;
70 import org.apache.commons.lang.StringUtils;
71 import org.json.JSONArray;
72 import org.json.JSONObject;
73 import org.onap.policy.common.logging.flexlogger.FlexLogger;
74 import org.onap.policy.common.logging.flexlogger.Logger;
75 import org.onap.policy.rest.XACMLRestProperties;
76 import org.onap.policy.rest.adapter.PolicyRestAdapter;
77 import org.onap.policy.rest.dao.CommonClassDao;
78 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
79 import org.onap.policy.rest.jpa.MicroServiceModels;
80 import org.onap.policy.rest.jpa.PolicyEntity;
81 import org.onap.policy.rest.util.MSAttributeObject;
82 import org.onap.policy.rest.util.MSModelUtils;
83 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
84 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
85 import org.openecomp.portalsdk.core.web.support.JsonMessage;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.http.MediaType;
88 import org.springframework.stereotype.Controller;
89 import org.springframework.web.bind.annotation.RequestMapping;
90 import org.springframework.web.servlet.ModelAndView;
91 import org.yaml.snakeyaml.Yaml;
93 import com.att.research.xacml.util.XACMLProperties;
94 import com.fasterxml.jackson.core.JsonProcessingException;
95 import com.fasterxml.jackson.databind.DeserializationFeature;
96 import com.fasterxml.jackson.databind.JsonNode;
97 import com.fasterxml.jackson.databind.ObjectMapper;
98 import com.fasterxml.jackson.databind.ObjectWriter;
99 import com.fasterxml.jackson.databind.node.ArrayNode;
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 <>();
144 public static final String DATATYPE = "data_types.policy.data.";
145 public static final String PROPERTIES=".properties.";
146 public static final String TYPE=".type";
147 public static final String STRING="string";
148 public static final String INTEGER="integer";
149 public static final String LIST="list";
150 public static final String DEFAULT=".default";
151 public static final String REQUIRED=".required";
152 public static final String MANYFALSE=":MANY-false";
156 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
157 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
160 public CreateDcaeMicroServiceController(){}
162 protected PolicyRestAdapter policyAdapter = null;
163 private int priorityCount;
164 private Map<String, String> attributesListRefMap = new HashMap<>();
165 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
167 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
169 String jsonContent = null;
171 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
173 String tempJson = root.get("policyJSON").toString();
175 //---replace empty value with the value below before calling decodeContent method.
176 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
177 tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
178 ObjectMapper mapper = new ObjectMapper();
179 JsonNode tempJsonNode = mapper.readTree(tempJson);
180 jsonContent = decodeContent(tempJsonNode).toString();
181 constructJson(policyData, jsonContent, dummyValue);
183 LOGGER.error("Error while decoding microservice content", e);
189 private GroupPolicyScopeList getPolicyObject(String policyScope) {
190 GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
194 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
195 ObjectWriter om = new ObjectMapper().writer();
197 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
198 MicroServiceModels returnModel = new MicroServiceModels();
199 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
200 if(policyAdapter.getServiceType() !=null){
201 microServiceObject.setService(policyAdapter.getServiceType());
202 microServiceObject.setVersion(policyAdapter.getVersion());
203 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
205 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
206 if(policyAdapter.getUuid()!=null){
207 microServiceObject.setUuid(policyAdapter.getUuid());
209 if(policyAdapter.getLocation()!=null){
210 microServiceObject.setLocation(policyAdapter.getLocation());
212 if(policyAdapter.getConfigName()!=null){
213 microServiceObject.setConfigName(policyAdapter.getConfigName());
215 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
216 if(policyScopeValue!=null){
217 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
221 if(policyAdapter.getPolicyName()!=null){
222 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
224 if(policyAdapter.getPolicyDescription()!=null){
225 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
227 if (policyAdapter.getPriority()!=null){
228 microServiceObject.setPriority(policyAdapter.getPriority());
230 microServiceObject.setPriority("9999");
233 if (policyAdapter.getRiskLevel()!=null){
234 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
236 if (policyAdapter.getRiskType()!=null){
237 microServiceObject.setRiskType(policyAdapter.getRiskType());
239 if (policyAdapter.getGuard()!=null){
240 microServiceObject.setGuard(policyAdapter.getGuard());
242 microServiceObject.setContent(jsonContent);
245 json = om.writeValueAsString(microServiceObject);
246 } catch (JsonProcessingException e) {
247 LOGGER.error("Error writing out the object", e);
249 LOGGER.info("input json: " + json);
250 LOGGER.info("input jsonContent: " + jsonContent);
251 String cleanJson = cleanUPJson(json);
252 //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
253 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
254 LOGGER.info("tempJson: " + tempJson);
255 cleanJson = removeNullAttributes(tempJson);
256 policyAdapter.setJsonBody(cleanJson);
257 return policyAdapter;
260 private String removeNullAttributes(String cleanJson) {
261 ObjectMapper mapper = new ObjectMapper();
264 JsonNode rootNode = mapper.readTree(cleanJson);
265 JsonNode returnNode = mapper.readTree(cleanJson);
266 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
267 boolean remove = false;
268 JsonObject removed = null;
269 boolean contentChanged = false;
270 while (fieldsIterator.hasNext()) {
271 Map.Entry<String, JsonNode> field = fieldsIterator.next();
272 final String key = field.getKey();
273 final JsonNode value = field.getValue();
274 if("content".equalsIgnoreCase(key)){
275 String contentStr = value.toString();
276 JsonObject jsonContent = Json.createReader(new StringReader(contentStr)).readObject();
277 removed = removeNull(jsonContent);
278 if(!jsonContent.toString().equals(removed.toString())){
279 contentChanged = true;
282 if (value==null || value.isNull()){
283 ((ObjectNode) returnNode).remove(key);
288 cleanJson = returnNode.toString();
292 //set modified content to cleanJson
293 JSONObject jObject = new JSONObject(cleanJson);
294 jObject.put("content",removed.toString());
295 cleanJson = cleanUPJson(jObject.toString());
298 } catch (IOException e) {
299 LOGGER.error("Error writing out the JsonNode",e);
304 public static JsonArray removeNull(JsonArray array) {
305 JsonArrayBuilder builder = Json.createArrayBuilder();
307 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
308 JsonValue value = it.next();
309 switch (value.getValueType()) {
311 JsonArray a = removeNull(array.getJsonArray(i));
316 JsonObject object = removeNull(array.getJsonObject(i));
317 if (!object.isEmpty())
321 String s = array.getString(i);
322 if (s != null && !s.isEmpty())
326 builder.add(array.getJsonNumber(i));
330 builder.add(array.getBoolean(i));
336 return builder.build();
339 public static JsonObject removeNull(JsonObject obj) {
340 JsonObjectBuilder builder = Json.createObjectBuilder();
341 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
342 Entry<String, JsonValue> e = it.next();
343 String key = e.getKey();
344 JsonValue value = e.getValue();
345 switch (value.getValueType()) {
347 JsonArray array = removeNull(obj.getJsonArray(key));
348 if (!array.isEmpty())
349 builder.add(key, array);
352 JsonObject object = removeNull(obj.getJsonObject(key));
353 if (!object.isEmpty())
354 builder.add(key, object);
357 String s = obj.getString(key);
358 if (s != null && !s.isEmpty())
362 builder.add(key, obj.getJsonNumber(key));
366 builder.add(key, obj.getBoolean(key));
372 return builder.build();
375 // Second index of dot should be returned.
376 public int stringBetweenDots(String str){
377 String stringToSearch=str;
378 String[]ss=stringToSearch.split("\\.");
382 uniqueKeys.add(ss[2]);
386 return uniqueKeys.size();
389 public void stringBetweenDotsForDataFields(String str){
390 String stringToSearch=str;
391 String[]ss=stringToSearch.split("\\.");
396 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
402 public Map<String, String> load(String fileName) throws IOException {
403 File newConfiguration = new File(fileName);
404 InputStream is = null;
406 is = new FileInputStream(newConfiguration);
407 } catch (FileNotFoundException e) {
411 Yaml yaml = new Yaml();
412 @SuppressWarnings("unchecked")
413 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is);
414 StringBuilder sb = new StringBuilder();
415 Map<String, String> settings = new HashMap<>();
416 if (yamlMap == null) {
419 List<String> path = new ArrayList <>();
420 serializeMap(settings, sb, path, yamlMap);
424 public Map<String, String> load(byte[] source) throws IOException {
425 Yaml yaml = new Yaml();
426 @SuppressWarnings("unchecked")
427 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
428 StringBuilder sb = new StringBuilder();
429 Map<String, String> settings = new HashMap <>();
430 if (yamlMap == null) {
433 List<String> path = new ArrayList <>();
434 serializeMap(settings, sb, path, yamlMap);
438 @SuppressWarnings({ "unchecked", "rawtypes" })
439 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
440 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
441 if (entry.getValue() instanceof Map) {
442 path.add((String) entry.getKey());
443 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
444 path.remove(path.size() - 1);
445 } else if (entry.getValue() instanceof List) {
446 path.add((String) entry.getKey());
447 serializeList(settings, sb, path, (List) entry.getValue());
448 path.remove(path.size() - 1);
450 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
455 @SuppressWarnings("unchecked")
456 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
458 for (Object listEle : yamlList) {
459 if (listEle instanceof Map) {
460 path.add(Integer.toString(counter));
461 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
462 path.remove(path.size() - 1);
463 } else if (listEle instanceof List) {
464 path.add(Integer.toString(counter));
465 serializeList(settings, sb, path, (List<String>) listEle);
466 path.remove(path.size() - 1);
468 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
474 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
479 for (String pathEle : path) {
480 sb.append(pathEle).append('.');
483 settings.put(sb.toString(), value.toString());
486 void parseDataAndPolicyNodes(Map<String,String> map){
487 for(String key:map.keySet()){
488 if(key.contains("policy.nodes.Root"))
492 else if(key.contains("policy.nodes")){
493 String wordToFind = "policy.nodes.";
494 int indexForPolicyNode=key.indexOf(wordToFind);
495 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
497 stringBetweenDots(subNodeString);
499 else if(key.contains("policy.data")){
500 String wordToFind="policy.data.";
501 int indexForPolicyNode=key.indexOf(wordToFind);
502 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
504 stringBetweenDotsForDataFields(subNodeString);
509 HashMap<String,String> parseDataNodes(Map<String,String> map){
510 HashMap<String,String> dataMapForJson=new HashMap <>();
511 for(String uniqueDataKey: uniqueDataKeys){
512 if(uniqueDataKey.contains("%")){
513 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
514 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
515 String typeValue=map.get(findType);
516 LOGGER.info(typeValue);
517 if(typeValue.equalsIgnoreCase(STRING)||
518 typeValue.equalsIgnoreCase(INTEGER)
521 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
522 String defaultValue= map.get(findDefault);
523 LOGGER.info("defaultValue is:"+ defaultValue);
525 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
526 String requiredValue= map.get(findRequired);
527 LOGGER.info("requiredValue is:"+ requiredValue);
529 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
530 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
531 attributeIndividualStringBuilder.append(defaultValue+":required-");
532 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
533 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
535 else if(typeValue.equalsIgnoreCase(LIST)){
536 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
537 String listValue=map.get(findList);
539 LOGGER.info("Type of list is:"+ listValue);
541 if(listValue.contains(".")){
542 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
543 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
544 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
545 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
548 StringBuilder stringListItems= new StringBuilder();
549 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
550 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
551 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
552 for(int i=0;i<10;i++){
553 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
554 String constraintsValue=map.get(findConstraints);
555 LOGGER.info(constraintsValue);
556 if(constraintsValue==null){
560 dataConstraints.add(constraintsValue);
561 dataListBuffer.append(constraintsValue+",");
564 dataListBuffer.append("]#");
566 LOGGER.info(dataListBuffer);
571 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
572 String userDefinedValue=map.get(findUserDefined);
573 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
574 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
575 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
576 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
581 return dataMapForJson;
584 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
585 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
586 HashMap<String,String> hmSub;
587 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
588 String uniqueDataKey= entry.getKey();
589 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
590 String value= dataMapForJson.get(uniqueDataKey);
591 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
592 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
593 hmSub.put(uniqueDataKeySplit[1], value);
596 hmSub=new HashMap <>();
597 hmSub.put(uniqueDataKeySplit[1], value);
600 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
603 JSONObject mainObject= new JSONObject();
605 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
606 String s=entry.getKey();
607 json= new JSONObject();
608 HashMap<String,String> jsonHm=dataMapKey.get(s);
609 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
610 String key=entryMap.getKey();
611 json.put(key, jsonHm.get(key));
613 mainObject.put(s,json);
615 Iterator<String> keysItr = mainObject.keys();
616 while(keysItr.hasNext()) {
617 String key = keysItr.next();
618 String value = mainObject.get(key).toString();
619 retmap.put(key, value);
622 LOGGER.info("#############################################################################");
623 LOGGER.info(mainObject);
624 LOGGER.info("###############################################################################");
628 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
629 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
630 for(String uniqueKey: uniqueKeys){
631 HashMap<String,String> hm;
633 for(Map.Entry<String,String> entry:map.entrySet()){
634 String key=entry.getKey();
635 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
636 if(mapKey.containsKey(uniqueKey)){
637 hm = mapKey.get(uniqueKey);
638 String keyStr= key.substring(key.lastIndexOf('.')+1);
639 String valueStr= map.get(key);
640 if(("type").equals(keyStr)){
641 if(!key.contains("entry_schema"))
643 hm.put(keyStr,valueStr);
646 hm.put(keyStr,valueStr);
650 hm = new HashMap <>();
651 String keyStr= key.substring(key.lastIndexOf('.')+1);
652 String valueStr= map.get(key);
653 if(("type").equals(keyStr)){
654 if(!key.contains("entry_schema"))
656 hm.put(keyStr,valueStr);
659 hm.put(keyStr,valueStr);
661 mapKey.put(uniqueKey, hm);
669 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
670 StringBuilder attributeStringBuilder= new StringBuilder();
671 StringBuilder referenceStringBuilder= new StringBuilder();
672 StringBuilder listBuffer= new StringBuilder();
673 List<String> constraints= new ArrayList<>();
674 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
675 String keySetString= entry.getKey();
676 HashMap<String,String> keyValues=mapKey.get(keySetString);
677 if(keyValues.get("type").equalsIgnoreCase(STRING)||
678 keyValues.get("type").equalsIgnoreCase(INTEGER)
680 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
681 attributeIndividualStringBuilder.append(keySetString+"=");
682 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
683 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
684 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
685 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
688 else if(keyValues.get("type").equalsIgnoreCase(LIST)){
690 Set<String> keys= keyValues.keySet();
691 Iterator<String> itr=keys.iterator();
692 while(itr.hasNext()){
693 String key= itr.next();
694 if((!("type").equals(key) ||("required").equals(key)))
696 String value= keyValues.get(key);
697 //The "." in the value determines if its a string or a user defined type.
698 if (!value.contains(".")){
700 constraints.add(keyValues.get(key));
702 //This is userdefined string
703 String trimValue=value.substring(value.lastIndexOf('.')+1);
704 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
705 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
706 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
712 //User defined Datatype.
713 String value=keyValues.get("type");
714 String trimValue=value.substring(value.lastIndexOf('.')+1);
715 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
716 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
717 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
720 if(constraints!=null &&constraints.isEmpty()==false){
722 listBuffer.append(keySetString.toUpperCase()+"=[");
723 for(String str:constraints){
724 listBuffer.append(str+",");
726 listBuffer.append("]#");
727 LOGGER.info(listBuffer);
730 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
731 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
732 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
737 dataListBuffer.append(listBuffer);
740 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
741 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
742 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
743 LOGGER.info("List String is:"+listBuffer);
744 LOGGER.info("Data list buffer is:"+dataListBuffer);
745 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
747 this.listConstraints=dataListBuffer.toString();
748 this.referenceAttributes=referenceStringBuilder.toString();
749 this.attributeString=attributeStringBuilder.toString();
754 public void parseTosca (String fileName){
755 Map<String,String> map= new HashMap<>();
760 parseDataAndPolicyNodes(map);
762 HashMap<String,String> dataMapForJson=parseDataNodes(map);
764 constructJsonForDataFields(dataMapForJson);
766 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
768 createAttributes(mapKey);
770 } catch (IOException e) {
776 private String cleanUPJson(String json) {
777 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
778 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
779 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
781 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
782 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
783 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[]{"[", "]"});
794 private JSONObject decodeContent(JsonNode jsonNode){
795 Iterator<JsonNode> jsonElements = jsonNode.elements();
796 Iterator<String> jsonKeys = jsonNode.fieldNames();
797 Map<String,String> element = new TreeMap<>();
798 while(jsonElements.hasNext() && jsonKeys.hasNext()){
799 element.put(jsonKeys.next(), jsonElements.next().toString());
801 JSONObject jsonResult = new JSONObject();
802 JSONArray jsonArray = null;
803 String oldValue = null;
804 String nodeKey = null;
805 String arryKey = null;
806 Boolean isArray = false;
807 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
808 ObjectNode node = nodeFactory.objectNode();
809 String prevKey = null;
810 String presKey = null;
811 for(String key: element.keySet()){
812 if(key.contains(".")){
813 presKey = key.substring(0,key.indexOf("."));
814 }else if(key.contains("@")){
815 presKey = key.substring(0,key.indexOf("@"));
819 // first check if we are different from old.
820 LOGGER.info(key+"\n");
821 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
822 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
823 jsonResult.put(oldValue, jsonArray);
824 jsonArray = new JSONArray();
826 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
827 jsonResult.put(oldValue, jsonArray);
829 jsonArray = new JSONArray();
834 if(key.contains(".")){
836 nodeKey = key.substring(0,key.indexOf("."));
838 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
839 node.put(key.substring(key.indexOf(".")+1), element.get(key));
842 if(nodeKey.contains("@")){
844 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
846 if(nodeKey.endsWith("@0")){
848 jsonArray = new JSONArray();
850 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
851 jsonArray.put(decodeContent(node));
853 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){
854 jsonResult.put(arryKey, jsonArray);
855 jsonArray = new JSONArray();
857 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
860 jsonResult.put(nodeKey, decodeContent(node));
862 node = nodeFactory.objectNode();
864 nodeKey = key.substring(0,key.indexOf("."));
865 if(nodeKey.contains("@")){
866 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
868 node.put(key.substring(key.indexOf(".")+1), element.get(key));
870 }else if(node.size()!=0){
871 if(nodeKey.contains("@")){
873 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
875 if(nodeKey.endsWith("@0")){
877 jsonArray = new JSONArray();
879 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
880 jsonArray.put(decodeContent(node));
882 jsonResult.put(arryKey, jsonArray);
883 jsonArray = new JSONArray();
884 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
887 jsonResult.put(nodeKey, decodeContent(node));
889 node = nodeFactory.objectNode();
890 if(key.contains("@")){
892 if(key.endsWith("@0")|| jsonArray==null){
893 jsonArray = new JSONArray();
895 }else if(!key.contains("@")){
900 oldValue = key.substring(0,key.indexOf("@"));
902 if(oldValue!=prevKey){
903 oldValue = key.substring(0,key.indexOf("@"));
905 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
906 jsonArray.put(element.get(key));
908 jsonResult.put(oldValue, jsonArray);
909 jsonArray = new JSONArray();
911 oldValue = key.substring(0,key.indexOf("@"));
913 jsonResult.put(key, element.get(key));
916 if(key.contains("@")){
918 if(key.endsWith("@0")|| jsonArray==null){
919 jsonArray = new JSONArray();
921 }else if(!key.contains("@")){
926 oldValue = key.substring(0,key.indexOf("@"));
928 if(oldValue!=prevKey){
929 oldValue = key.substring(0,key.indexOf("@"));
931 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
932 jsonArray.put(element.get(key));
934 jsonResult.put(oldValue, jsonArray);
935 jsonArray = new JSONArray();
937 oldValue = key.substring(0,key.indexOf("@"));
939 jsonResult.put(key, element.get(key));
944 if(nodeKey.contains("@")){
946 jsonArray = new JSONArray();
949 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
951 jsonArray.put(decodeContent(node));
952 jsonResult.put(arryKey, jsonArray);
955 jsonResult.put(nodeKey, decodeContent(node));
958 if(isArray && jsonArray.length() > 0){
959 jsonResult.put(oldValue, jsonArray);
964 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
965 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
966 ObjectMapper mapper = new ObjectMapper();
967 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
968 JsonNode root = mapper.readTree(request.getReader());
970 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
971 String servicename = value.toString().split("-v")[0];
972 String version = null;
973 if (value.toString().contains("-v")){
974 version = value.toString().split("-v")[1];
976 MicroServiceModels returnModel = getAttributeObject(servicename, version);
978 String jsonModel = createMicroSeriveJson(returnModel);
980 response.setCharacterEncoding("UTF-8");
981 response.setContentType("application / json");
982 request.setCharacterEncoding("UTF-8");
983 List<Object> list = new ArrayList<>();
984 PrintWriter out = response.getWriter();
985 String responseString = mapper.writeValueAsString(returnModel);
986 JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
988 out.write(list.toString());
992 @SuppressWarnings({ "unchecked", "rawtypes" })
993 private String createMicroSeriveJson(MicroServiceModels returnModel) {
994 Map<String, String> attributeMap = new HashMap<>();
995 Map<String, String> refAttributeMap = new HashMap<>();
996 String attribute = returnModel.getAttributes();
997 if(attribute != null){
998 attribute = attribute.trim();
1000 String refAttribute = returnModel.getRef_attributes();
1001 if(refAttribute != null){
1002 refAttribute = refAttribute.trim();
1004 String enumAttribute = returnModel.getEnumValues();
1005 if(enumAttribute != null){
1006 enumAttribute = enumAttribute.trim();
1008 if (!StringUtils.isEmpty(attribute)){
1009 attributeMap = convert(attribute, ",");
1011 if (!StringUtils.isEmpty(refAttribute)){
1012 refAttributeMap = convert(refAttribute, ",");
1015 Gson gson = new Gson();
1017 String subAttributes = returnModel.getSub_attributes();
1018 if(subAttributes != null){
1019 subAttributes = subAttributes.trim();
1023 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1025 JSONObject object = new JSONObject();
1026 JSONArray array = new JSONArray();
1028 for (Entry<String, String> keySet : attributeMap.entrySet()){
1029 array = new JSONArray();
1030 String value = keySet.getValue();
1031 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1033 object.put(keySet.getKey().trim(), array);
1035 object.put(keySet.getKey().trim(), value.trim());
1039 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
1040 array = new JSONArray();
1041 String value = keySet.getValue().split(":")[0];
1042 if (gsonObject.containsKey(value)){
1043 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1044 array.put(recursiveReference(value, gsonObject, enumAttribute));
1045 object.put(keySet.getKey().trim(), array);
1047 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1050 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1051 array.put(value.trim());
1052 object.put(keySet.getKey().trim(), array);
1054 object.put(keySet.getKey().trim(), value.trim());
1059 return object.toString();
1062 @SuppressWarnings("unchecked")
1063 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
1064 JSONObject object = new JSONObject();
1065 Map<String, String> map = new HashMap<>();
1066 Object returnClass = subAttributeMap.get(name);
1067 map = (Map<String, String>) returnClass;
1068 JSONArray array = new JSONArray();
1070 for( Entry<String, String> m:map.entrySet()){
1071 String[] splitValue = m.getValue().split(":");
1072 array = new JSONArray();
1073 if (subAttributeMap.containsKey(splitValue[0])){
1074 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1075 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1076 object.put(m.getKey().trim(), array);
1078 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1081 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
1082 array.put(splitValue[0].trim());
1083 object.put(m.getKey().trim(), array);
1085 object.put(m.getKey().trim(), splitValue[0].trim());
1094 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1095 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
1096 ObjectMapper mapper = new ObjectMapper();
1097 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1098 JsonNode root = mapper.readTree(request.getReader());
1100 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1101 String servicename = value.toString().split("-v")[0];
1102 Set<String> returnList = getVersionList(servicename);
1104 response.setCharacterEncoding("UTF-8");
1105 response.setContentType("application / json");
1106 request.setCharacterEncoding("UTF-8");
1107 List<Object> list = new ArrayList<>();
1108 PrintWriter out = response.getWriter();
1109 String responseString = mapper.writeValueAsString(returnList);
1110 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1112 out.write(list.toString());
1116 private Set<String> getVersionList(String name) {
1117 MicroServiceModels workingModel = new MicroServiceModels();
1118 Set<String> list = new HashSet<>();
1119 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1120 for (int i = 0; i < microServiceModelsData.size(); i++) {
1121 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1122 if (workingModel.getVersion()!=null){
1123 list.add(workingModel.getVersion());
1125 list.add("Default");
1131 private MicroServiceModels getAttributeObject(String name, String version) {
1132 MicroServiceModels workingModel = new MicroServiceModels();
1133 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1134 for (int i = 0; i < microServiceModelsData.size(); i++) {
1135 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1136 if(version != null){
1137 if (workingModel.getVersion()!=null){
1138 if (workingModel.getVersion().equals(version)){
1139 return workingModel;
1142 return workingModel;
1145 return workingModel;
1149 return workingModel;
1152 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1153 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1155 Map<String, Object> model = new HashMap<>();
1156 ObjectMapper mapper = new ObjectMapper();
1157 List<String> priorityList = new ArrayList<>();
1159 for (int i = 1; i < priorityCount; i++) {
1160 priorityList.add(String.valueOf(i));
1162 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1163 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1164 JSONObject j = new JSONObject(msg);
1165 response.getWriter().write(j.toString());
1167 catch (Exception e){
1172 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1173 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1174 Object policyData = policyAdapter.getPolicyData();
1175 PolicyType policy = (PolicyType) policyData;
1176 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1177 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1178 policyAdapter.setPolicyName(policyNameValue);
1179 String description = "";
1181 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1182 }catch(Exception e){
1183 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
1184 description = policy.getDescription();
1186 policyAdapter.setPolicyDescription(description);
1187 // Get the target data under policy.
1188 TargetType target = policy.getTarget();
1189 if (target != null) {
1190 // Under target we have AnyOFType
1191 List<AnyOfType> anyOfList = target.getAnyOf();
1192 if (anyOfList != null) {
1193 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1194 while (iterAnyOf.hasNext()) {
1195 AnyOfType anyOf = iterAnyOf.next();
1196 // Under AnyOFType we have AllOFType
1197 List<AllOfType> allOfList = anyOf.getAllOf();
1198 if (allOfList != null) {
1199 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1200 while (iterAllOf.hasNext()) {
1201 AllOfType allOf = iterAllOf.next();
1202 // Under AllOFType we have Match
1203 List<MatchType> matchList = allOf.getMatch();
1204 if (matchList != null) {
1205 Iterator<MatchType> iterMatch = matchList.iterator();
1206 while (matchList.size()>1 && iterMatch.hasNext()) {
1207 MatchType match = iterMatch.next();
1209 // Under the match we have attribute value and
1210 // attributeDesignator. So,finally down to the actual attribute.
1212 AttributeValueType attributeValue = match.getAttributeValue();
1213 String value = (String) attributeValue.getContent().get(0);
1214 AttributeDesignatorType designator = match.getAttributeDesignator();
1215 String attributeId = designator.getAttributeId();
1216 // First match in the target is OnapName, so set that value.
1217 if (attributeId.equals("ONAPName")) {
1218 policyAdapter.setOnapName(value);
1220 if (attributeId.equals("ConfigName")){
1221 policyAdapter.setConfigName(value);
1223 if (attributeId.equals("uuid")){
1224 policyAdapter.setUuid(value);
1226 if (attributeId.equals("location")){
1227 policyAdapter.setLocation(value);
1229 if (attributeId.equals("RiskType")){
1230 policyAdapter.setRiskType(value);
1232 if (attributeId.equals("RiskLevel")){
1233 policyAdapter.setRiskLevel(value);
1235 if (attributeId.equals("guard")){
1236 policyAdapter.setGuard(value);
1238 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1239 PolicyController controller = new PolicyController();
1240 String newDate = controller.convertDate(value);
1241 policyAdapter.setTtlDate(newDate);
1244 readFile(policyAdapter, entity);
1254 public static Map<String, String> convert(String str, String split) {
1255 Map<String, String> map = new HashMap<>();
1256 for(final String entry : str.split(split)) {
1257 String[] parts = entry.split("=");
1258 map.put(parts[0], parts[1]);
1264 @SuppressWarnings("unchecked")
1265 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1266 String policyScopeName = null;
1267 ObjectMapper mapper = new ObjectMapper();
1269 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1270 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1271 policyAdapter.setPolicyScope(policyScopeName);
1273 policyAdapter.setPriority(msBody.getPriority());
1275 if (msBody.getVersion()!= null){
1276 policyAdapter.setServiceType(msBody.getService());
1277 policyAdapter.setVersion(msBody.getVersion());
1279 policyAdapter.setServiceType(msBody.getService());
1281 if(msBody.getContent() != null){
1282 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1283 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1284 readRecursivlyJSONContent(map, data);
1285 policyAdapter.setRuleData(data);
1288 } catch (Exception e) {
1294 @SuppressWarnings({ "rawtypes", "unchecked" })
1295 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1296 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1297 Object key = iterator.next();
1298 Object value = map.get(key);
1299 if(value instanceof LinkedHashMap<?, ?>){
1300 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1301 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1302 for(String objKey: secondObjec.keySet()){
1303 data.put(key+"." +objKey, secondObjec.get(objKey));
1305 }else if(value instanceof ArrayList){
1306 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1307 for(int i = 0; i < jsonArrayVal.size(); i++){
1308 Object arrayvalue = jsonArrayVal.get(i);
1309 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1310 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1311 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1312 for(String objKey: newData.keySet()){
1313 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1315 }else if(arrayvalue instanceof ArrayList){
1316 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1317 for(int j = 0; j < jsonArrayVal1.size(); j++){
1318 Object arrayvalue1 = jsonArrayVal1.get(i);
1319 data.put(key+"@"+j, arrayvalue1.toString());
1322 data.put(key+"@"+i, arrayvalue.toString());
1326 data.put(key.toString(), value.toString());
1331 private String getPolicyScope(String value) {
1332 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1333 if(groupList != null && !groupList.isEmpty()){
1334 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1335 return pScope.getGroupName();
1340 //Convert the map values and set into JSON body
1341 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1342 Map<String, String> attribute = new HashMap<>();
1346 for (Entry<String, String> entry : attributesMap.entrySet()) {
1347 key = entry.getKey();
1348 value = entry.getValue();
1349 attribute.put(key, value);
1351 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1352 key = entryRef.getKey();
1353 value = entryRef.getValue().toString();
1354 attribute.put(key, value);
1356 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1357 key = entryList.getKey();
1358 value = entryList.getValue().toString();
1359 attribute.put(key, value);
1361 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1362 key = arrayList.getKey();
1364 for (Object textList : arrayList.getValue()){
1366 temp = "[" + textList;
1368 temp = temp + "," + textList;
1371 attribute.put(key, temp+ "]");
1377 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1378 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
1379 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1380 boolean zip = false;
1382 for (FileItem item : items) {
1383 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1384 this.newModel = new MicroServiceModels();
1386 File file = new File(item.getName());
1387 OutputStream outputStream = new FileOutputStream(file);
1388 IOUtils.copy(item.getInputStream(), outputStream);
1389 outputStream.close();
1390 this.newFile = file.toString();
1391 this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
1393 if (this.newFile.toString().contains("-v")){
1394 if (item.getName().endsWith(".zip")){
1395 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
1397 }else if(item.getName().endsWith(".yml")){
1398 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
1402 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
1406 }catch(Exception e){
1407 LOGGER.error("Upload error : " + e);
1412 List<File> fileList = new ArrayList<>();;
1413 this.directory = "model";
1415 extractFolder(this.newFile);
1416 fileList = listModelFiles(this.directory);
1417 }else if (yml==true){
1418 parseTosca(this.newFile);
1420 File file = new File(this.newFile);
1423 String modelType= "";
1426 //Process Main Model file first
1427 classMap = new HashMap<>();
1428 for (File file : fileList) {
1429 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1430 retreiveDependency(file.toString(), true);
1434 modelList = createList();
1436 cleanUp(this.newFile);
1440 modelList.add(this.newModel.getModelName());
1441 String className=this.newModel.getModelName();
1442 MSAttributeObject msAttributes= new MSAttributeObject();
1443 msAttributes.setClassName(className);
1445 HashMap<String, String> returnAttributeList =new HashMap<>();
1446 returnAttributeList.put(className, this.attributeString);
1447 msAttributes.setAttribute(returnAttributeList);
1449 msAttributes.setSubClass(this.retmap);
1451 HashMap<String, String> returnReferenceList =new HashMap<>();
1452 //String[] referenceArray=this.referenceAttributes.split("=");
1453 returnReferenceList.put(className, this.referenceAttributes);
1454 msAttributes.setRefAttribute(returnReferenceList);
1456 if(this.listConstraints!=""){
1457 HashMap<String, String> enumList =new HashMap<>();
1458 String[] listArray=this.listConstraints.split("#");
1459 for(String str:listArray){
1460 String[] strArr= str.split("=");
1461 if(strArr.length>1){
1462 enumList.put(strArr[0], strArr[1]);
1465 msAttributes.setEnumType(enumList);
1468 classMap=new HashMap<>();
1469 classMap.put(className, msAttributes);
1473 PrintWriter out = response.getWriter();
1475 response.setCharacterEncoding("UTF-8");
1476 response.setContentType("application / json");
1477 request.setCharacterEncoding("UTF-8");
1479 ObjectMapper mapper = new ObjectMapper();
1480 JSONObject j = new JSONObject();
1481 j.put("classListDatas", modelList);
1482 j.put("modelDatas", mapper.writeValueAsString(classMap));
1483 j.put("modelType", modelType);
1484 out.write(j.toString());
1488 * Unzip file and store in the model directory for processing
1490 @SuppressWarnings("rawtypes")
1491 private void extractFolder(String zipFile ) {
1493 File file = new File(zipFile);
1497 zip = new ZipFile(file);
1498 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1499 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1500 checkZipDirectory(this.directory);
1501 new File(newPath).mkdir();
1502 Enumeration zipFileEntries = zip.entries();
1504 // Process each entry
1505 while (zipFileEntries.hasMoreElements()){
1506 // grab a zip file entry
1507 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1508 String currentEntry = entry.getName();
1509 File destFile = new File("model" + File.separator + currentEntry);
1510 File destinationParent = destFile.getParentFile();
1512 destinationParent.mkdirs();
1514 if (!entry.isDirectory()){
1515 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1517 byte data[] = new byte[BUFFER];
1518 FileOutputStream fos = new FileOutputStream(destFile);
1519 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1520 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1521 dest.write(data, 0, currentByte);
1528 if (currentEntry.endsWith(".zip")){
1529 extractFolder(destFile.getAbsolutePath());
1532 } catch (IOException e) {
1533 LOGGER.error("Failed to unzip model file " + zipFile, e);
1538 } catch (IOException e) {
1539 LOGGER.error("Exception Occured While closing zipfile " + e);
1544 private void retreiveDependency(String workingFile, Boolean modelClass) {
1546 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1547 HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
1549 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1551 classMap.putAll(tempMap);
1552 LOGGER.info(tempMap);
1558 private List<File> listModelFiles(String directoryName) {
1559 File directory = new File(directoryName);
1560 List<File> resultList = new ArrayList<>();
1561 File[] fList = directory.listFiles();
1562 for (File file : fList) {
1563 if (file.isFile()) {
1564 resultList.add(file);
1565 } else if (file.isDirectory()) {
1566 dirDependencyList.add(file.getName());
1567 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1573 private void cleanUp(String path) {
1576 FileUtils.forceDelete(new File(path));
1577 } catch (IOException e) {
1578 LOGGER.error("Failed to delete folder " + path, e);
1583 private void checkZipDirectory(String zipDirectory) {
1584 Path path = Paths.get(zipDirectory);
1586 if (Files.exists(path)) {
1587 cleanUp(zipDirectory);
1591 private List<String> createList() {
1592 List<String> list = new ArrayList<>();
1593 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1594 if (cMap.getValue().isPolicyTempalate()){
1595 list.add(cMap.getKey());
1600 if (list.isEmpty()){
1601 if (classMap.containsKey(this.newModel.getModelName())){
1602 list.add(this.newModel.getModelName());
1610 public Map<String, String> getAttributesListRefMap() {
1611 return attributesListRefMap;
1614 public Map<String, LinkedList<String>> getArrayTextList() {
1615 return arrayTextList;
1620 class DCAEMicroServiceObject {
1622 private String service;
1623 private String location;
1624 private String uuid;
1625 private String policyName;
1626 private String description;
1627 private String configName;
1628 private String templateVersion;
1629 private String version;
1630 private String priority;
1631 private String policyScope;
1632 private String riskType;
1633 private String riskLevel;
1634 private String guard = null;
1636 public String getGuard() {
1639 public void setGuard(String guard) {
1642 public String getRiskType() {
1645 public void setRiskType(String riskType) {
1646 this.riskType = riskType;
1648 public String getRiskLevel() {
1651 public void setRiskLevel(String riskLevel) {
1652 this.riskLevel = riskLevel;
1654 public String getPolicyScope() {
1657 public void setPolicyScope(String policyScope) {
1658 this.policyScope = policyScope;
1661 public String getPriority() {
1664 public void setPriority(String priority) {
1665 this.priority = priority;
1667 public String getVersion() {
1670 public void setVersion(String version) {
1671 this.version = version;
1673 private Object content;
1676 public String getPolicyName() {
1679 public void setPolicyName(String policyName) {
1680 this.policyName = policyName;
1682 public String getDescription() {
1685 public void setDescription(String description) {
1686 this.description = description;
1688 public String getConfigName() {
1691 public void setConfigName(String configName) {
1692 this.configName = configName;
1694 public Object getContent() {
1697 public void setContent(Object content) {
1698 this.content = content;
1701 public String getService() {
1704 public void setService(String service) {
1705 this.service = service;
1707 public String getLocation() {
1710 public void setLocation(String location) {
1711 this.location = location;
1714 public String getUuid() {
1717 public void setUuid(String uuid) {
1720 public String getTemplateVersion() {
1721 return templateVersion;
1723 public void setTemplateVersion(String templateVersion) {
1724 this.templateVersion = templateVersion;