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 (value == null || value.trim().isEmpty()) {
90 if (key.startsWith(var + "[")) {
91 String newKey = key.substring(var.length());
92 set(ll, newKey, value);
93 } else if (var == null || var.isEmpty()) {
95 } else if (key.startsWith(var + ".")) {
96 String newKey = key.substring(var.length() + 1);
97 set(mm, newKey, value);
110 @SuppressWarnings("unchecked")
111 public static void set(Object struct, String compositeKey, Object value) {
112 if (struct == null) {
113 throw new IllegalArgumentException("Null argument: struct");
116 if (compositeKey == null || compositeKey.length() == 0) {
117 throw new IllegalArgumentException("Null or empty argument: compositeKey");
124 List<Object> keys = splitCompositeKey(compositeKey);
125 Object currentValue = struct;
126 String currentKey = "";
128 for (int i = 0; i < keys.size() - 1; i++) {
129 Object key = keys.get(i);
131 if (key instanceof Integer) {
132 if (!(currentValue instanceof List)) {
133 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
136 Integer keyi = (Integer) key;
137 List<Object> currentValueL = (List<Object>) currentValue;
138 int size = currentValueL.size();
141 for (int k = 0; k < keyi - size + 1; k++) {
142 currentValueL.add(null);
146 Object newValue = currentValueL.get(keyi);
147 if (newValue == null) {
148 Object nextKey = keys.get(i + 1);
149 if (nextKey instanceof Integer) {
150 newValue = new ArrayList<>();
152 newValue = new HashMap<>();
154 currentValueL.set(keyi, newValue);
157 currentValue = newValue;
158 currentKey += "[" + key + "]";
161 if (!(currentValue instanceof Map)) {
162 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
165 Object newValue = ((Map<String, Object>) currentValue).get(key);
166 if (newValue == null) {
167 Object nextKey = keys.get(i + 1);
168 if (nextKey instanceof Integer) {
169 newValue = new ArrayList<>();
171 newValue = new HashMap<>();
173 ((Map<String, Object>) currentValue).put((String) key, newValue);
176 currentValue = newValue;
177 currentKey += "." + key;
181 Object key = keys.get(keys.size() - 1);
182 if (key instanceof Integer) {
183 if (!(currentValue instanceof List)) {
184 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
187 Integer keyi = (Integer) key;
188 List<Object> currentValueL = (List<Object>) currentValue;
189 int size = currentValueL.size();
192 for (int k = 0; k < keyi - size + 1; k++) {
193 currentValueL.add(null);
197 currentValueL.set(keyi, value);
200 if (!(currentValue instanceof Map)) {
201 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
204 ((Map<String, Object>) currentValue).put((String) key, value);
208 private static List<Object> splitCompositeKey(String compositeKey) {
209 if (compositeKey == null) {
210 return Collections.emptyList();
213 String[] ss = compositeKey.split("\\.");
214 List<Object> ll = new ArrayList<>();
215 for (String s : ss) {
216 if (s.length() == 0) {
220 int i1 = s.indexOf('[');
224 if (!s.endsWith("]")) {
225 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": No matching ] found");
228 String s1 = s.substring(0, i1);
229 if (s1.length() > 0) {
233 String s2 = s.substring(i1 + 1, s.length() - 1);
235 int n = Integer.parseInt(s2);
237 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index must be >= 0: " + n);
241 } catch (NumberFormatException e) {
242 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index not a number: " + s2);
250 @SuppressWarnings("unchecked")
251 private static String generateXml(Object o, int indent, boolean escape) {
256 if (o instanceof String) {
257 return escape ? StringEscapeUtils.escapeXml10((String) o) : (String) o;
260 if (o instanceof Map) {
261 StringBuilder ss = new StringBuilder();
262 Map<String, Object> mm = (Map<String, Object>) o;
263 for (Map.Entry<String, Object> entry : mm.entrySet()) {
264 Object v = entry.getValue();
265 String key = entry.getKey();
266 if (v instanceof String) {
267 String s = escape ? StringEscapeUtils.escapeXml10((String) v) : (String) v;
268 ss.append(pad(indent)).append('<').append(key).append('>');
270 ss.append("</").append(key).append('>').append('\n');
271 } else if (v instanceof Map) {
272 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
273 ss.append(generateXml(v, indent + 1, escape));
274 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
275 } else if (v instanceof List) {
276 List<Object> ll = (List<Object>) v;
277 for (Object o1 : ll) {
278 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
279 ss.append(generateXml(o1, indent + 1, escape));
280 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
284 return ss.toString();
289 private static String generateJson(Object o, boolean escape, boolean quotes) {
293 if (o instanceof String && ((String) o).length() == 0) {
297 StringBuilder ss = new StringBuilder();
298 generateJson(ss, o, 0, false, escape, quotes);
299 return ss.toString();
302 @SuppressWarnings("unchecked")
303 private static void generateJson(StringBuilder ss, Object o, int indent, boolean padFirst, boolean escape, boolean quotes) {
304 if (o instanceof String) {
305 String s = escape ? StringEscapeUtils.escapeJson((String) o) : (String) o;
307 ss.append(pad(indent));
310 ss.append('"').append(s).append('"');
317 if (o instanceof Map) {
318 Map<String, Object> mm = (Map<String, Object>) o;
321 ss.append(pad(indent));
325 boolean first = true;
326 for (Map.Entry<String, Object> entry : mm.entrySet()) {
331 Object v = entry.getValue();
332 String key = entry.getKey();
333 ss.append(pad(indent + 1)).append('"').append(key).append("\": ");
334 generateJson(ss, v, indent + 1, false, escape, true);
338 ss.append(pad(indent)).append('}');
343 if (o instanceof List) {
344 List<Object> ll = (List<Object>) o;
347 ss.append(pad(indent));
351 boolean first = true;
352 for (Object o1 : ll) {
358 generateJson(ss, o1, indent + 1, true, escape, quotes);
362 ss.append(pad(indent)).append(']');
366 public static String removeLastCommaJson(String s) {
367 StringBuilder sb = new StringBuilder();
370 while (k < s.length()) {
371 int i11 = s.indexOf('}', k);
372 int i12 = s.indexOf(']', k);
376 } else if (i12 < 0) {
379 i1 = i11 < i12 ? i11 : i12;
385 int i2 = s.lastIndexOf(',', i1);
391 String between = s.substring(i2 + 1, i1);
392 if (between.trim().length() > 0) {
397 sb.append(s.substring(start, i2));
402 sb.append(s.substring(start, s.length()));
404 return sb.toString();
407 public static String removeEmptyStructJson(String template, String s) {
409 while (k < s.length()) {
410 boolean curly = true;
411 int i11 = s.indexOf('{', k);
412 int i12 = s.indexOf('[', k);
417 } else if (i12 < 0) {
419 } else if (i11 < i12) {
427 int i2 = curly ? s.indexOf('}', i1) : s.indexOf(']', i1);
429 String value = s.substring(i1 + 1, i2);
430 if (value.trim().length() == 0) {
431 int i4 = s.lastIndexOf('\n', i1);
435 int i5 = s.indexOf('\n', i2);
441 /*If template mandates empty construct to be present, those should not be removed.*/
442 if (template != null && template.contains(s.substring(i4))) {
445 s = s.substring(0, i4) + s.substring(i5);
462 public static String removeEmptyStructXml(String s) {
464 while (k < s.length()) {
465 int i1 = s.indexOf('<', k);
466 if (i1 < 0 || i1 == s.length() - 1) {
470 char c1 = s.charAt(i1 + 1);
471 if (c1 == '?' || c1 == '!') {
476 int i2 = s.indexOf('>', i1);
482 String closingTag = "</" + s.substring(i1 + 1, i2 + 1);
483 int i3 = s.indexOf(closingTag, i2 + 1);
489 String value = s.substring(i2 + 1, i3);
490 if (value.trim().length() > 0) {
495 int i4 = s.lastIndexOf('\n', i1);
499 int i5 = s.indexOf('\n', i3);
504 s = s.substring(0, i4) + s.substring(i5);
511 private static String pad(int n) {
512 StringBuilder s = new StringBuilder();
513 for (int i = 0; i < n; i++) {
514 s.append(Character.toString('\t'));