X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=POLICY-SDK-APP%2Fsrc%2Fmain%2Fjava%2Forg%2Fopenecomp%2Fpolicy%2Fcontroller%2FCreateDcaeMicroServiceController.java;h=777fb89e378b8a910a70ce8b57db26844195a5cc;hb=e92ff832cf993db876f22b2d27562fedf59f5043;hp=aeb5266c5d992b7be88a62401c15e0a09a719f98;hpb=dda032f8bb161d54eb1f59de2b4a3efb774fc4d1;p=policy%2Fengine.git diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java index aeb5266c5..777fb89e3 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; @@ -92,6 +93,7 @@ import com.google.gson.Gson; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @@ -100,23 +102,45 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Controller @RequestMapping("/") public class CreateDcaeMicroServiceController extends RestrictedBaseController { - private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + private MicroServiceModels newModel; private String newFile; private String directory; - private List modelList = new ArrayList(); - private List dirDependencyList = new ArrayList(); - private HashMap classMap = new HashMap(); + private List modelList = new ArrayList<>(); + private List dirDependencyList = new ArrayList<>(); + private HashMap classMap = new HashMap<>(); //Tosca Model related Datastructure. String referenceAttributes; String attributeString; String listConstraints; String subAttributeString; - HashMap retmap = new HashMap(); - Set uniqueKeys= new HashSet(); - Set uniqueDataKeys= new HashSet(); + HashMap retmap = new HashMap<>(); + Set uniqueKeys= new HashSet<>(); + Set uniqueDataKeys= new HashSet<>(); + StringBuilder dataListBuffer=new StringBuilder(); + List dataConstraints= new ArrayList <>(); + + public static final String DATATYPE = "data_types.policy.data."; + public static final String PROPERTIES=".properties."; + public static final String TYPE=".type"; + public static final String STRING="string"; + public static final String INTEGER="integer"; + public static final String LIST="list"; + public static final String DEFAULT=".default"; + public static final String REQUIRED=".required"; + public static final String MANYFALSE=":MANY-false"; + @Autowired private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ @@ -127,8 +151,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { protected PolicyRestAdapter policyAdapter = null; private int priorityCount; - private Map attributesListRefMap = new HashMap(); - private Map> arrayTextList = new HashMap>(); + private Map attributesListRefMap = new HashMap<>(); + private Map> arrayTextList = new HashMap<>(); public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { @@ -137,7 +161,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { jsonContent = decodeContent(root.get("policyJSON")).toString(); constructJson(policyData, jsonContent); }catch(Exception e){ - logger.error("Error while decoding microservice content"); + LOGGER.error("Error while decoding microservice content", e); } return policyData; @@ -201,9 +225,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { try { json = om.writeValueAsString(microServiceObject); } catch (JsonProcessingException e) { - logger.error("Error writing out the object"); + LOGGER.error("Error writing out the object", e); } - logger.info(json); + LOGGER.info(json); String cleanJson = cleanUPJson(json); cleanJson = removeNullAttributes(cleanJson); policyAdapter.setJsonBody(cleanJson); @@ -231,13 +255,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { cleanJson = returnNode.toString(); } } catch (IOException e) { - logger.error("Error writing out the JsonNode"); + LOGGER.error("Error writing out the JsonNode",e); } return cleanJson; } // Second index of dot should be returned. - public void stringBetweenDots(String str,String value){ + public int stringBetweenDots(String str){ String stringToSearch=str; String[]ss=stringToSearch.split("\\."); if(ss!=null){ @@ -246,9 +270,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { uniqueKeys.add(ss[2]); } } + + return uniqueKeys.size(); } - public void stringBetweenDotsForDataFields(String str,String value){ + public void stringBetweenDotsForDataFields(String str){ String stringToSearch=str; String[]ss=stringToSearch.split("\\."); if(ss!=null){ @@ -267,18 +293,18 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { try { is = new FileInputStream(newConfiguration); } catch (FileNotFoundException e) { - logger.error(e); + LOGGER.error(e); } Yaml yaml = new Yaml(); @SuppressWarnings("unchecked") Map yamlMap = (Map) yaml.load(is); StringBuilder sb = new StringBuilder(); - Map settings = new HashMap(); + Map settings = new HashMap<>(); if (yamlMap == null) { return settings; } - List path = new ArrayList(); + List path = new ArrayList <>(); serializeMap(settings, sb, path, yamlMap); return settings; } @@ -286,13 +312,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { public Map load(byte[] source) throws IOException { Yaml yaml = new Yaml(); @SuppressWarnings("unchecked") - Map yamlMap = (Map) yaml.load(source.toString()); + Map yamlMap = (Map) yaml.load(Arrays.toString(source)); StringBuilder sb = new StringBuilder(); - Map settings = new HashMap(); + Map settings = new HashMap <>(); if (yamlMap == null) { return settings; } - List path = new ArrayList(); + List path = new ArrayList <>(); serializeMap(settings, sb, path, yamlMap); return settings; } @@ -345,248 +371,294 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { settings.put(sb.toString(), value.toString()); } - - public void parseTosca (String fileName){ - Map map= new HashMap(); - try { - map=load(fileName); - for(String key:map.keySet()){ - if(key.contains("policy.nodes.Root")) - { - continue; - } - else if(key.contains("policy.nodes")){ - String wordToFind = "policy.nodes."; - int indexForPolicyNode=key.indexOf(wordToFind); - String subNodeString= key.substring(indexForPolicyNode+13, key.length()); - - stringBetweenDots(subNodeString,map.get(key)); - } - else if(key.contains("policy.data")){ - String wordToFind="policy.data."; - int indexForPolicyNode=key.indexOf(wordToFind); - String subNodeString= key.substring(indexForPolicyNode+12, key.length()); - - stringBetweenDotsForDataFields(subNodeString,map.get(key)); - Iterator itr= uniqueDataKeys.iterator(); - while(itr.hasNext()){ - logger.info(itr.next()); - } - } + void parseDataAndPolicyNodes(Map map){ + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")) + { + continue; } + else if(key.contains("policy.nodes")){ + String wordToFind = "policy.nodes."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+13, key.length()); - String attributeIndividualString=""; - String userDefinedIndividualString=""; - String referenceIndividualAttributes=""; - - String attributeString=""; - String userDefinedString=""; - String referenceAttributes=""; - String listConstraints=""; + stringBetweenDots(subNodeString); + } + else if(key.contains("policy.data")){ + String wordToFind="policy.data."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+12, key.length()); - for(String uniqueDataKey: uniqueDataKeys){ + stringBetweenDotsForDataFields(subNodeString); + } + } + } + + HashMap parseDataNodes(Map map){ + HashMap dataMapForJson=new HashMap <>(); + for(String uniqueDataKey: uniqueDataKeys){ + if(uniqueDataKey.contains("%")){ String[] uniqueDataKeySplit= uniqueDataKey.split("%"); - userDefinedIndividualString=userDefinedIndividualString+uniqueDataKey+"="; - userDefinedIndividualString=userDefinedIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; - for(String key:map.keySet()){ - if(key.contains("policy.data")){ - String containsKey= uniqueDataKeySplit[1]+".type"; - if(key.contains(uniqueDataKeySplit[0])){ - if(key.contains("default")){ - userDefinedIndividualString=userDefinedIndividualString.replace("#B", map.get(key)); - } - else if(key.contains("required")){ - userDefinedIndividualString=userDefinedIndividualString.replace("#C", map.get(key)); + String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE; + String typeValue=map.get(findType); + LOGGER.info(typeValue); + if(typeValue.equalsIgnoreCase(STRING)|| + typeValue.equalsIgnoreCase(INTEGER) + ) + { + String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT; + String defaultValue= map.get(findDefault); + LOGGER.info("defaultValue is:"+ defaultValue); + + String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED; + String requiredValue= map.get(findRequired); + LOGGER.info("requiredValue is:"+ requiredValue); + + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(typeValue+":defaultValue-"); + attributeIndividualStringBuilder.append(defaultValue+":required-"); + attributeIndividualStringBuilder.append(requiredValue+MANYFALSE); + dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); + } + else if(typeValue.equalsIgnoreCase(LIST)){ + String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type"; + String listValue=map.get(findList); + if(listValue!=null){ + LOGGER.info("Type of list is:"+ listValue); + //Its userdefined + if(listValue.contains(".")){ + String trimValue=listValue.substring(listValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-true"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + }//Its string + else{ + StringBuilder stringListItems= new StringBuilder(); + stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false"); + dataMapForJson.put(uniqueDataKey, stringListItems.toString()); + dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=["); + for(int i=0;i<10;i++){ + String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i; + String constraintsValue=map.get(findConstraints); + LOGGER.info(constraintsValue); + if(constraintsValue==null){ + break; + } + else{ + dataConstraints.add(constraintsValue); + dataListBuffer.append(constraintsValue+","); + } } - else if(key.contains(containsKey)){ - String typeValue= map.get(key); - userDefinedIndividualString=userDefinedIndividualString.replace("#A", typeValue); - } + dataListBuffer.append("]#"); + + LOGGER.info(dataListBuffer); } } - - } - if(userDefinedString!=""){ - userDefinedString=userDefinedString+","+userDefinedIndividualString; - }else{ - userDefinedString=userDefinedString+userDefinedIndividualString; } - userDefinedIndividualString=""; - } - logger.info("userDefinedString :"+userDefinedString); - - HashMap> mapKey= new HashMap>(); - String secondPartString=""; - String firstPartString=""; - for(String value: userDefinedString.split(",")){ - String[] splitWithEquals= value.split("="); - secondPartString=splitWithEquals[0].substring(splitWithEquals[0].indexOf("%")+1); - firstPartString=splitWithEquals[0].substring(0, splitWithEquals[0].indexOf("%")); - ArrayList list; - if(mapKey.containsKey(firstPartString)){ - list = mapKey.get(firstPartString); - list.add(secondPartString+"<"+splitWithEquals[1]); - } else { - list = new ArrayList(); - list.add(secondPartString+"<"+splitWithEquals[1]); - mapKey.put(firstPartString, list); + else{ + String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type"; + String userDefinedValue=map.get(findUserDefined); + String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-false"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + } } - - JSONObject mainObject= new JSONObject();; - JSONObject json; - for(String s: mapKey.keySet()){ - json= new JSONObject(); - List value=mapKey.get(s); - for(String listValue:value){ - String[] splitValue=listValue.split("<"); - json.put(splitValue[0], splitValue[1]); - } - mainObject.put(s,json); + } + return dataMapForJson; + } + + void constructJsonForDataFields(HashMap dataMapForJson){ + HashMap> dataMapKey= new HashMap <>(); + HashMap hmSub; + for(Map.Entry entry: dataMapForJson.entrySet()){ + String uniqueDataKey= entry.getKey(); + String[] uniqueDataKeySplit=uniqueDataKey.split("%"); + String value= dataMapForJson.get(uniqueDataKey); + if(dataMapKey.containsKey(uniqueDataKeySplit[0])){ + hmSub = dataMapKey.get(uniqueDataKeySplit[0]); + hmSub.put(uniqueDataKeySplit[1], value); } - - logger.info(mainObject); - - Iterator keysItr = mainObject.keys(); - while(keysItr.hasNext()) { - String key = keysItr.next(); - String value = mainObject.get(key).toString(); - retmap.put(key, value); + else{ + hmSub=new HashMap <>(); + hmSub.put(uniqueDataKeySplit[1], value); } - - for(String str:retmap.keySet()){ - logger.info(str+":"+retmap.get(str)); + + dataMapKey.put(uniqueDataKeySplit[0], hmSub); + } + + JSONObject mainObject= new JSONObject(); + JSONObject json; + for(Map.Entry> entry: dataMapKey.entrySet()){ + String s=entry.getKey(); + json= new JSONObject(); + HashMap jsonHm=dataMapKey.get(s); + for(Map.Entry entryMap:jsonHm.entrySet()){ + String key=entryMap.getKey(); + json.put(key, jsonHm.get(key)); } - - String typeValueFromKey=""; - boolean userDefinedDataType=false; - boolean isList=false; - for(String uniqueKey: uniqueKeys){ - List constraints= new ArrayList(); - logger.info("===================="); - attributeIndividualString=attributeIndividualString+uniqueKey+"="; - attributeIndividualString=attributeIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; - - logger.info("UniqueStrings: "+uniqueKey); - for(String key:map.keySet()){ - if(key.contains("policy.nodes.Root")|| - key.contains("policy.data")) - { - continue; - } - else if(key.contains("policy.nodes")){ - if(key.contains(uniqueKey)){ - int p=key.lastIndexOf("."); - String firstLastOccurance=key.substring(0,p); - int p1=firstLastOccurance.lastIndexOf("."); - String secondLastOccurance= firstLastOccurance.substring(p1+1,firstLastOccurance.length()); - if(secondLastOccurance.equals(uniqueKey)){ - String checkTypeString= firstLastOccurance+".type"; - typeValueFromKey= map.get(checkTypeString); - }//Its a list. - else if (key.contains("entry_schema")){ - if(key.contains("constraints")){ - constraints.add(map.get(key)); - } - if(key.contains("type")){ - isList=true; - String value= map.get(key); - if(! (value.contains("string")) || - (value.contains("integer")) || - (value.contains("boolean")) ) - { - if(!key.contains("valid_values")){ - String trimValue=value.substring(value.lastIndexOf(".")+1); - referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-true"; - attributeIndividualString=""; - } - - } - } + mainObject.put(s,json); + } + Iterator keysItr = mainObject.keys(); + while(keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + LOGGER.info("#############################################################################"); + LOGGER.info(mainObject); + LOGGER.info("###############################################################################"); + } + + + HashMap> parsePolicyNodes(Map map){ + HashMap> mapKey= new HashMap <>(); + for(String uniqueKey: uniqueKeys){ + HashMap hm; + + for(Map.Entry entry:map.entrySet()){ + String key=entry.getKey(); + if(key.contains(uniqueKey) && key.contains("policy.nodes")){ + if(mapKey.containsKey(uniqueKey)){ + hm = mapKey.get(uniqueKey); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) + { + hm.put(keyStr,valueStr); } + }else{ + hm.put(keyStr,valueStr); + } - if(!(typeValueFromKey.equals("string")|| - typeValueFromKey.equals("integer") || - typeValueFromKey.equals("boolean"))) + } else { + hm = new HashMap <>(); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) { - if(typeValueFromKey.equals("list")){ - isList=true; - userDefinedDataType=false; - } - else{ - userDefinedDataType=true; - } - } - if(userDefinedDataType==false && isList==false){ - if(key.contains("default")){ - attributeIndividualString=attributeIndividualString.replace("#B", map.get(key)); - } - else if(key.contains("required")){ - attributeIndividualString=attributeIndividualString.replace("#C", map.get(key)); - } - else if(key.contains("type")){ - String typeValue= map.get(key); - attributeIndividualString=attributeIndividualString.replace("#A", typeValue); - } - } - else if(userDefinedDataType==true){ - String checkTypeAndUpdate=key.substring(p+1); - if(checkTypeAndUpdate.equals("type")){ - String value=map.get(key); - String trimValue=value.substring(value.lastIndexOf(".")+1); - referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-false"; - } - attributeIndividualString=""; + hm.put(keyStr,valueStr); } + }else{ + hm.put(keyStr,valueStr); } + mapKey.put(uniqueKey, hm); } } + } + } + return mapKey; + } - if(constraints!=null &&constraints.isEmpty()==false){ - //List handling. - listConstraints=uniqueKey.toUpperCase()+"=["; - isList=true; - for(String str:constraints){ - listConstraints=listConstraints+str+","; - } - listConstraints+="],"; - logger.info(listConstraints); - attributeIndividualString=""; - referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+uniqueKey.toUpperCase()+":MANY-false"; - constraints=null; + void createAttributes(HashMap> mapKey){ + StringBuilder attributeStringBuilder= new StringBuilder(); + StringBuilder referenceStringBuilder= new StringBuilder(); + StringBuilder listBuffer= new StringBuilder(); + List constraints= new ArrayList<>(); + for(Map.Entry> entry: mapKey.entrySet()){ + String keySetString= entry.getKey(); + HashMap keyValues=mapKey.get(keySetString); + if(keyValues.get("type").equalsIgnoreCase(STRING)|| + keyValues.get("type").equalsIgnoreCase(INTEGER) + ){ + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(keySetString+"="); + attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-"); + attributeIndividualStringBuilder.append(keyValues.get("default")+":required-"); + attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false"); + attributeStringBuilder.append(attributeIndividualStringBuilder+","); - } - if(userDefinedDataType==false && isList==false){ - if(attributeString!=""){ - attributeString=attributeString+","+attributeIndividualString; - }else{ - attributeString=attributeString+attributeIndividualString; - } - } - if(isList==true || userDefinedDataType==true){ - if(referenceAttributes!=""){ - referenceAttributes=referenceAttributes+","+referenceIndividualAttributes; - }else{ - referenceAttributes=referenceAttributes+referenceIndividualAttributes; + } + else if(keyValues.get("type").equalsIgnoreCase(LIST)){ + //List Datatype + Set keys= keyValues.keySet(); + Iterator itr=keys.iterator(); + while(itr.hasNext()){ + String key= itr.next(); + if((!("type").equals(key) ||("required").equals(key))) + { + String value= keyValues.get(key); + //The "." in the value determines if its a string or a user defined type. + if (!value.contains(".")){ + //This is string + constraints.add(keyValues.get(key)); + }else{ + //This is userdefined string + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + } } - logger.info("ReferenceAttributes: "+referenceAttributes); } - logger.info("AttributeString: "+ attributeString); - logger.info("ListConstraints is: "+listConstraints); + }else{ + //User defined Datatype. + String value=keyValues.get("type"); + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); - attributeIndividualString=""; - referenceIndividualAttributes=""; - userDefinedDataType=false; - isList=false; + } + if(constraints!=null &&constraints.isEmpty()==false){ + //List handling. + listBuffer.append(keySetString.toUpperCase()+"=["); + for(String str:constraints){ + listBuffer.append(str+","); + } + listBuffer.append("]#"); + LOGGER.info(listBuffer); + + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + constraints.clear(); } - this.listConstraints=listConstraints; - this.referenceAttributes=referenceAttributes; - this.attributeString=attributeString; - } catch (IOException e) { - logger.error(e); } + + dataListBuffer.append(listBuffer); + + + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + LOGGER.info("Whole attribute String is:"+attributeStringBuilder); + LOGGER.info("Whole reference String is:"+referenceStringBuilder); + LOGGER.info("List String is:"+listBuffer); + LOGGER.info("Data list buffer is:"+dataListBuffer); + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + + this.listConstraints=dataListBuffer.toString(); + this.referenceAttributes=referenceStringBuilder.toString(); + this.attributeString=attributeStringBuilder.toString(); + } + + + + public void parseTosca (String fileName){ + Map map= new HashMap<>(); + + try { + map=load(fileName); + + parseDataAndPolicyNodes(map); + + HashMap dataMapForJson=parseDataNodes(map); + + constructJsonForDataFields(dataMapForJson); + + HashMap> mapKey= parsePolicyNodes(map); + + createAttributes(mapKey); + + } catch (IOException e) { + LOGGER.error(e); + } + } private String cleanUPJson(String json) { @@ -610,7 +682,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private JSONObject decodeContent(JsonNode jsonNode){ Iterator jsonElements = jsonNode.elements(); Iterator jsonKeys = jsonNode.fieldNames(); - Map element = new TreeMap(); + Map element = new TreeMap<>(); while(jsonElements.hasNext() && jsonKeys.hasNext()){ element.put(jsonKeys.next(), jsonElements.next().toString()); } @@ -633,7 +705,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { presKey = key; } // first check if we are different from old. - logger.info(key+"\n"); + LOGGER.info(key+"\n"); if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ jsonResult.put(oldValue, jsonArray); @@ -663,13 +735,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { isArray = true; jsonArray = new JSONArray(); } - if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ jsonArray.put(decodeContent(node)); } - if(key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))){ - jsonResult.put(arryKey, jsonArray); - jsonArray = new JSONArray(); - }else if(!key.contains("@")){ + if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){ jsonResult.put(arryKey, jsonArray); jsonArray = new JSONArray(); } @@ -695,7 +764,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { isArray = true; jsonArray = new JSONArray(); } - if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ jsonArray.put(decodeContent(node)); } jsonResult.put(arryKey, jsonArray); @@ -810,8 +879,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { @SuppressWarnings({ "unchecked", "rawtypes" }) private String createMicroSeriveJson(MicroServiceModels returnModel) { - Map attributeMap = new HashMap(); - Map refAttributeMap = new HashMap(); + Map attributeMap = new HashMap<>(); + Map refAttributeMap = new HashMap<>(); String attribute = returnModel.getAttributes(); if(attribute != null){ attribute = attribute.trim(); @@ -881,7 +950,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { @SuppressWarnings("unchecked") private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { JSONObject object = new JSONObject(); - Map map = new HashMap(); + Map map = new HashMap<>(); Object returnClass = subAttributeMap.get(name); map = (Map) returnClass; JSONArray array = new JSONArray(); @@ -934,7 +1003,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private Set getVersionList(String name) { MicroServiceModels workingModel = new MicroServiceModels(); - Set list = new HashSet(); + Set list = new HashSet<>(); List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); for (int i = 0; i < microServiceModelsData.size(); i++) { workingModel = (MicroServiceModels) microServiceModelsData.get(i); @@ -971,9 +1040,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ try{ - Map model = new HashMap(); + Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - List priorityList = new ArrayList(); + List priorityList = new ArrayList<>(); priorityCount = 10; for (int i = 1; i < priorityCount; i++) { priorityList.add(String.valueOf(i)); @@ -984,7 +1053,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { response.getWriter().write(j.toString()); } catch (Exception e){ - logger.error(e); + LOGGER.error(e); } } @@ -1020,52 +1089,45 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // Under AllOFType we have Match List matchList = allOf.getMatch(); if (matchList != null) { - int index = 0; Iterator iterMatch = matchList.iterator(); while (matchList.size()>1 && iterMatch.hasNext()) { MatchType match = iterMatch.next(); // - // Under the match we have attributevalue and + // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. // AttributeValueType attributeValue = match.getAttributeValue(); String value = (String) attributeValue.getContent().get(0); - + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); // First match in the target is EcompName, so set that value. - if (index == 0) { + if (attributeId.equals("ECOMPName")) { policyAdapter.setEcompName(value); } - if (index == 1){ + if (attributeId.equals("ConfigName")){ policyAdapter.setConfigName(value); } - if (index == 2){ - if(value != null){ - readFile(policyAdapter, entity); - } - } - if (index == 3){ + if (attributeId.equals("uuid")){ policyAdapter.setUuid(value); } - if (index == 4){ + if (attributeId.equals("location")){ policyAdapter.setLocation(value); } - if (index == 5){ + if (attributeId.equals("RiskType")){ policyAdapter.setRiskType(value); } - - if (index == 6){ + if (attributeId.equals("RiskLevel")){ policyAdapter.setRiskLevel(value); } - - if (index == 7){ + if (attributeId.equals("guard")){ policyAdapter.setGuard(value); } - if (index == 8 && !value.contains("NA")){ + if (attributeId.equals("TTLDate") && !value.contains("NA")){ String newDate = convertDate(value, true); policyAdapter.setTtlDate(newDate); } - index++; } + readFile(policyAdapter, entity); } } } @@ -1085,7 +1147,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } public static Map convert(String str, String split) { - Map map = new HashMap(); + Map map = new HashMap<>(); for(final String entry : str.split(split)) { String[] parts = entry.split("="); map.put(parts[0], parts[1]); @@ -1112,14 +1174,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { policyAdapter.setServiceType(msBody.getService()); } if(msBody.getContent() != null){ - LinkedHashMap data = new LinkedHashMap(); + LinkedHashMap data = new LinkedHashMap<>(); LinkedHashMap map = (LinkedHashMap) msBody.getContent(); readRecursivlyJSONContent(map, data); policyAdapter.setRuleData(data); } } catch (Exception e) { - logger.error(e); + LOGGER.error(e); } } @@ -1130,7 +1192,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { Object key = iterator.next(); Object value = map.get(key); if(value instanceof LinkedHashMap){ - LinkedHashMap secondObjec = new LinkedHashMap(); + LinkedHashMap secondObjec = new LinkedHashMap<>(); readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); for(String objKey: secondObjec.keySet()){ data.put(key+"." +objKey, secondObjec.get(objKey)); @@ -1140,7 +1202,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { for(int i = 0; i < jsonArrayVal.size(); i++){ Object arrayvalue = jsonArrayVal.get(i); if(arrayvalue instanceof LinkedHashMap){ - LinkedHashMap newData = new LinkedHashMap(); + LinkedHashMap newData = new LinkedHashMap<>(); readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); for(String objKey: newData.keySet()){ data.put(key+"@"+i+"." +objKey, newData.get(objKey)); @@ -1161,23 +1223,18 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - private String getPolicyScope(String value) { - GroupPolicyScopeList pScope = new GroupPolicyScopeList(); - List groupList= commonClassDao.getData(GroupPolicyScopeList.class); - if(groupList.size() > 0){ - for(int i = 0 ; i < groupList.size() ; i ++){ - pScope = (GroupPolicyScopeList) groupList.get(i); - if (pScope.getGroupList().equals(value)){ - break; - } - } + private String getPolicyScope(String value) { + List groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); + if(groupList != null && !groupList.isEmpty()){ + GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); + return pScope.getGroupName(); } - return pScope.getGroupName(); + return null; } //Convert the map values and set into JSON body public Map convertMap(Map attributesMap, Map attributesRefMap) { - Map attribute = new HashMap(); + Map attribute = new HashMap<>(); String temp = null; String key; String value; @@ -1242,12 +1299,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } }catch(Exception e){ - logger.error("Upload error : " + e); + LOGGER.error("Upload error : " + e); } } } - List fileList = new ArrayList();; + List fileList = new ArrayList<>();; this.directory = "model"; if (zip){ extractFolder(this.newFile); @@ -1262,7 +1319,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if(yml==false){ modelType="xmi"; //Process Main Model file first - classMap = new HashMap(); + classMap = new HashMap<>(); for (File file : fileList) { if(!file.isDirectory() && file.getName().endsWith(".xmi")){ retreiveDependency(file.toString(), true); @@ -1280,25 +1337,30 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { MSAttributeObject msAttributes= new MSAttributeObject(); msAttributes.setClassName(className); - HashMap returnAttributeList =new HashMap(); + HashMap returnAttributeList =new HashMap<>(); returnAttributeList.put(className, this.attributeString); msAttributes.setAttribute(returnAttributeList); msAttributes.setSubClass(this.retmap); - HashMap returnReferenceList =new HashMap(); + HashMap returnReferenceList =new HashMap<>(); //String[] referenceArray=this.referenceAttributes.split("="); returnReferenceList.put(className, this.referenceAttributes); msAttributes.setRefAttribute(returnReferenceList); if(this.listConstraints!=""){ - HashMap enumList =new HashMap(); - String[] listArray=this.listConstraints.split("="); - enumList.put(listArray[0], listArray[1]); + HashMap enumList =new HashMap<>(); + String[] listArray=this.listConstraints.split("#"); + for(String str:listArray){ + String[] strArr= str.split("="); + if(strArr.length>1){ + enumList.put(strArr[0], strArr[1]); + } + } msAttributes.setEnumType(enumList); } - classMap=new HashMap(); + classMap=new HashMap<>(); classMap.put(className, msAttributes); } @@ -1325,7 +1387,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { int BUFFER = 2048; File file = new File(zipFile); - ZipFile zip; + ZipFile zip = null; try { zip = new ZipFile(file); String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); @@ -1363,19 +1425,26 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } } catch (IOException e) { - logger.error("Failed to unzip model file " + zipFile); + LOGGER.error("Failed to unzip model file " + zipFile); + }finally{ + try { + if(zip != null) + zip.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While closing zipfile " + e); + } } } private void retreiveDependency(String workingFile, Boolean modelClass) { - MSModelUtils utils = new MSModelUtils(PolicyController.msEcompName, PolicyController.msPolicyName); - HashMap tempMap = new HashMap(); + MSModelUtils utils = new MSModelUtils(PolicyController.getMsEcompName(), PolicyController.getMsPolicyName()); + HashMap tempMap = new HashMap<>(); tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); classMap.putAll(tempMap); - logger.info(tempMap); + LOGGER.info(tempMap); return; @@ -1383,7 +1452,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private List listModelFiles(String directoryName) { File directory = new File(directoryName); - List resultList = new ArrayList(); + List resultList = new ArrayList<>(); File[] fList = directory.listFiles(); for (File file : fList) { if (file.isFile()) { @@ -1401,7 +1470,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { try { FileUtils.forceDelete(new File(path)); } catch (IOException e) { - logger.error("Failed to delete folder " + path); + LOGGER.error("Failed to delete folder " + path); } } } @@ -1415,7 +1484,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } private List createList() { - List list = new ArrayList(); + List list = new ArrayList<>(); for (Entry cMap : classMap.entrySet()){ if (cMap.getValue().isPolicyTempalate()){ list.add(cMap.getKey()); @@ -1433,23 +1502,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return list; } + public Map getAttributesListRefMap() { + return attributesListRefMap; + } + + public Map> getArrayTextList() { + return arrayTextList; + } + } class DCAEMicroServiceObject { - public String service; - public String location; - public String uuid; - public String policyName; - public String description; - public String configName; - public String templateVersion; - public String version; - public String priority; - public String policyScope; - public String riskType; - public String riskLevel; - public String guard = null; + private String service; + private String location; + private String uuid; + private String policyName; + private String description; + private String configName; + private String templateVersion; + private String version; + private String priority; + private String policyScope; + private String riskType; + private String riskLevel; + private String guard = null; public String getGuard() { return guard;