import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
+import org.yaml.snakeyaml.Yaml;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
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;
@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<String> modelList = new ArrayList<String>();
- private List<String> dirDependencyList = new ArrayList<String>();
- private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
+ private List<String> modelList = new ArrayList<>();
+ private List<String> dirDependencyList = new ArrayList<>();
+ private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
+ //Tosca Model related Datastructure.
+ String referenceAttributes;
+ String attributeString;
+ String listConstraints;
+ String subAttributeString;
+ HashMap<String, Object> retmap = new HashMap<>();
+ Set<String> uniqueKeys= new HashSet<>();
+ Set<String> uniqueDataKeys= new HashSet<>();
+ StringBuilder dataListBuffer=new StringBuilder();
+ List<String> 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){
protected PolicyRestAdapter policyAdapter = null;
private int priorityCount;
- private Map<String, String> attributesListRefMap = new HashMap<String, String>();
- private Map<String, LinkedList<String>> arrayTextList = new HashMap<String, LinkedList<String>>();
+ private Map<String, String> attributesListRefMap = new HashMap<>();
+ private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
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;
try {
json = om.writeValueAsString(microServiceObject);
} catch (JsonProcessingException e) {
- logger.error("Error writing out the object");
+ LOGGER.error("Error writing out the object", e);
}
- System.out.println(json);
+ LOGGER.info(json);
String cleanJson = cleanUPJson(json);
cleanJson = removeNullAttributes(cleanJson);
policyAdapter.setJsonBody(cleanJson);
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 int stringBetweenDots(String str){
+ String stringToSearch=str;
+ String[]ss=stringToSearch.split("\\.");
+ if(ss!=null){
+ int len= ss.length;
+ if(len>2){
+ uniqueKeys.add(ss[2]);
+ }
+ }
+
+ return uniqueKeys.size();
+ }
+
+ public void stringBetweenDotsForDataFields(String str){
+ String stringToSearch=str;
+ String[]ss=stringToSearch.split("\\.");
+ if(ss!=null){
+ int len= ss.length;
+
+ if(len>2){
+ uniqueDataKeys.add(ss[0]+"%"+ss[2]);
+ }
+ }
+ }
+
+
+ public Map<String, String> load(String fileName) throws IOException {
+ File newConfiguration = new File(fileName);
+ InputStream is = null;
+ try {
+ is = new FileInputStream(newConfiguration);
+ } catch (FileNotFoundException e) {
+ LOGGER.error(e);
+ }
+
+ Yaml yaml = new Yaml();
+ @SuppressWarnings("unchecked")
+ Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is);
+ StringBuilder sb = new StringBuilder();
+ Map<String, String> settings = new HashMap<>();
+ if (yamlMap == null) {
+ return settings;
+ }
+ List<String> path = new ArrayList <>();
+ serializeMap(settings, sb, path, yamlMap);
+ return settings;
+ }
+
+ public Map<String, String> load(byte[] source) throws IOException {
+ Yaml yaml = new Yaml();
+ @SuppressWarnings("unchecked")
+ Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
+ StringBuilder sb = new StringBuilder();
+ Map<String, String> settings = new HashMap <>();
+ if (yamlMap == null) {
+ return settings;
+ }
+ List<String> path = new ArrayList <>();
+ serializeMap(settings, sb, path, yamlMap);
+ return settings;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
+ for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
+ if (entry.getValue() instanceof Map) {
+ path.add((String) entry.getKey());
+ serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
+ path.remove(path.size() - 1);
+ } else if (entry.getValue() instanceof List) {
+ path.add((String) entry.getKey());
+ serializeList(settings, sb, path, (List) entry.getValue());
+ path.remove(path.size() - 1);
+ } else {
+ serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
+ int counter = 0;
+ for (Object listEle : yamlList) {
+ if (listEle instanceof Map) {
+ path.add(Integer.toString(counter));
+ serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
+ path.remove(path.size() - 1);
+ } else if (listEle instanceof List) {
+ path.add(Integer.toString(counter));
+ serializeList(settings, sb, path, (List<String>) listEle);
+ path.remove(path.size() - 1);
+ } else {
+ serializeValue(settings, sb, path, Integer.toString(counter), listEle);
+ }
+ counter++;
+ }
+ }
+
+ private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
+ if (value == null) {
+ return;
+ }
+ sb.setLength(0);
+ for (String pathEle : path) {
+ sb.append(pathEle).append('.');
+ }
+ sb.append(name);
+ settings.put(sb.toString(), value.toString());
+ }
+
+ void parseDataAndPolicyNodes(Map<String,String> 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());
+
+ 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());
+ stringBetweenDotsForDataFields(subNodeString);
+ }
+ }
+ }
+ HashMap<String,String> parseDataNodes(Map<String,String> map){
+ HashMap<String,String> dataMapForJson=new HashMap <>();
+ for(String uniqueDataKey: uniqueDataKeys){
+ if(uniqueDataKey.contains("%")){
+ String[] uniqueDataKeySplit= uniqueDataKey.split("%");
+ 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+",");
+ }
+ }
+ dataListBuffer.append("]#");
+
+ LOGGER.info(dataListBuffer);
+ }
+ }
+ }
+ 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());
+
+ }
+ }
+ }
+ return dataMapForJson;
+ }
+
+ void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
+ HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
+ HashMap<String,String> hmSub;
+ for(Map.Entry<String, String> 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);
+ }
+ else{
+ hmSub=new HashMap <>();
+ hmSub.put(uniqueDataKeySplit[1], value);
+ }
+
+ dataMapKey.put(uniqueDataKeySplit[0], hmSub);
+ }
+
+ JSONObject mainObject= new JSONObject();
+ JSONObject json;
+ for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
+ String s=entry.getKey();
+ json= new JSONObject();
+ HashMap<String,String> jsonHm=dataMapKey.get(s);
+ for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
+ String key=entryMap.getKey();
+ json.put(key, jsonHm.get(key));
+ }
+ mainObject.put(s,json);
+ }
+ Iterator<String> 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<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
+ HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
+ for(String uniqueKey: uniqueKeys){
+ HashMap<String,String> hm;
+
+ for(Map.Entry<String,String> 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);
+ }
+
+ } 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"))
+ {
+ hm.put(keyStr,valueStr);
+ }
+ }else{
+ hm.put(keyStr,valueStr);
+ }
+ mapKey.put(uniqueKey, hm);
+ }
+ }
+ }
+ }
+ return mapKey;
+ }
+
+ void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
+ StringBuilder attributeStringBuilder= new StringBuilder();
+ StringBuilder referenceStringBuilder= new StringBuilder();
+ StringBuilder listBuffer= new StringBuilder();
+ List<String> constraints= new ArrayList<>();
+ for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
+ String keySetString= entry.getKey();
+ HashMap<String,String> 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+",");
+
+ }
+ else if(keyValues.get("type").equalsIgnoreCase(LIST)){
+ //List Datatype
+ Set<String> keys= keyValues.keySet();
+ Iterator<String> 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+",");
+ }
+ }
+ }
+
+ }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+",");
+
+ }
+ 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();
+ }
+ }
+
+ 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<String,String> map= new HashMap<>();
+
+ try {
+ map=load(fileName);
+
+ parseDataAndPolicyNodes(map);
+
+ HashMap<String,String> dataMapForJson=parseDataNodes(map);
+
+ constructJsonForDataFields(dataMapForJson);
+
+ HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
+
+ createAttributes(mapKey);
+
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+
+ }
+
private String cleanUPJson(String json) {
String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
private JSONObject decodeContent(JsonNode jsonNode){
Iterator<JsonNode> jsonElements = jsonNode.elements();
Iterator<String> jsonKeys = jsonNode.fieldNames();
- Map<String,String> element = new TreeMap<String,String>();
+ Map<String,String> element = new TreeMap<>();
while(jsonElements.hasNext() && jsonKeys.hasNext()){
element.put(jsonKeys.next(), jsonElements.next().toString());
}
presKey = key;
}
// first check if we are different from old.
- System.out.println(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);
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();
}
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);
return null;
}
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "rawtypes" })
private String createMicroSeriveJson(MicroServiceModels returnModel) {
- Map<String, String> attributeMap = new HashMap<String, String>();
- Map<String, String> refAttributeMap = new HashMap<String, String>();
+ Map<String, String> attributeMap = new HashMap<>();
+ Map<String, String> refAttributeMap = new HashMap<>();
String attribute = returnModel.getAttributes();
if(attribute != null){
attribute = attribute.trim();
@SuppressWarnings("unchecked")
private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
JSONObject object = new JSONObject();
- Map<String, String> map = new HashMap<String, String>();
+ Map<String, String> map = new HashMap<>();
Object returnClass = subAttributeMap.get(name);
map = (Map<String, String>) returnClass;
JSONArray array = new JSONArray();
private Set<String> getVersionList(String name) {
MicroServiceModels workingModel = new MicroServiceModels();
- Set<String> list = new HashSet<String>();
+ Set<String> list = new HashSet<>();
List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
for (int i = 0; i < microServiceModelsData.size(); i++) {
workingModel = (MicroServiceModels) microServiceModelsData.get(i);
@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<String, Object> model = new HashMap<String, Object>();
+ Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
- List<String> priorityList = new ArrayList<String>();
+ List<String> priorityList = new ArrayList<>();
priorityCount = 10;
for (int i = 1; i < priorityCount; i++) {
priorityList.add(String.valueOf(i));
response.getWriter().write(j.toString());
}
catch (Exception e){
- e.printStackTrace();
+ LOGGER.error(e);
}
}
// Under AllOFType we have Match
List<MatchType> matchList = allOf.getMatch();
if (matchList != null) {
- int index = 0;
Iterator<MatchType> 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);
}
}
}
}
public static Map<String, String> convert(String str, String split) {
- Map<String, String> map = new HashMap<String, String>();
+ Map<String, String> map = new HashMap<>();
for(final String entry : str.split(split)) {
String[] parts = entry.split("=");
map.put(parts[0], parts[1]);
policyAdapter.setServiceType(msBody.getService());
}
if(msBody.getContent() != null){
- LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
+ LinkedHashMap<String, Object> data = new LinkedHashMap<>();
LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
readRecursivlyJSONContent(map, data);
policyAdapter.setRuleData(data);
}
} catch (Exception e) {
- e.printStackTrace();
+ LOGGER.error(e);
}
}
Object key = iterator.next();
Object value = map.get(key);
if(value instanceof LinkedHashMap<?, ?>){
- LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<String, Object>();
+ LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
for(String objKey: secondObjec.keySet()){
data.put(key+"." +objKey, secondObjec.get(objKey));
for(int i = 0; i < jsonArrayVal.size(); i++){
Object arrayvalue = jsonArrayVal.get(i);
if(arrayvalue instanceof LinkedHashMap<?, ?>){
- LinkedHashMap<String, Object> newData = new LinkedHashMap<String, Object>();
+ LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
for(String objKey: newData.keySet()){
data.put(key+"@"+i+"." +objKey, newData.get(objKey));
}
}
- private String getPolicyScope(String value) {
- GroupPolicyScopeList pScope = new GroupPolicyScopeList();
- List<Object> 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<Object> 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<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
- Map<String, String> attribute = new HashMap<String, String>();
+ Map<String, String> attribute = new HashMap<>();
String temp = null;
String key;
String value;
public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
boolean zip = false;
+ boolean yml= false;
for (FileItem item : items) {
- if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")){
+ if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
this.newModel = new MicroServiceModels();
try{
File file = new File(item.getName());
outputStream.close();
this.newFile = file.toString();
this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
+
if (this.newFile.toString().contains("-v")){
if (item.getName().endsWith(".zip")){
this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
zip = true;
- }else {
+ }else if(item.getName().endsWith(".yml")){
+ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
+ yml = true;
+ }
+ else {
this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
}
}
+
}catch(Exception e){
- logger.error("Upload error : " + e);
+ LOGGER.error("Upload error : " + e);
}
}
+
}
- List<File> fileList = new ArrayList<File>();;
+ List<File> fileList = new ArrayList<>();;
this.directory = "model";
if (zip){
extractFolder(this.newFile);
fileList = listModelFiles(this.directory);
+ }else if (yml==true){
+ parseTosca(this.newFile);
}else {
File file = new File(this.newFile);
fileList.add(file);
}
-
- //Process Main Model file first
- classMap = new HashMap<String,MSAttributeObject>();
- for (File file : fileList) {
- if(!file.isDirectory() && file.getName().endsWith(".xmi")){
- retreiveDependency(file.toString(), true);
- }
+ String modelType= "";
+ if(yml==false){
+ modelType="xmi";
+ //Process Main Model file first
+ classMap = new HashMap<>();
+ for (File file : fileList) {
+ if(!file.isDirectory() && file.getName().endsWith(".xmi")){
+ retreiveDependency(file.toString(), true);
+ }
+ }
+
+ modelList = createList();
+
+ cleanUp(this.newFile);
+ cleanUp(directory);
+ }else{
+ modelType="yml";
+ modelList.add(this.newModel.getModelName());
+ String className=this.newModel.getModelName();
+ MSAttributeObject msAttributes= new MSAttributeObject();
+ msAttributes.setClassName(className);
+
+ HashMap<String, String> returnAttributeList =new HashMap<>();
+ returnAttributeList.put(className, this.attributeString);
+ msAttributes.setAttribute(returnAttributeList);
+
+ msAttributes.setSubClass(this.retmap);
+
+ HashMap<String, String> returnReferenceList =new HashMap<>();
+ //String[] referenceArray=this.referenceAttributes.split("=");
+ returnReferenceList.put(className, this.referenceAttributes);
+ msAttributes.setRefAttribute(returnReferenceList);
+
+ if(this.listConstraints!=""){
+ HashMap<String, String> 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.put(className, msAttributes);
+
}
-
- modelList = createList();
-
- cleanUp(this.newFile);
- cleanUp(directory);
PrintWriter out = response.getWriter();
JSONObject j = new JSONObject();
j.put("classListDatas", modelList);
j.put("modelDatas", mapper.writeValueAsString(classMap));
+ j.put("modelType", modelType);
out.write(j.toString());
}
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);
}
}
} 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<String, MSAttributeObject> tempMap = new HashMap<String, MSAttributeObject>();
+ MSModelUtils utils = new MSModelUtils(PolicyController.getMsEcompName(), PolicyController.getMsPolicyName());
+ HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
classMap.putAll(tempMap);
- System.out.println(tempMap);
+ LOGGER.info(tempMap);
return;
private List<File> listModelFiles(String directoryName) {
File directory = new File(directoryName);
- List<File> resultList = new ArrayList<File>();
+ List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
try {
FileUtils.forceDelete(new File(path));
} catch (IOException e) {
- logger.error("Failed to delete folder " + path);
+ LOGGER.error("Failed to delete folder " + path);
}
}
}
}
private List<String> createList() {
- List<String> list = new ArrayList<String>();
+ List<String> list = new ArrayList<>();
for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
if (cMap.getValue().isPolicyTempalate()){
list.add(cMap.getKey());
return list;
}
+ public Map<String, String> getAttributesListRefMap() {
+ return attributesListRefMap;
+ }
+
+ public Map<String, LinkedList<String>> 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;