Enhancements for the aai-common library
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / transforms / XmlFormatTransformer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.aai.transforms;
21
22 import com.bazaarvoice.jolt.Chainr;
23 import com.bazaarvoice.jolt.JsonUtils;
24 import org.json.JSONObject;
25 import org.json.XML;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import java.util.List;
30
31 public class XmlFormatTransformer {
32
33     private static final Logger LOGGER = LoggerFactory.getLogger(XmlFormatTransformer.class);
34
35     private static final String RESULT_WITH_QUOTES = "\"result\"";
36     private static final String RESULTS_STRING = "results";
37
38     private Chainr chainr;
39
40     public XmlFormatTransformer() {
41         List<Object> spec = JsonUtils.classpathToList("/specs/transform-related-to-node.json");
42         this.chainr       = Chainr.fromSpec(spec);
43     }
44
45     public String transform(String input) {
46
47         Object transformedOutput;
48
49         if(!input.contains(RESULT_WITH_QUOTES)){
50             Object inputMap = JsonUtils.jsonToMap(input);
51             transformedOutput = chainr.transform(inputMap);
52
53             JSONObject jsonObject;
54             if(transformedOutput == null){
55                 LOGGER.debug("For the input {}, unable to transform it so returning null", input);
56                 jsonObject = new JSONObject();
57             } else {
58                 jsonObject = new JSONObject(JsonUtils.toJsonString(transformedOutput));
59             }
60
61             return XML.toString(jsonObject, RESULTS_STRING);
62         } else {
63             // If the json is already conforming to the following format
64             // {"results":[{"results":"v[2]"}]}
65             // Then no transformation is required
66             return XML.toString(new JSONObject(input));
67         }
68
69     }
70 }