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.openecomp.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.nio.file.Files;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Enumeration;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.LinkedHashMap;
44 import java.util.LinkedList;
45 import java.util.List;
47 import java.util.Map.Entry;
49 import java.util.TreeMap;
50 import java.util.zip.ZipEntry;
51 import java.util.zip.ZipFile;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
56 import org.apache.commons.compress.utils.IOUtils;
57 import org.apache.commons.fileupload.FileItem;
58 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
59 import org.apache.commons.fileupload.servlet.ServletFileUpload;
60 import org.apache.commons.io.FileUtils;
61 import org.apache.commons.lang.StringUtils;
62 import org.json.JSONArray;
63 import org.json.JSONObject;
64 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
65 import org.openecomp.policy.common.logging.flexlogger.Logger;
66 import org.openecomp.policy.rest.XACMLRestProperties;
67 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
68 import org.openecomp.policy.rest.dao.CommonClassDao;
69 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
70 import org.openecomp.policy.rest.jpa.MicroServiceModels;
71 import org.openecomp.policy.rest.jpa.PolicyEntity;
72 import org.openecomp.policy.rest.util.MSAttributeObject;
73 import org.openecomp.policy.rest.util.MSModelUtils;
74 import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE;
75 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
76 import org.openecomp.portalsdk.core.web.support.JsonMessage;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.http.MediaType;
79 import org.springframework.stereotype.Controller;
80 import org.springframework.web.bind.annotation.RequestMapping;
81 import org.springframework.web.servlet.ModelAndView;
82 import org.yaml.snakeyaml.Yaml;
84 import com.att.research.xacml.util.XACMLProperties;
85 import com.fasterxml.jackson.core.JsonProcessingException;
86 import com.fasterxml.jackson.databind.DeserializationFeature;
87 import com.fasterxml.jackson.databind.JsonNode;
88 import com.fasterxml.jackson.databind.ObjectMapper;
89 import com.fasterxml.jackson.databind.ObjectWriter;
90 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
91 import com.fasterxml.jackson.databind.node.ObjectNode;
92 import com.google.gson.Gson;
94 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
95 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
96 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
97 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
98 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
99 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
100 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
104 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
105 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
107 private static CommonClassDao commonClassDao;
109 public static CommonClassDao getCommonClassDao() {
110 return commonClassDao;
113 public static void setCommonClassDao(CommonClassDao commonClassDao) {
114 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
117 private MicroServiceModels newModel;
118 private String newFile;
119 private String directory;
120 private List<String> modelList = new ArrayList<>();
121 private List<String> dirDependencyList = new ArrayList<>();
122 private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
123 //Tosca Model related Datastructure.
124 String referenceAttributes;
125 String attributeString;
126 String listConstraints;
127 String subAttributeString;
128 HashMap<String, Object> retmap = new HashMap<>();
129 Set<String> uniqueKeys= new HashSet<>();
130 Set<String> uniqueDataKeys= new HashSet<>();
131 StringBuilder dataListBuffer=new StringBuilder();
132 List<String> dataConstraints= new ArrayList <>();
134 public static final String DATATYPE = "data_types.policy.data.";
135 public static final String PROPERTIES=".properties.";
136 public static final String TYPE=".type";
137 public static final String STRING="string";
138 public static final String INTEGER="integer";
139 public static final String LIST="list";
140 public static final String DEFAULT=".default";
141 public static final String REQUIRED=".required";
142 public static final String MANYFALSE=":MANY-false";
146 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
147 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
150 public CreateDcaeMicroServiceController(){}
152 protected PolicyRestAdapter policyAdapter = null;
153 private int priorityCount;
154 private Map<String, String> attributesListRefMap = new HashMap<>();
155 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
157 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
159 String jsonContent = null;
161 jsonContent = decodeContent(root.get("policyJSON")).toString();
162 constructJson(policyData, jsonContent);
164 LOGGER.error("Error while decoding microservice content", e);
170 private GroupPolicyScopeList getPolicyObject(String policyScope) {
171 GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
175 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent) {
176 ObjectWriter om = new ObjectMapper().writer();
178 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
179 MicroServiceModels returnModel = new MicroServiceModels();
180 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
181 if(policyAdapter.getServiceType() !=null){
182 microServiceObject.setService(policyAdapter.getServiceType());
183 microServiceObject.setVersion(policyAdapter.getVersion());
184 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
186 if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
187 if(policyAdapter.getUuid()!=null){
188 microServiceObject.setUuid(policyAdapter.getUuid());
190 if(policyAdapter.getLocation()!=null){
191 microServiceObject.setLocation(policyAdapter.getLocation());
193 if(policyAdapter.getConfigName()!=null){
194 microServiceObject.setConfigName(policyAdapter.getConfigName());
196 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
197 if(policyScopeValue!=null){
198 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
202 if(policyAdapter.getPolicyName()!=null){
203 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
205 if(policyAdapter.getPolicyDescription()!=null){
206 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
208 if (policyAdapter.getPriority()!=null){
209 microServiceObject.setPriority(policyAdapter.getPriority());
211 microServiceObject.setPriority("9999");
214 if (policyAdapter.getRiskLevel()!=null){
215 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
217 if (policyAdapter.getRiskType()!=null){
218 microServiceObject.setRiskType(policyAdapter.getRiskType());
220 if (policyAdapter.getGuard()!=null){
221 microServiceObject.setGuard(policyAdapter.getGuard());
223 microServiceObject.setContent(jsonContent);
226 json = om.writeValueAsString(microServiceObject);
227 } catch (JsonProcessingException e) {
228 LOGGER.error("Error writing out the object", e);
231 String cleanJson = cleanUPJson(json);
232 cleanJson = removeNullAttributes(cleanJson);
233 policyAdapter.setJsonBody(cleanJson);
234 return policyAdapter;
237 private String removeNullAttributes(String cleanJson) {
238 ObjectMapper mapper = new ObjectMapper();
241 JsonNode rootNode = mapper.readTree(cleanJson);
242 JsonNode returnNode = mapper.readTree(cleanJson);
243 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
244 boolean remove = false;
245 while (fieldsIterator.hasNext()) {
246 Map.Entry<String, JsonNode> field = fieldsIterator.next();
247 final String key = field.getKey();
248 final JsonNode value = field.getValue();
249 if (value==null || value.isNull()){
250 ((ObjectNode) returnNode).remove(key);
255 cleanJson = returnNode.toString();
257 } catch (IOException e) {
258 LOGGER.error("Error writing out the JsonNode",e);
263 // Second index of dot should be returned.
264 public int stringBetweenDots(String str){
265 String stringToSearch=str;
266 String[]ss=stringToSearch.split("\\.");
270 uniqueKeys.add(ss[2]);
274 return uniqueKeys.size();
277 public void stringBetweenDotsForDataFields(String str){
278 String stringToSearch=str;
279 String[]ss=stringToSearch.split("\\.");
284 uniqueDataKeys.add(ss[0]+"%"+ss[2]);
290 public Map<String, String> load(String fileName) throws IOException {
291 File newConfiguration = new File(fileName);
292 InputStream is = null;
294 is = new FileInputStream(newConfiguration);
295 } catch (FileNotFoundException e) {
299 Yaml yaml = new Yaml();
300 @SuppressWarnings("unchecked")
301 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is);
302 StringBuilder sb = new StringBuilder();
303 Map<String, String> settings = new HashMap<>();
304 if (yamlMap == null) {
307 List<String> path = new ArrayList <>();
308 serializeMap(settings, sb, path, yamlMap);
312 public Map<String, String> load(byte[] source) throws IOException {
313 Yaml yaml = new Yaml();
314 @SuppressWarnings("unchecked")
315 Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
316 StringBuilder sb = new StringBuilder();
317 Map<String, String> settings = new HashMap <>();
318 if (yamlMap == null) {
321 List<String> path = new ArrayList <>();
322 serializeMap(settings, sb, path, yamlMap);
326 @SuppressWarnings({ "unchecked", "rawtypes" })
327 private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
328 for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
329 if (entry.getValue() instanceof Map) {
330 path.add((String) entry.getKey());
331 serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
332 path.remove(path.size() - 1);
333 } else if (entry.getValue() instanceof List) {
334 path.add((String) entry.getKey());
335 serializeList(settings, sb, path, (List) entry.getValue());
336 path.remove(path.size() - 1);
338 serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
343 @SuppressWarnings("unchecked")
344 private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
346 for (Object listEle : yamlList) {
347 if (listEle instanceof Map) {
348 path.add(Integer.toString(counter));
349 serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
350 path.remove(path.size() - 1);
351 } else if (listEle instanceof List) {
352 path.add(Integer.toString(counter));
353 serializeList(settings, sb, path, (List<String>) listEle);
354 path.remove(path.size() - 1);
356 serializeValue(settings, sb, path, Integer.toString(counter), listEle);
362 private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
367 for (String pathEle : path) {
368 sb.append(pathEle).append('.');
371 settings.put(sb.toString(), value.toString());
374 void parseDataAndPolicyNodes(Map<String,String> map){
375 for(String key:map.keySet()){
376 if(key.contains("policy.nodes.Root"))
380 else if(key.contains("policy.nodes")){
381 String wordToFind = "policy.nodes.";
382 int indexForPolicyNode=key.indexOf(wordToFind);
383 String subNodeString= key.substring(indexForPolicyNode+13, key.length());
385 stringBetweenDots(subNodeString);
387 else if(key.contains("policy.data")){
388 String wordToFind="policy.data.";
389 int indexForPolicyNode=key.indexOf(wordToFind);
390 String subNodeString= key.substring(indexForPolicyNode+12, key.length());
392 stringBetweenDotsForDataFields(subNodeString);
397 HashMap<String,String> parseDataNodes(Map<String,String> map){
398 HashMap<String,String> dataMapForJson=new HashMap <>();
399 for(String uniqueDataKey: uniqueDataKeys){
400 if(uniqueDataKey.contains("%")){
401 String[] uniqueDataKeySplit= uniqueDataKey.split("%");
402 String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
403 String typeValue=map.get(findType);
404 LOGGER.info(typeValue);
405 if(typeValue.equalsIgnoreCase(STRING)||
406 typeValue.equalsIgnoreCase(INTEGER)
409 String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
410 String defaultValue= map.get(findDefault);
411 LOGGER.info("defaultValue is:"+ defaultValue);
413 String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
414 String requiredValue= map.get(findRequired);
415 LOGGER.info("requiredValue is:"+ requiredValue);
417 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
418 attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
419 attributeIndividualStringBuilder.append(defaultValue+":required-");
420 attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
421 dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
423 else if(typeValue.equalsIgnoreCase(LIST)){
424 String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
425 String listValue=map.get(findList);
427 LOGGER.info("Type of list is:"+ listValue);
429 if(listValue.contains(".")){
430 String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
431 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
432 referenceIndividualStringBuilder.append(trimValue+":MANY-true");
433 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
436 StringBuilder stringListItems= new StringBuilder();
437 stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
438 dataMapForJson.put(uniqueDataKey, stringListItems.toString());
439 dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
440 for(int i=0;i<10;i++){
441 String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
442 String constraintsValue=map.get(findConstraints);
443 LOGGER.info(constraintsValue);
444 if(constraintsValue==null){
448 dataConstraints.add(constraintsValue);
449 dataListBuffer.append(constraintsValue+",");
452 dataListBuffer.append("]#");
454 LOGGER.info(dataListBuffer);
459 String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
460 String userDefinedValue=map.get(findUserDefined);
461 String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
462 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
463 referenceIndividualStringBuilder.append(trimValue+":MANY-false");
464 dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
469 return dataMapForJson;
472 void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
473 HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
474 HashMap<String,String> hmSub;
475 for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
476 String uniqueDataKey= entry.getKey();
477 String[] uniqueDataKeySplit=uniqueDataKey.split("%");
478 String value= dataMapForJson.get(uniqueDataKey);
479 if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
480 hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
481 hmSub.put(uniqueDataKeySplit[1], value);
484 hmSub=new HashMap <>();
485 hmSub.put(uniqueDataKeySplit[1], value);
488 dataMapKey.put(uniqueDataKeySplit[0], hmSub);
491 JSONObject mainObject= new JSONObject();
493 for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
494 String s=entry.getKey();
495 json= new JSONObject();
496 HashMap<String,String> jsonHm=dataMapKey.get(s);
497 for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
498 String key=entryMap.getKey();
499 json.put(key, jsonHm.get(key));
501 mainObject.put(s,json);
503 Iterator<String> keysItr = mainObject.keys();
504 while(keysItr.hasNext()) {
505 String key = keysItr.next();
506 String value = mainObject.get(key).toString();
507 retmap.put(key, value);
510 LOGGER.info("#############################################################################");
511 LOGGER.info(mainObject);
512 LOGGER.info("###############################################################################");
516 HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
517 HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
518 for(String uniqueKey: uniqueKeys){
519 HashMap<String,String> hm;
521 for(Map.Entry<String,String> entry:map.entrySet()){
522 String key=entry.getKey();
523 if(key.contains(uniqueKey) && key.contains("policy.nodes")){
524 if(mapKey.containsKey(uniqueKey)){
525 hm = mapKey.get(uniqueKey);
526 String keyStr= key.substring(key.lastIndexOf('.')+1);
527 String valueStr= map.get(key);
528 if(("type").equals(keyStr)){
529 if(!key.contains("entry_schema"))
531 hm.put(keyStr,valueStr);
534 hm.put(keyStr,valueStr);
538 hm = new HashMap <>();
539 String keyStr= key.substring(key.lastIndexOf('.')+1);
540 String valueStr= map.get(key);
541 if(("type").equals(keyStr)){
542 if(!key.contains("entry_schema"))
544 hm.put(keyStr,valueStr);
547 hm.put(keyStr,valueStr);
549 mapKey.put(uniqueKey, hm);
557 void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
558 StringBuilder attributeStringBuilder= new StringBuilder();
559 StringBuilder referenceStringBuilder= new StringBuilder();
560 StringBuilder listBuffer= new StringBuilder();
561 List<String> constraints= new ArrayList<>();
562 for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
563 String keySetString= entry.getKey();
564 HashMap<String,String> keyValues=mapKey.get(keySetString);
565 if(keyValues.get("type").equalsIgnoreCase(STRING)||
566 keyValues.get("type").equalsIgnoreCase(INTEGER)
568 StringBuilder attributeIndividualStringBuilder= new StringBuilder();
569 attributeIndividualStringBuilder.append(keySetString+"=");
570 attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
571 attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
572 attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
573 attributeStringBuilder.append(attributeIndividualStringBuilder+",");
576 else if(keyValues.get("type").equalsIgnoreCase(LIST)){
578 Set<String> keys= keyValues.keySet();
579 Iterator<String> itr=keys.iterator();
580 while(itr.hasNext()){
581 String key= itr.next();
582 if((!("type").equals(key) ||("required").equals(key)))
584 String value= keyValues.get(key);
585 //The "." in the value determines if its a string or a user defined type.
586 if (!value.contains(".")){
588 constraints.add(keyValues.get(key));
590 //This is userdefined string
591 String trimValue=value.substring(value.lastIndexOf('.')+1);
592 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
593 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
594 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
600 //User defined Datatype.
601 String value=keyValues.get("type");
602 String trimValue=value.substring(value.lastIndexOf('.')+1);
603 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
604 referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
605 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
608 if(constraints!=null &&constraints.isEmpty()==false){
610 listBuffer.append(keySetString.toUpperCase()+"=[");
611 for(String str:constraints){
612 listBuffer.append(str+",");
614 listBuffer.append("]#");
615 LOGGER.info(listBuffer);
618 StringBuilder referenceIndividualStringBuilder= new StringBuilder();
619 referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
620 referenceStringBuilder.append(referenceIndividualStringBuilder+",");
625 dataListBuffer.append(listBuffer);
628 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
629 LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
630 LOGGER.info("Whole reference String is:"+referenceStringBuilder);
631 LOGGER.info("List String is:"+listBuffer);
632 LOGGER.info("Data list buffer is:"+dataListBuffer);
633 LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
635 this.listConstraints=dataListBuffer.toString();
636 this.referenceAttributes=referenceStringBuilder.toString();
637 this.attributeString=attributeStringBuilder.toString();
642 public void parseTosca (String fileName){
643 Map<String,String> map= new HashMap<>();
648 parseDataAndPolicyNodes(map);
650 HashMap<String,String> dataMapForJson=parseDataNodes(map);
652 constructJsonForDataFields(dataMapForJson);
654 HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
656 createAttributes(mapKey);
658 } catch (IOException e) {
664 private String cleanUPJson(String json) {
665 String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
666 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
667 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
669 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
670 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
671 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
672 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
673 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
674 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
675 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
676 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
677 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
678 cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
682 private JSONObject decodeContent(JsonNode jsonNode){
683 Iterator<JsonNode> jsonElements = jsonNode.elements();
684 Iterator<String> jsonKeys = jsonNode.fieldNames();
685 Map<String,String> element = new TreeMap<>();
686 while(jsonElements.hasNext() && jsonKeys.hasNext()){
687 element.put(jsonKeys.next(), jsonElements.next().toString());
689 JSONObject jsonResult = new JSONObject();
690 JSONArray jsonArray = null;
691 String oldValue = null;
692 String nodeKey = null;
693 String arryKey = null;
694 Boolean isArray = false;
695 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
696 ObjectNode node = nodeFactory.objectNode();
697 String prevKey = null;
698 String presKey = null;
699 for(String key: element.keySet()){
700 if(key.contains(".")){
701 presKey = key.substring(0,key.indexOf("."));
702 }else if(key.contains("@")){
703 presKey = key.substring(0,key.indexOf("@"));
707 // first check if we are different from old.
708 LOGGER.info(key+"\n");
709 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
710 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
711 jsonResult.put(oldValue, jsonArray);
712 jsonArray = new JSONArray();
714 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
715 jsonResult.put(oldValue, jsonArray);
717 jsonArray = new JSONArray();
722 if(key.contains(".")){
724 nodeKey = key.substring(0,key.indexOf("."));
726 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
727 node.put(key.substring(key.indexOf(".")+1), element.get(key));
730 if(nodeKey.contains("@")){
732 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
734 if(nodeKey.endsWith("@0")){
736 jsonArray = new JSONArray();
738 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
739 jsonArray.put(decodeContent(node));
741 if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){
742 jsonResult.put(arryKey, jsonArray);
743 jsonArray = new JSONArray();
745 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
748 jsonResult.put(nodeKey, decodeContent(node));
750 node = nodeFactory.objectNode();
752 nodeKey = key.substring(0,key.indexOf("."));
753 if(nodeKey.contains("@")){
754 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
756 node.put(key.substring(key.indexOf(".")+1), element.get(key));
758 }else if(node.size()!=0){
759 if(nodeKey.contains("@")){
761 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
763 if(nodeKey.endsWith("@0")){
765 jsonArray = new JSONArray();
767 if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
768 jsonArray.put(decodeContent(node));
770 jsonResult.put(arryKey, jsonArray);
771 jsonArray = new JSONArray();
772 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
775 jsonResult.put(nodeKey, decodeContent(node));
777 node = nodeFactory.objectNode();
778 if(key.contains("@")){
780 if(key.endsWith("@0")|| jsonArray==null){
781 jsonArray = new JSONArray();
783 }else if(!key.contains("@")){
788 oldValue = key.substring(0,key.indexOf("@"));
790 if(oldValue!=prevKey){
791 oldValue = key.substring(0,key.indexOf("@"));
793 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
794 jsonArray.put(element.get(key));
796 jsonResult.put(oldValue, jsonArray);
797 jsonArray = new JSONArray();
799 oldValue = key.substring(0,key.indexOf("@"));
801 jsonResult.put(key, element.get(key));
804 if(key.contains("@")){
806 if(key.endsWith("@0")|| jsonArray==null){
807 jsonArray = new JSONArray();
809 }else if(!key.contains("@")){
814 oldValue = key.substring(0,key.indexOf("@"));
816 if(oldValue!=prevKey){
817 oldValue = key.substring(0,key.indexOf("@"));
819 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
820 jsonArray.put(element.get(key));
822 jsonResult.put(oldValue, jsonArray);
823 jsonArray = new JSONArray();
825 oldValue = key.substring(0,key.indexOf("@"));
827 jsonResult.put(key, element.get(key));
832 if(nodeKey.contains("@")){
834 jsonArray = new JSONArray();
837 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
839 jsonArray.put(decodeContent(node));
840 jsonResult.put(arryKey, jsonArray);
843 jsonResult.put(nodeKey, decodeContent(node));
846 if(isArray && jsonArray.length() > 0){
847 jsonResult.put(oldValue, jsonArray);
852 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
853 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{
854 ObjectMapper mapper = new ObjectMapper();
855 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
856 JsonNode root = mapper.readTree(request.getReader());
858 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
859 String servicename = value.toString().split("-v")[0];
860 String version = null;
861 if (value.toString().contains("-v")){
862 version = value.toString().split("-v")[1];
864 MicroServiceModels returnModel = getAttributeObject(servicename, version);
866 String jsonModel = createMicroSeriveJson(returnModel);
868 response.setCharacterEncoding("UTF-8");
869 response.setContentType("application / json");
870 request.setCharacterEncoding("UTF-8");
871 List<Object> list = new ArrayList<>();
872 PrintWriter out = response.getWriter();
873 String responseString = mapper.writeValueAsString(returnModel);
874 JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
876 out.write(list.toString());
880 @SuppressWarnings({ "unchecked", "rawtypes" })
881 private String createMicroSeriveJson(MicroServiceModels returnModel) {
882 Map<String, String> attributeMap = new HashMap<>();
883 Map<String, String> refAttributeMap = new HashMap<>();
884 String attribute = returnModel.getAttributes();
885 if(attribute != null){
886 attribute = attribute.trim();
888 String refAttribute = returnModel.getRef_attributes();
889 if(refAttribute != null){
890 refAttribute = refAttribute.trim();
892 String enumAttribute = returnModel.getEnumValues();
893 if(enumAttribute != null){
894 enumAttribute = enumAttribute.trim();
896 if (!StringUtils.isEmpty(attribute)){
897 attributeMap = convert(attribute, ",");
899 if (!StringUtils.isEmpty(refAttribute)){
900 refAttributeMap = convert(refAttribute, ",");
903 Gson gson = new Gson();
905 String subAttributes = returnModel.getSub_attributes();
906 if(subAttributes != null){
907 subAttributes = subAttributes.trim();
911 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
913 JSONObject object = new JSONObject();
914 JSONArray array = new JSONArray();
916 for (Entry<String, String> keySet : attributeMap.entrySet()){
917 array = new JSONArray();
918 String value = keySet.getValue();
919 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
921 object.put(keySet.getKey().trim(), array);
923 object.put(keySet.getKey().trim(), value.trim());
927 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
928 array = new JSONArray();
929 String value = keySet.getValue().split(":")[0];
930 if (gsonObject.containsKey(value)){
931 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
932 array.put(recursiveReference(value, gsonObject, enumAttribute));
933 object.put(keySet.getKey().trim(), array);
935 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
938 if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
939 array.put(value.trim());
940 object.put(keySet.getKey().trim(), array);
942 object.put(keySet.getKey().trim(), value.trim());
947 return object.toString();
950 @SuppressWarnings("unchecked")
951 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
952 JSONObject object = new JSONObject();
953 Map<String, String> map = new HashMap<>();
954 Object returnClass = subAttributeMap.get(name);
955 map = (Map<String, String>) returnClass;
956 JSONArray array = new JSONArray();
958 for( Entry<String, String> m:map.entrySet()){
959 String[] splitValue = m.getValue().split(":");
960 array = new JSONArray();
961 if (subAttributeMap.containsKey(splitValue[0])){
962 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
963 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
964 object.put(m.getKey().trim(), array);
966 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
969 if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
970 array.put(splitValue[0].trim());
971 object.put(m.getKey().trim(), array);
973 object.put(m.getKey().trim(), splitValue[0].trim());
982 @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
983 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws Exception{
984 ObjectMapper mapper = new ObjectMapper();
985 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
986 JsonNode root = mapper.readTree(request.getReader());
988 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
989 String servicename = value.toString().split("-v")[0];
990 Set<String> returnList = getVersionList(servicename);
992 response.setCharacterEncoding("UTF-8");
993 response.setContentType("application / json");
994 request.setCharacterEncoding("UTF-8");
995 List<Object> list = new ArrayList<>();
996 PrintWriter out = response.getWriter();
997 String responseString = mapper.writeValueAsString(returnList);
998 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
1000 out.write(list.toString());
1004 private Set<String> getVersionList(String name) {
1005 MicroServiceModels workingModel = new MicroServiceModels();
1006 Set<String> list = new HashSet<>();
1007 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1008 for (int i = 0; i < microServiceModelsData.size(); i++) {
1009 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1010 if (workingModel.getVersion()!=null){
1011 list.add(workingModel.getVersion());
1013 list.add("Default");
1019 private MicroServiceModels getAttributeObject(String name, String version) {
1020 MicroServiceModels workingModel = new MicroServiceModels();
1021 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1022 for (int i = 0; i < microServiceModelsData.size(); i++) {
1023 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1024 if(version != null){
1025 if (workingModel.getVersion()!=null){
1026 if (workingModel.getVersion().equals(version)){
1027 return workingModel;
1030 return workingModel;
1033 return workingModel;
1037 return workingModel;
1040 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
1041 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
1043 Map<String, Object> model = new HashMap<>();
1044 ObjectMapper mapper = new ObjectMapper();
1045 List<String> priorityList = new ArrayList<>();
1047 for (int i = 1; i < priorityCount; i++) {
1048 priorityList.add(String.valueOf(i));
1050 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1051 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1052 JSONObject j = new JSONObject(msg);
1053 response.getWriter().write(j.toString());
1055 catch (Exception e){
1060 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1061 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1062 Object policyData = policyAdapter.getPolicyData();
1063 PolicyType policy = (PolicyType) policyData;
1064 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1065 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
1066 policyAdapter.setPolicyName(policyNameValue);
1067 String description = "";
1069 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1070 }catch(Exception e){
1071 description = policy.getDescription();
1073 policyAdapter.setPolicyDescription(description);
1074 // Get the target data under policy.
1075 TargetType target = policy.getTarget();
1076 if (target != null) {
1077 // Under target we have AnyOFType
1078 List<AnyOfType> anyOfList = target.getAnyOf();
1079 if (anyOfList != null) {
1080 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1081 while (iterAnyOf.hasNext()) {
1082 AnyOfType anyOf = iterAnyOf.next();
1083 // Under AnyOFType we have AllOFType
1084 List<AllOfType> allOfList = anyOf.getAllOf();
1085 if (allOfList != null) {
1086 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1087 while (iterAllOf.hasNext()) {
1088 AllOfType allOf = iterAllOf.next();
1089 // Under AllOFType we have Match
1090 List<MatchType> matchList = allOf.getMatch();
1091 if (matchList != null) {
1092 Iterator<MatchType> iterMatch = matchList.iterator();
1093 while (matchList.size()>1 && iterMatch.hasNext()) {
1094 MatchType match = iterMatch.next();
1096 // Under the match we have attribute value and
1097 // attributeDesignator. So,finally down to the actual attribute.
1099 AttributeValueType attributeValue = match.getAttributeValue();
1100 String value = (String) attributeValue.getContent().get(0);
1101 AttributeDesignatorType designator = match.getAttributeDesignator();
1102 String attributeId = designator.getAttributeId();
1103 // First match in the target is EcompName, so set that value.
1104 if (attributeId.equals("ECOMPName")) {
1105 policyAdapter.setEcompName(value);
1107 if (attributeId.equals("ConfigName")){
1108 policyAdapter.setConfigName(value);
1110 if (attributeId.equals("uuid")){
1111 policyAdapter.setUuid(value);
1113 if (attributeId.equals("location")){
1114 policyAdapter.setLocation(value);
1116 if (attributeId.equals("RiskType")){
1117 policyAdapter.setRiskType(value);
1119 if (attributeId.equals("RiskLevel")){
1120 policyAdapter.setRiskLevel(value);
1122 if (attributeId.equals("guard")){
1123 policyAdapter.setGuard(value);
1125 if (attributeId.equals("TTLDate") && !value.contains("NA")){
1126 String newDate = convertDate(value, true);
1127 policyAdapter.setTtlDate(newDate);
1130 readFile(policyAdapter, entity);
1140 private String convertDate(String dateTTL, boolean portalType) {
1141 String formateDate = null;
1142 String[] date = dateTTL.split("T");
1143 String[] parts = date[0].split("-");
1145 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
1149 public static Map<String, String> convert(String str, String split) {
1150 Map<String, String> map = new HashMap<>();
1151 for(final String entry : str.split(split)) {
1152 String[] parts = entry.split("=");
1153 map.put(parts[0], parts[1]);
1159 @SuppressWarnings("unchecked")
1160 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1161 String policyScopeName = null;
1162 ObjectMapper mapper = new ObjectMapper();
1164 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1165 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1166 policyAdapter.setPolicyScope(policyScopeName);
1168 policyAdapter.setPriority(msBody.getPriority());
1170 if (msBody.getVersion()!= null){
1171 policyAdapter.setServiceType(msBody.getService());
1172 policyAdapter.setVersion(msBody.getVersion());
1174 policyAdapter.setServiceType(msBody.getService());
1176 if(msBody.getContent() != null){
1177 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1178 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1179 readRecursivlyJSONContent(map, data);
1180 policyAdapter.setRuleData(data);
1183 } catch (Exception e) {
1189 @SuppressWarnings({ "rawtypes", "unchecked" })
1190 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
1191 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1192 Object key = iterator.next();
1193 Object value = map.get(key);
1194 if(value instanceof LinkedHashMap<?, ?>){
1195 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1196 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1197 for(String objKey: secondObjec.keySet()){
1198 data.put(key+"." +objKey, secondObjec.get(objKey));
1200 }else if(value instanceof ArrayList){
1201 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
1202 for(int i = 0; i < jsonArrayVal.size(); i++){
1203 Object arrayvalue = jsonArrayVal.get(i);
1204 if(arrayvalue instanceof LinkedHashMap<?, ?>){
1205 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1206 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1207 for(String objKey: newData.keySet()){
1208 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
1210 }else if(arrayvalue instanceof ArrayList){
1211 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
1212 for(int j = 0; j < jsonArrayVal1.size(); j++){
1213 Object arrayvalue1 = jsonArrayVal1.get(i);
1214 data.put(key+"@"+j, arrayvalue1.toString());
1217 data.put(key+"@"+i, arrayvalue.toString());
1221 data.put(key.toString(), value.toString());
1226 private String getPolicyScope(String value) {
1227 List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1228 if(groupList != null && !groupList.isEmpty()){
1229 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1230 return pScope.getGroupName();
1235 //Convert the map values and set into JSON body
1236 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1237 Map<String, String> attribute = new HashMap<>();
1241 for (Entry<String, String> entry : attributesMap.entrySet()) {
1242 key = entry.getKey();
1243 value = entry.getValue();
1244 attribute.put(key, value);
1246 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1247 key = entryRef.getKey();
1248 value = entryRef.getValue().toString();
1249 attribute.put(key, value);
1251 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1252 key = entryList.getKey();
1253 value = entryList.getValue().toString();
1254 attribute.put(key, value);
1256 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
1257 key = arrayList.getKey();
1259 for (Object textList : arrayList.getValue()){
1261 temp = "[" + textList;
1263 temp = temp + "," + textList;
1266 attribute.put(key, temp+ "]");
1272 @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
1273 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{
1274 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1275 boolean zip = false;
1277 for (FileItem item : items) {
1278 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
1279 this.newModel = new MicroServiceModels();
1281 File file = new File(item.getName());
1282 OutputStream outputStream = new FileOutputStream(file);
1283 IOUtils.copy(item.getInputStream(), outputStream);
1284 outputStream.close();
1285 this.newFile = file.toString();
1286 this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
1288 if (this.newFile.toString().contains("-v")){
1289 if (item.getName().endsWith(".zip")){
1290 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
1292 }else if(item.getName().endsWith(".yml")){
1293 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
1297 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
1301 }catch(Exception e){
1302 LOGGER.error("Upload error : " + e);
1307 List<File> fileList = new ArrayList<>();;
1308 this.directory = "model";
1310 extractFolder(this.newFile);
1311 fileList = listModelFiles(this.directory);
1312 }else if (yml==true){
1313 parseTosca(this.newFile);
1315 File file = new File(this.newFile);
1318 String modelType= "";
1321 //Process Main Model file first
1322 classMap = new HashMap<>();
1323 for (File file : fileList) {
1324 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
1325 retreiveDependency(file.toString(), true);
1329 modelList = createList();
1331 cleanUp(this.newFile);
1335 modelList.add(this.newModel.getModelName());
1336 String className=this.newModel.getModelName();
1337 MSAttributeObject msAttributes= new MSAttributeObject();
1338 msAttributes.setClassName(className);
1340 HashMap<String, String> returnAttributeList =new HashMap<>();
1341 returnAttributeList.put(className, this.attributeString);
1342 msAttributes.setAttribute(returnAttributeList);
1344 msAttributes.setSubClass(this.retmap);
1346 HashMap<String, String> returnReferenceList =new HashMap<>();
1347 //String[] referenceArray=this.referenceAttributes.split("=");
1348 returnReferenceList.put(className, this.referenceAttributes);
1349 msAttributes.setRefAttribute(returnReferenceList);
1351 if(this.listConstraints!=""){
1352 HashMap<String, String> enumList =new HashMap<>();
1353 String[] listArray=this.listConstraints.split("#");
1354 for(String str:listArray){
1355 String[] strArr= str.split("=");
1356 if(strArr.length>1){
1357 enumList.put(strArr[0], strArr[1]);
1360 msAttributes.setEnumType(enumList);
1363 classMap=new HashMap<>();
1364 classMap.put(className, msAttributes);
1368 PrintWriter out = response.getWriter();
1370 response.setCharacterEncoding("UTF-8");
1371 response.setContentType("application / json");
1372 request.setCharacterEncoding("UTF-8");
1374 ObjectMapper mapper = new ObjectMapper();
1375 JSONObject j = new JSONObject();
1376 j.put("classListDatas", modelList);
1377 j.put("modelDatas", mapper.writeValueAsString(classMap));
1378 j.put("modelType", modelType);
1379 out.write(j.toString());
1383 * Unzip file and store in the model directory for processing
1385 @SuppressWarnings("rawtypes")
1386 private void extractFolder(String zipFile ) {
1388 File file = new File(zipFile);
1392 zip = new ZipFile(file);
1393 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1394 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1395 checkZipDirectory(this.directory);
1396 new File(newPath).mkdir();
1397 Enumeration zipFileEntries = zip.entries();
1399 // Process each entry
1400 while (zipFileEntries.hasMoreElements()){
1401 // grab a zip file entry
1402 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1403 String currentEntry = entry.getName();
1404 File destFile = new File("model" + File.separator + currentEntry);
1405 File destinationParent = destFile.getParentFile();
1407 destinationParent.mkdirs();
1409 if (!entry.isDirectory()){
1410 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1412 byte data[] = new byte[BUFFER];
1413 FileOutputStream fos = new FileOutputStream(destFile);
1414 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
1415 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1416 dest.write(data, 0, currentByte);
1423 if (currentEntry.endsWith(".zip")){
1424 extractFolder(destFile.getAbsolutePath());
1427 } catch (IOException e) {
1428 LOGGER.error("Failed to unzip model file " + zipFile);
1433 } catch (IOException e) {
1434 LOGGER.error("Exception Occured While closing zipfile " + e);
1439 private void retreiveDependency(String workingFile, Boolean modelClass) {
1441 MSModelUtils utils = new MSModelUtils(PolicyController.getMsEcompName(), PolicyController.getMsPolicyName());
1442 HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
1444 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1446 classMap.putAll(tempMap);
1447 LOGGER.info(tempMap);
1453 private List<File> listModelFiles(String directoryName) {
1454 File directory = new File(directoryName);
1455 List<File> resultList = new ArrayList<>();
1456 File[] fList = directory.listFiles();
1457 for (File file : fList) {
1458 if (file.isFile()) {
1459 resultList.add(file);
1460 } else if (file.isDirectory()) {
1461 dirDependencyList.add(file.getName());
1462 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1468 private void cleanUp(String path) {
1471 FileUtils.forceDelete(new File(path));
1472 } catch (IOException e) {
1473 LOGGER.error("Failed to delete folder " + path);
1478 private void checkZipDirectory(String zipDirectory) {
1479 Path path = Paths.get(zipDirectory);
1481 if (Files.exists(path)) {
1482 cleanUp(zipDirectory);
1486 private List<String> createList() {
1487 List<String> list = new ArrayList<>();
1488 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
1489 if (cMap.getValue().isPolicyTempalate()){
1490 list.add(cMap.getKey());
1495 if (list.isEmpty()){
1496 if (classMap.containsKey(this.newModel.getModelName())){
1497 list.add(this.newModel.getModelName());
1505 public Map<String, String> getAttributesListRefMap() {
1506 return attributesListRefMap;
1509 public Map<String, LinkedList<String>> getArrayTextList() {
1510 return arrayTextList;
1515 class DCAEMicroServiceObject {
1517 private String service;
1518 private String location;
1519 private String uuid;
1520 private String policyName;
1521 private String description;
1522 private String configName;
1523 private String templateVersion;
1524 private String version;
1525 private String priority;
1526 private String policyScope;
1527 private String riskType;
1528 private String riskLevel;
1529 private String guard = null;
1531 public String getGuard() {
1534 public void setGuard(String guard) {
1537 public String getRiskType() {
1540 public void setRiskType(String riskType) {
1541 this.riskType = riskType;
1543 public String getRiskLevel() {
1546 public void setRiskLevel(String riskLevel) {
1547 this.riskLevel = riskLevel;
1549 public String getPolicyScope() {
1552 public void setPolicyScope(String policyScope) {
1553 this.policyScope = policyScope;
1556 public String getPriority() {
1559 public void setPriority(String priority) {
1560 this.priority = priority;
1562 public String getVersion() {
1565 public void setVersion(String version) {
1566 this.version = version;
1568 private Object content;
1571 public String getPolicyName() {
1574 public void setPolicyName(String policyName) {
1575 this.policyName = policyName;
1577 public String getDescription() {
1580 public void setDescription(String description) {
1581 this.description = description;
1583 public String getConfigName() {
1586 public void setConfigName(String configName) {
1587 this.configName = configName;
1589 public Object getContent() {
1592 public void setContent(Object content) {
1593 this.content = content;
1596 public String getService() {
1599 public void setService(String service) {
1600 this.service = service;
1602 public String getLocation() {
1605 public void setLocation(String location) {
1606 this.location = location;
1609 public String getUuid() {
1612 public void setUuid(String uuid) {
1615 public String getTemplateVersion() {
1616 return templateVersion;
1618 public void setTemplateVersion(String templateVersion) {
1619 this.templateVersion = templateVersion;