- if (value==null || value.isNull()){
- ((ObjectNode) returnNode).remove(key);
- remove = true;
- }
- }
- if (remove){
- cleanJson = returnNode.toString();
- }
- if (value==null || value.isNull()){
- ((ObjectNode) returnNode).remove(key);
- remove = true;
- }
- }
- if (remove){
- cleanJson = returnNode.toString();
- }
-
- if(contentChanged){
- //set modified content to cleanJson
- JSONObject jObject = new JSONObject(cleanJson);
- jObject.put("content",removed.toString());
- cleanJson = cleanUPJson(jObject.toString());
- }
-
- } catch (IOException e) {
- LOGGER.error("Error writing out the JsonNode",e);
- }
- return cleanJson;
- }
-
- public static JsonArray removeNull(JsonArray array) {
- JsonArrayBuilder builder = Json.createArrayBuilder();
- int i = 0;
- for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
- JsonValue value = it.next();
- switch (value.getValueType()) {
- case ARRAY:
- JsonArray a = removeNull(array.getJsonArray(i));
- if (!a.isEmpty())
- builder.add(a);
- break;
- case OBJECT:
- JsonObject object = removeNull(array.getJsonObject(i));
- if (!object.isEmpty())
- builder.add(object);
- break;
- case STRING:
- String s = array.getString(i);
- if (s != null && !s.isEmpty())
- builder.add(s);
- break;
- case NUMBER:
- builder.add(array.getJsonNumber(i));
- break;
- case TRUE:
- case FALSE:
- builder.add(array.getBoolean(i));
- break;
- case NULL:
- break;
- }
- }
- return builder.build();
- }
-
- public static JsonObject removeNull(JsonObject obj) {
- JsonObjectBuilder builder = Json.createObjectBuilder();
- for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
- Entry<String, JsonValue> e = it.next();
- String key = e.getKey();
- JsonValue value = e.getValue();
- switch (value.getValueType()) {
- case ARRAY:
- JsonArray array = removeNull(obj.getJsonArray(key));
- if (!array.isEmpty())
- builder.add(key, array);
- break;
- case OBJECT:
- JsonObject object = removeNull(obj.getJsonObject(key));
- if (!object.isEmpty())
- builder.add(key, object);
- break;
- case STRING:
- String s = obj.getString(key);
- if (s != null && !s.isEmpty())
- builder.add(key, s);
- break;
- case NUMBER:
- builder.add(key, obj.getJsonNumber(key));
- break;
- case TRUE:
- case FALSE:
- builder.add(key, obj.getBoolean(key));
- break;
- case NULL:
- break;
- }
- }
- return builder.build();
- }
-
- // 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]);
- }
- }
- }
-
-
- @SuppressWarnings("unchecked")
- public Map<String, String> load(String fileName) throws IOException {
- File newConfiguration = new File(fileName);
- Yaml yaml = new Yaml();
- Map<Object, Object> yamlMap = null;
- try(InputStream is = new FileInputStream(newConfiguration)){
- yamlMap = (Map<Object, Object>) yaml.load(is);
- } catch (FileNotFoundException e) {
- LOGGER.error(e);
- }
-
- 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 != null && 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 != null && 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") != null && keyValues.get("type").equalsIgnoreCase(STRING)||
- keyValues.get("type") != null && 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") != null && 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
- if(StringUtils.isNumeric(key) ){ //only integer key for the value of Constrains
- constraints.add(keyValues.get(key));
- }
- }else{
- //This is user defined string
- String trimValue=value.substring(value.lastIndexOf('.')+1);
- StringBuilder referenceIndividualStringBuilder= new StringBuilder();
- referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
- referenceStringBuilder.append(referenceIndividualStringBuilder+",");
- }
- }
-
- }
-
- if(keyValues.get("type").equalsIgnoreCase(LIST) &&
- (constraints == null || constraints.isEmpty()) ) {
- referenceStringBuilder.append(keySetString+"=MANY-true"+",");
- }
- }else{
- //User defined Datatype.
- String value=keyValues.get("type");
- if(value != null && !value.isEmpty()){
- String trimValue=value.substring(value.lastIndexOf('.')+1);
- StringBuilder referenceIndividualStringBuilder= new StringBuilder();
- referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
- referenceStringBuilder.append(referenceIndividualStringBuilder+",");
- }else{
- LOGGER.info("keyValues.get(type) is null/empty");
- }
-
- }
- if(constraints!=null && ! constraints.isEmpty()){
- //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[]{"\\"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
-
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
- return cleanJson;
- }
-
- private JSONObject decodeContent(JsonNode jsonNode){
- Iterator<JsonNode> jsonElements = jsonNode.elements();
- Iterator<String> jsonKeys = jsonNode.fieldNames();
- Map<String,String> element = new TreeMap<>();
- while(jsonElements.hasNext() && jsonKeys.hasNext()){
- element.put(jsonKeys.next(), jsonElements.next().toString());
- }
- JSONObject jsonResult = new JSONObject();
- JSONArray jsonArray = null;
- String oldValue = null;
- String nodeKey = null;
- String arryKey = null;
- Boolean isArray = false;
- JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
- ObjectNode node = nodeFactory.objectNode();
- String prevKey = null;
- String presKey;
- for(String key: element.keySet()){
- if(key.contains(".")){
- presKey = key.substring(0,key.indexOf('.'));
- }else if(key.contains("@")){
- presKey = key.substring(0,key.indexOf('@'));
- }else{
- presKey = key;
- }
- // first check if we are different from old.
- 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);
- jsonArray = new JSONArray();
- }
- }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
- jsonResult.put(oldValue, jsonArray);
- isArray = false;
- jsonArray = new JSONArray();
- }
-
- prevKey = presKey;
- //
- if(key.contains(".")){
- if(nodeKey==null){
- nodeKey = key.substring(0,key.indexOf('.'));
- }
- if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
- node.put(key.substring(key.indexOf('.')+1), element.get(key));
- }else{
- if(node.size()!=0){
- if(nodeKey.contains("@")){
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- if(nodeKey.endsWith("@0")){
- isArray = true;
- jsonArray = new JSONArray();
- }
- if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
- jsonArray.put(decodeContent(node));
- }
- if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){
- jsonResult.put(arryKey, jsonArray);
- jsonArray = new JSONArray();
- }
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }else{
- isArray = false;
- jsonResult.put(nodeKey, decodeContent(node));
- }
- node = nodeFactory.objectNode();
- }
- nodeKey = key.substring(0,key.indexOf('.'));
- if(nodeKey.contains("@")){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- node.put(key.substring(key.indexOf('.')+1), element.get(key));
- }
- }else if(node.size()!=0){
- if(nodeKey.contains("@")){
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- if(nodeKey.endsWith("@0")){
- isArray = true;
- jsonArray = new JSONArray();
- }
- if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
- jsonArray.put(decodeContent(node));
- }
- jsonResult.put(arryKey, jsonArray);
- jsonArray = new JSONArray();
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }else{
- isArray = false;
- jsonResult.put(nodeKey, decodeContent(node));
- }
- node = nodeFactory.objectNode();
- if(key.contains("@")){
- isArray = true;
- if(key.endsWith("@0")|| jsonArray==null){
- jsonArray = new JSONArray();
- }
- }else if(!key.contains("@")){
- isArray = false;
- }
- if(isArray){
- if(oldValue==null){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue!=prevKey){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonArray.put(element.get(key));
- }else{
- jsonResult.put(oldValue, jsonArray);
- jsonArray = new JSONArray();
- }
- oldValue = key.substring(0,key.indexOf('@'));
- }else{
- jsonResult.put(key, element.get(key));
- }
- }else{
- if(key.contains("@")){
- isArray = true;
- if(key.endsWith("@0")|| jsonArray==null){
- jsonArray = new JSONArray();
- }
- }else if(!key.contains("@")){
- isArray = false;
- }
- if(isArray){
- if(oldValue==null){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue!=prevKey){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonArray.put(element.get(key));
- }else{
- jsonResult.put(oldValue, jsonArray);
- jsonArray = new JSONArray();
- }
- oldValue = key.substring(0,key.indexOf('@'));
- }else{
- jsonResult.put(key, element.get(key));
- }
- }
- }
- if(node.size()>0){
- if(nodeKey.contains("@")){
- if(jsonArray==null){
- jsonArray = new JSONArray();
- }
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- jsonArray.put(decodeContent(node));
- jsonResult.put(arryKey, jsonArray);
- isArray = false;
- }else{
- jsonResult.put(nodeKey, decodeContent(node));
- }
- }
- if(isArray && jsonArray.length() > 0){
- jsonResult.put(oldValue, jsonArray);
- }
- return jsonResult;
- }
-
- @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- String version = null;
- if (value.contains("-v")){
- version = value.split("-v")[1];
- }
- MicroServiceModels returnModel = getAttributeObject(servicename, version);
-
-
- //Get all keys with "MANY-true" defined in their value from subAttribute
- Set<String> allkeys = null;
- if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
- JSONObject json = new JSONObject(returnModel.getSub_attributes());
- getAllKeys(json);
- allkeys = allManyTrueKeys;
- allManyTrueKeys = new HashSet <>();
- LOGGER.info("allkeys : " + allkeys);
- }
-
- String allManyTrueKeys = "";
- if(allkeys != null){
- allManyTrueKeys = allkeys.toString();
- }
-
- String jsonModel = createMicroSeriveJson(returnModel, allkeys);
-
- JSONObject jsonObject = new JSONObject(jsonModel);
-
- JSONObject finalJsonObject = null;
- if(allkeys != null){
- Iterator<String> iter = allkeys.iterator();
- while(iter.hasNext()){
- //Convert to array values for MANY-true keys
- finalJsonObject = convertToArrayElement(jsonObject, iter.next());
- }
- }
-
- if(finalJsonObject != null){
- LOGGER.info(finalJsonObject.toString());
- jsonModel = finalJsonObject.toString();
- }
-
- //get all properties with "MANY-true" defined in Ref_attributes
- Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
- if(manyTrueProperties != null){
- JSONObject jsonObj = new JSONObject(jsonModel);
- for (String s : manyTrueProperties) {
- LOGGER.info(s);
- //convert to array element for MANY-true properties
- finalJsonObject = convertToArrayElement(jsonObj, s.trim());
- }
-
- if(finalJsonObject != null){
- LOGGER.info(finalJsonObject.toString());
- jsonModel = finalJsonObject.toString();
- }
- }
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j;
- if("".equals(allManyTrueKeys)){
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
- }else{
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+ "}");
- }
- list.add(j);
- out.write(list.toString());
- return null;
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
- Map<String, String> attributeMap = new HashMap<>();
- Map<String, String> refAttributeMap = new HashMap<>();
- String attribute = returnModel.getAttributes();
- if(attribute != null){
- attribute = attribute.trim();
- }
- String refAttribute = returnModel.getRef_attributes();
- if(refAttribute != null){
- refAttribute = refAttribute.trim();
- }
- String enumAttribute = returnModel.getEnumValues();
- if(enumAttribute != null){
- enumAttribute = enumAttribute.trim();
- }
- if (!StringUtils.isEmpty(attribute)){
- attributeMap = convert(attribute, ",");
- }
- if (!StringUtils.isEmpty(refAttribute)){
- refAttributeMap = convert(refAttribute, ",");
- }
-
- Gson gson = new Gson();
-
- String subAttributes = returnModel.getSub_attributes();
- if(subAttributes != null){
- subAttributes = subAttributes.trim();
- }else{
- subAttributes = "";
- }
- Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
-
- JSONObject object = new JSONObject();
- JSONArray array;
-
- for (Entry<String, String> keySet : attributeMap.entrySet()){
- array = new JSONArray();
- String value = keySet.getValue();
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(value);
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), value.trim());
- }
- }
-
- for (Entry<String, String> keySet : refAttributeMap.entrySet()){
- array = new JSONArray();
- String value = keySet.getValue().split(":")[0];
- if (gsonObject.containsKey(value)){
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(recursiveReference(value, gsonObject, enumAttribute));
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
- }
- }else {
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(value.trim());
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), value.trim());
- }
- }
- }
-
-
-
- return object.toString();
- }
-
- @SuppressWarnings("unchecked")
- private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
- JSONObject object = new JSONObject();
- Map<String, String> map;
- Object returnClass = subAttributeMap.get(name);
- map = (Map<String, String>) returnClass;
- JSONArray array;
-
- for( Entry<String, String> m:map.entrySet()){
- String[] splitValue = m.getValue().split(":");
- array = new JSONArray();
- if (subAttributeMap.containsKey(splitValue[0])){
- if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
- array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
- object.put(m.getKey().trim(), array);
- }else {
- object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
- }
- } else{
- if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
- array.put(splitValue[0].trim());
- object.put(m.getKey().trim(), array);
- }else {
- object.put(m.getKey().trim(), splitValue[0].trim());
- }
- }
- }
-
- return object;
- }
-
-
- public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
- return convertToArrayElement(json, new HashSet<>(), keyValue);
- }
-
- private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
- for (String key : json.keySet()) {
- Object obj = json.get(key);
- if(key.equals(keyValue.trim())){
- if(!(obj instanceof JSONArray)){
- JSONArray newJsonArray = new JSONArray();
- newJsonArray.put(obj);
- json.put(key, newJsonArray);
- }
- LOGGER.info("key : " + key);
- LOGGER.info("obj : " + obj);
- LOGGER.info("json.get(key) : " + json.get(key));
- LOGGER.info("keyValue : " + keyValue);
- keys.addAll(json.keySet());
-
- return json;
- }
-
- if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);
- }
-
- return json;
- }
-
- // call this method to get all MANY-true properties
- public static Set<String> getManyTrueProperties(String referAttributes){
- LOGGER.info("referAttributes : " + referAttributes);
- Set<String> manyTrueProperties = new HashSet<>();
-
- if(referAttributes != null){
- String[] referAarray = referAttributes.split(",");
- String []element;
- for(int i=0; i<referAarray.length; i++){
- element = referAarray[i].split("=");
- if(element.length > 1 && element[1].contains("MANY-true")){
- manyTrueProperties.add(element[0]);
- }
- }
- }
-
- return manyTrueProperties;
- }
-
- //call this method to start the recursive
- private Set<String> getAllKeys(JSONObject json) {
- return getAllKeys(json, new HashSet<>());
- }
-
- private Set<String> getAllKeys(JSONArray arr) {
- return getAllKeys(arr, new HashSet<>());
- }
-
- private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
- for (int i = 0; i < arr.length(); i++) {
- Object obj = arr.get(i);
- if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
- }
-
- return keys;
- }