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 keepEmpty = false;
55 if (var.startsWith("~")) {
56 var = var.substring(1);
60 boolean escape = true;
61 if (var.startsWith("'")) {
62 var = var.substring(1);
66 boolean quotes = true;
67 if (var.startsWith("\"")) {
68 var = var.substring(1);
72 Object o = createStructure(varmap, var);
73 return generateJson(o, escape, quotes, keepEmpty);
76 private static Object createStructure(Map<String, String> flatmap, String var) {
77 if (flatmap.containsKey(var)) {
78 return flatmap.get(var);
81 Map<String, Object> mm = new HashMap<>();
82 List<Object> ll = new ArrayList<>();
84 for (Map.Entry<String, String> e : flatmap.entrySet()) {
85 String key = e.getKey();
86 String value = e.getValue();
88 if (key.endsWith("_length") || key.endsWith("].key")) {
92 if (value == null || value.trim().isEmpty()) {
96 if (key.startsWith(var + "[")) {
97 String newKey = key.substring(var.length());
98 set(ll, newKey, value);
99 } else if (var == null || var.isEmpty()) {
101 } else if (key.startsWith(var + ".")) {
102 String newKey = key.substring(var.length() + 1);
103 set(mm, newKey, value);
116 @SuppressWarnings("unchecked")
117 public static void set(Object struct, String compositeKey, Object value) {
118 if (struct == null) {
119 throw new IllegalArgumentException("Null argument: struct");
122 if (compositeKey == null || compositeKey.length() == 0) {
123 throw new IllegalArgumentException("Null or empty argument: compositeKey");
130 List<Object> keys = splitCompositeKey(compositeKey);
131 Object currentValue = struct;
132 String currentKey = "";
134 for (int i = 0; i < keys.size() - 1; i++) {
135 Object key = keys.get(i);
137 if (key instanceof Integer) {
138 if (!(currentValue instanceof List)) {
139 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
142 Integer keyi = (Integer) key;
143 List<Object> currentValueL = (List<Object>) currentValue;
144 int size = currentValueL.size();
147 for (int k = 0; k < keyi - size + 1; k++) {
148 currentValueL.add(null);
152 Object newValue = currentValueL.get(keyi);
153 if (newValue == null) {
154 Object nextKey = keys.get(i + 1);
155 if (nextKey instanceof Integer) {
156 newValue = new ArrayList<>();
158 newValue = new HashMap<>();
160 currentValueL.set(keyi, newValue);
163 currentValue = newValue;
164 currentKey += "[" + key + "]";
167 if (!(currentValue instanceof Map)) {
168 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
171 Object newValue = ((Map<String, Object>) currentValue).get(key);
172 if (newValue == null) {
173 Object nextKey = keys.get(i + 1);
174 if (nextKey instanceof Integer) {
175 newValue = new ArrayList<>();
177 newValue = new HashMap<>();
179 ((Map<String, Object>) currentValue).put((String) key, newValue);
182 currentValue = newValue;
183 currentKey += "." + key;
187 Object key = keys.get(keys.size() - 1);
188 if (key instanceof Integer) {
189 if (!(currentValue instanceof List)) {
190 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References list '" + currentKey + "', but '" + currentKey + "' is not a list");
193 Integer keyi = (Integer) key;
194 List<Object> currentValueL = (List<Object>) currentValue;
195 int size = currentValueL.size();
198 for (int k = 0; k < keyi - size + 1; k++) {
199 currentValueL.add(null);
203 currentValueL.set(keyi, value);
206 if (!(currentValue instanceof Map)) {
207 throw new IllegalArgumentException("Cannot resolve: " + compositeKey + ": References map '" + currentKey + "', but '" + currentKey + "' is not a map");
210 ((Map<String, Object>) currentValue).put((String) key, value);
214 private static List<Object> splitCompositeKey(String compositeKey) {
215 if (compositeKey == null) {
216 return Collections.emptyList();
219 String[] ss = compositeKey.split("\\.");
220 List<Object> ll = new ArrayList<>();
221 for (String s : ss) {
222 if (s.length() == 0) {
226 int i1 = s.indexOf('[');
230 if (!s.endsWith("]")) {
231 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": No matching ] found");
234 String s1 = s.substring(0, i1);
235 if (s1.length() > 0) {
239 String s2 = s.substring(i1 + 1, s.length() - 1);
241 int n = Integer.parseInt(s2);
243 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index must be >= 0: " + n);
247 } catch (NumberFormatException e) {
248 throw new IllegalArgumentException("Invalid composite key: " + compositeKey + ": Index not a number: " + s2);
256 @SuppressWarnings("unchecked")
257 private static String generateXml(Object o, int indent, boolean escape) {
262 if (o instanceof String) {
263 return escape ? StringEscapeUtils.escapeXml10((String) o) : (String) o;
266 if (o instanceof Map) {
267 StringBuilder ss = new StringBuilder();
268 Map<String, Object> mm = (Map<String, Object>) o;
269 for (Map.Entry<String, Object> entry : mm.entrySet()) {
270 Object v = entry.getValue();
271 String key = entry.getKey();
272 if (v instanceof String) {
273 String s = escape ? StringEscapeUtils.escapeXml10((String) v) : (String) v;
274 ss.append(pad(indent)).append('<').append(key).append('>');
276 ss.append("</").append(key).append('>').append('\n');
277 } else if (v instanceof Map) {
278 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
279 ss.append(generateXml(v, indent + 1, escape));
280 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
281 } else if (v instanceof List) {
282 List<Object> ll = (List<Object>) v;
283 for (Object o1 : ll) {
284 ss.append(pad(indent)).append('<').append(key).append('>').append('\n');
285 ss.append(generateXml(o1, indent + 1, escape));
286 ss.append(pad(indent)).append("</").append(key).append('>').append('\n');
290 return ss.toString();
295 private static String generateJson(Object o, boolean escape, boolean quotes, boolean keepEmpty) {
299 if (o instanceof String && ((String) o).length() == 0 && !keepEmpty) {
303 StringBuilder ss = new StringBuilder();
304 generateJson(ss, o, 0, false, escape, quotes);
305 return ss.toString();
308 @SuppressWarnings("unchecked")
309 private static void generateJson(StringBuilder ss, Object o, int indent, boolean padFirst, boolean escape, boolean quotes) {
310 if (o instanceof String) {
311 String s = escape ? StringEscapeUtils.escapeJson((String) o) : (String) o;
313 ss.append(pad(indent));
316 ss.append('"').append(s).append('"');
323 if (o instanceof Map) {
324 Map<String, Object> mm = (Map<String, Object>) o;
327 ss.append(pad(indent));
331 boolean first = true;
332 for (Map.Entry<String, Object> entry : mm.entrySet()) {
337 Object v = entry.getValue();
338 String key = entry.getKey();
339 ss.append(pad(indent + 1)).append('"').append(key).append("\": ");
340 generateJson(ss, v, indent + 1, false, escape, true);
344 ss.append(pad(indent)).append('}');
349 if (o instanceof List) {
350 List<Object> ll = (List<Object>) o;
353 ss.append(pad(indent));
357 boolean first = true;
358 for (Object o1 : ll) {
364 generateJson(ss, o1, indent + 1, true, escape, quotes);
368 ss.append(pad(indent)).append(']');
372 public static String removeLastCommaJson(String s) {
373 StringBuilder sb = new StringBuilder();
376 while (k < s.length()) {
377 int i11 = s.indexOf('}', k);
378 int i12 = s.indexOf(']', k);
382 } else if (i12 < 0) {
385 i1 = i11 < i12 ? i11 : i12;
391 int i2 = s.lastIndexOf(',', i1);
397 String between = s.substring(i2 + 1, i1);
398 if (between.trim().length() > 0) {
403 sb.append(s.substring(start, i2));
408 sb.append(s.substring(start, s.length()));
410 return sb.toString();
413 public static String removeEmptyStructJson(String template, String s) {
415 while (k < s.length()) {
416 boolean curly = true;
417 int i11 = s.indexOf('{', k);
418 int i12 = s.indexOf('[', k);
423 } else if (i12 < 0) {
425 } else if (i11 < i12) {
433 int i2 = curly ? s.indexOf('}', i1) : s.indexOf(']', i1);
435 String value = s.substring(i1 + 1, i2);
436 if (value.trim().length() == 0) {
437 int i4 = s.lastIndexOf('\n', i1);
441 int i5 = s.indexOf('\n', i2);
447 /*If template mandates empty construct to be present, those should not be removed.*/
448 if (template != null && template.contains(s.substring(i4))) {
451 s = s.substring(0, i4) + s.substring(i5);
468 public static String removeEmptyStructXml(String s) {
470 while (k < s.length()) {
471 int i1 = s.indexOf('<', k);
472 if (i1 < 0 || i1 == s.length() - 1) {
476 char c1 = s.charAt(i1 + 1);
477 if (c1 == '?' || c1 == '!') {
482 int i2 = s.indexOf('>', i1);
488 String closingTag = "</" + s.substring(i1 + 1, i2 + 1);
489 int i3 = s.indexOf(closingTag, i2 + 1);
495 String value = s.substring(i2 + 1, i3);
496 if (value.trim().length() > 0) {
501 int i4 = s.lastIndexOf('\n', i1);
505 int i5 = s.indexOf('\n', i3);
510 s = s.substring(0, i4) + s.substring(i5);
517 private static String pad(int n) {
518 StringBuilder s = new StringBuilder();
519 for (int i = 0; i < n; i++) {
520 s.append(Character.toString('\t'));