2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.plugins.restapicall;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
29 import org.apache.commons.text.StringEscapeUtils;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 public final class XmlJsonUtil {
35 @SuppressWarnings("unused")
36 private static final Logger log = LoggerFactory.getLogger(XmlJsonUtil.class);
38 private XmlJsonUtil() {
39 // Preventing instantiation of the same.
42 public static String getXml(Map<String, String> varmap, String var) {
43 boolean escape = true;
44 if (var.startsWith("'")) {
45 var = var.substring(1);
49 Object o = createStructure(varmap, var);
50 return generateXml(o, 0, escape);
53 public static String getJson(Map<String, String> varmap, String var) {
54 boolean escape = true;
55 if (var.startsWith("'")) {
56 var = var.substring(1);
60 boolean quotes = true;
61 if (var.startsWith("\"")) {
62 var = var.substring(1);
66 Object o = createStructure(varmap, var);
67 return generateJson(o, escape, quotes);
70 private static Object createStructure(Map<String, String> flatmap, String var) {
71 if (flatmap.containsKey(var)) {
72 return flatmap.get(var);
75 Map<String, Object> mm = new HashMap<>();
76 List<Object> ll = new ArrayList<>();
78 for (Map.Entry<String, String> e : flatmap.entrySet()) {
79 String key = e.getKey();
80 String value = e.getValue();
82 if (key.endsWith("_length") || key.endsWith("].key")) {
86 if (key.startsWith(var + "[")) {
87 String newKey = key.substring(var.length());
88 set(ll, newKey, value);
89 } else if (var == null || var.isEmpty()) {
91 } else if (key.startsWith(var + ".")) {
92 String newKey = key.substring(var.length() + 1);
93 set(mm, newKey, value);
106 @SuppressWarnings("unchecked")
107 public static void set(Object struct, String compositeKey, Object value) {
108 if (struct == null) {
109 throw new IllegalArgumentException("Null argument: struct");
112 if (compositeKey == null || compositeKey.length() == 0) {
113 throw new IllegalArgumentException("Null or empty argument: compositeKey");
120 List<Object> keys = splitCompositeKey(compositeKey);
121 Object currentValue = struct;
122 String currentKey = "";
124 for (int i = 0; i < keys.size() - 1; i++) {
125 Object key = keys.get(i);
127 if (key instanceof Integer) {
128 if (!(currentValue instanceof List)) {
129 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
132 Integer keyi = (Integer) key;
133 List<Object> currentValueL = (List<Object>) currentValue;
134 int size = currentValueL.size();
137 for (int k = 0; k < keyi - size + 1; k++) {
138 currentValueL.add(null);
142 Object newValue = currentValueL.get(keyi);
143 if (newValue == null) {
144 Object nextKey = keys.get(i + 1);
145 if (nextKey instanceof Integer) {
146 newValue = new ArrayList<>();
148 newValue = new HashMap<>();
150 currentValueL.set(keyi, newValue);
153 currentValue = newValue;
154 currentKey += "[" + key + "]";
157 if (!(currentValue instanceof Map)) {
158 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
161 Object newValue = ((Map<String, Object>) currentValue).get(key);
162 if (newValue == null) {
163 Object nextKey = keys.get(i + 1);
164 if (nextKey instanceof Integer) {
165 newValue = new ArrayList<>();
167 newValue = new HashMap<>();
169 ((Map<String, Object>) currentValue).put((String) key, newValue);
172 currentValue = newValue;
173 currentKey += "." + key;
177 Object key = keys.get(keys.size() - 1);
178 if (key instanceof Integer) {
179 if (!(currentValue instanceof List)) {
180 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
183 Integer keyi = (Integer) key;
184 List<Object> currentValueL = (List<Object>) currentValue;
185 int size = currentValueL.size();
188 for (int k = 0; k < keyi - size + 1; k++) {
189 currentValueL.add(null);
193 currentValueL.set(keyi, value);
196 if (!(currentValue instanceof Map)) {
197 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
200 ((Map<String, Object>) currentValue).put((String) key, value);
204 private static List<Object> splitCompositeKey(String compositeKey) {
205 if (compositeKey == null) {
206 return Collections.emptyList();
209 String[] ss = compositeKey.split("\\.");
210 List<Object> ll = new ArrayList<>();
211 for (String s : ss) {
212 if (s.length() == 0) {
216 int i1 = s.indexOf('[');
220 if (!s.endsWith("]")) {
221 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": No matching ] found");
224 String s1 = s.substring(0, i1);
225 if (s1.length() > 0) {
229 String s2 = s.substring(i1 + 1, s.length() - 1);
231 int n = Integer.parseInt(s2);
233 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index must be >= 0: " + n);
237 } catch (NumberFormatException e) {
238 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index not a number: " + s2);
246 @SuppressWarnings("unchecked")
247 private static String generateXml(Object o, int indent, boolean escape) {
252 if (o instanceof String) {
253 return escape ? StringEscapeUtils.escapeXml10((String) o) : (String) o;
256 if (o instanceof Map) {
257 StringBuilder ss = new StringBuilder();
258 Map<String, Object> mm = (Map<String, Object>) o;
259 for (Map.Entry<String, Object> entry : mm.entrySet()) {
260 Object v = entry.getValue();
261 String key = entry.getKey();
262 if (v instanceof String) {
263 String s = escape ? StringEscapeUtils.escapeXml10((String) v) : (String) v;
264 ss.append(pad(indent)).append('<').append(key).append('>');
266 ss.append("</").append(key).append('>').append('\n');
267 } else if (v instanceof Map) {
268 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
269 ss.append(generateXml(v, indent + 1, escape));
270 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
271 } else if (v instanceof List) {
272 List<Object> ll = (List<Object>) v;
273 for (Object o1 : ll) {
274 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
275 ss.append(generateXml(o1, indent + 1, escape));
276 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
280 return ss.toString();
285 private static String generateJson(Object o, boolean escape, boolean quotes) {
289 if (o instanceof String && ((String) o).length() == 0) {
293 StringBuilder ss = new StringBuilder();
294 generateJson(ss, o, 0, false, escape, quotes);
295 return ss.toString();
298 @SuppressWarnings("unchecked")
299 private static void generateJson(StringBuilder ss, Object o, int indent, boolean padFirst, boolean escape, boolean quotes) {
300 if (o instanceof String) {
301 String s = escape ? StringEscapeUtils.escapeJson((String) o) : (String) o;
303 ss.append(pad(indent));
306 ss.append('"').append(s).append('"');
313 if (o instanceof Map) {
314 Map<String, Object> mm = (Map<String, Object>) o;
317 ss.append(pad(indent));
321 boolean first = true;
322 for (Map.Entry<String, Object> entry : mm.entrySet()) {
327 Object v = entry.getValue();
328 String key = entry.getKey();
329 ss.append(pad(indent + 1)).append('"').append(key).append("\": ");
330 generateJson(ss, v, indent + 1, false, escape, true);
334 ss.append(pad(indent)).append('}');
339 if (o instanceof List) {
340 List<Object> ll = (List<Object>) o;
343 ss.append(pad(indent));
347 boolean first = true;
348 for (Object o1 : ll) {
354 generateJson(ss, o1, indent + 1, true, escape, quotes);
358 ss.append(pad(indent)).append(']');
362 public static String removeLastCommaJson(String s) {
363 StringBuilder sb = new StringBuilder();
366 while (k < s.length()) {
367 int i11 = s.indexOf('}', k);
368 int i12 = s.indexOf(']', k);
372 } else if (i12 < 0) {
375 i1 = i11 < i12 ? i11 : i12;
381 int i2 = s.lastIndexOf(',', i1);
387 String between = s.substring(i2 + 1, i1);
388 if (between.trim().length() > 0) {
393 sb.append(s.substring(start, i2));
398 sb.append(s.substring(start, s.length()));
400 return sb.toString();
403 public static String removeEmptyStructJson(String template, String s) {
405 while (k < s.length()) {
406 boolean curly = true;
407 int i11 = s.indexOf('{', k);
408 int i12 = s.indexOf('[', k);
413 } else if (i12 < 0) {
415 } else if (i11 < i12) {
423 int i2 = curly ? s.indexOf('}', i1) : s.indexOf(']', i1);
425 String value = s.substring(i1 + 1, i2);
426 if (value.trim().length() == 0) {
427 int i4 = s.lastIndexOf('\n', i1);
431 int i5 = s.indexOf('\n', i2);
437 /*If template mandates empty construct to be present, those should not be removed.*/
438 if (template != null && template.contains(s.substring(i4))) {
441 s = s.substring(0, i4) + s.substring(i5);
458 public static String removeEmptyStructXml(String s) {
460 while (k < s.length()) {
461 int i1 = s.indexOf('<', k);
462 if (i1 < 0 || i1 == s.length() - 1) {
466 char c1 = s.charAt(i1 + 1);
467 if (c1 == '?' || c1 == '!') {
472 int i2 = s.indexOf('>', i1);
478 String closingTag = "</" + s.substring(i1 + 1, i2 + 1);
479 int i3 = s.indexOf(closingTag, i2 + 1);
485 String value = s.substring(i2 + 1, i3);
486 if (value.trim().length() > 0) {
491 int i4 = s.lastIndexOf('\n', i1);
495 int i5 = s.indexOf('\n', i3);
500 s = s.substring(0, i4) + s.substring(i5);
507 private static String pad(int n) {
508 StringBuilder s = new StringBuilder();
509 for (int i = 0; i < n; i++) {
510 s.append(Character.toString('\t'));