aboutsummaryrefslogtreecommitdiffstats
path: root/cps-tbdmt-service/src/main/java/org/onap/cps/tbdmt/service/ExecutionBusinessLogic.java
blob: a8004beacf461c85930c601a256d11c3b7e92959 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2021 Wipro Limited.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.cps.tbdmt.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hubspot.jinjava.Jinjava;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.onap.cps.tbdmt.client.CpsRestClient;
import org.onap.cps.tbdmt.db.TemplateRepository;
import org.onap.cps.tbdmt.exception.CpsClientException;
import org.onap.cps.tbdmt.exception.ExecuteException;
import org.onap.cps.tbdmt.exception.OutputTransformationException;
import org.onap.cps.tbdmt.exception.TemplateNotFoundException;
import org.onap.cps.tbdmt.model.AppConfiguration;
import org.onap.cps.tbdmt.model.ExecutionRequest;
import org.onap.cps.tbdmt.model.Template;
import org.onap.cps.tbdmt.model.TemplateKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ExecutionBusinessLogic {

    @Autowired
    private TemplateRepository templateRepository;

    @Autowired
    private AppConfiguration appConfiguration;

    @Autowired
    private CpsRestClient cpsRestClient;

    /**
     * Execute a template stored in the database.
     *
     * @param schemaSet schema set
     * @param templateId templateId
     * @param executionRequest inputs to be applied to the templates
     * @return result response from the execution of template
     */
    public String executeTemplate(final String schemaSet, final String templateId,
                    final ExecutionRequest executionRequest) {

        final Optional<Template> templateOptional = templateRepository.findById(new TemplateKey(templateId));
        if (templateOptional.isPresent()) {
            if (!StringUtils.isBlank(templateOptional.get().getMultipleQueryTemplateId())) {
                return executeMultipleQuery(templateOptional.get(), executionRequest.getInputParameters(),
                        executionRequest.getPayload());
            } else {
                return execute(templateOptional.get(), executionRequest.getInputParameters(),
                        executionRequest.getPayload());
            }
        }
        throw new TemplateNotFoundException("Template does not exist");
    }

    private String executeMultipleQuery(final Template template, final Map<String, String> inputParameters,
            final Map<String, Object> payload) throws OutputTransformationException {
        final List<Object> processedQueryOutput = new ArrayList<Object>();
        final String multipleQuerytemplateId = template.getMultipleQueryTemplateId();
        final Optional<Template> multipleQueryTemplate =
                templateRepository.findById(new TemplateKey(multipleQuerytemplateId));
        if (!multipleQueryTemplate.isPresent()) {
            throw new TemplateNotFoundException("Multiple query template does not exist");
        } else {
            if (StringUtils.isBlank(multipleQueryTemplate.get().getTransformParam())) {
                throw new OutputTransformationException("Error executing multiple query: "
                                + "Template must have atleast one transformParameter");
            }
            final List<String> transformParamList = new ArrayList<String>(
                    Arrays.asList(multipleQueryTemplate.get().getTransformParam().split("\\s*,\\s*")));
            final String inputKey = transformParamList.get(transformParamList.size() - 1);
            final String queryParamString = execute(multipleQueryTemplate.get(), inputParameters, payload);
            final List<String> queryParamList = new ArrayList<String>();
            final JsonParser jsonParser = new JsonParser();
            final Gson gson = new Gson();
            try {
                if (jsonParser.parse(queryParamString).isJsonArray()) {
                    final JsonArray array = jsonParser.parse(queryParamString).getAsJsonArray();

                    for (final JsonElement jsonElement : array) {
                        queryParamList.add(gson.fromJson(jsonElement, String.class));
                    }
                } else {
                    queryParamList.add(queryParamString);
                }
                queryParamList.forEach(queryParam -> {
                    final Map<String, String> inputParameter = new HashMap<String, String>();
                    inputParameter.put(inputKey, queryParam);
                    final Object result = execute(template, inputParameter, payload);
                    processedQueryOutput.add(result);
                });
            } catch (final Exception e) {
                throw new OutputTransformationException(e.getLocalizedMessage());
            }
            return processedQueryOutput.toString();
        }
    }

    private String execute(final Template template, final Map<String, String> inputParameters,
            final Map<String, Object> payload) {

        final String anchor = appConfiguration.getSchemaToAnchor().get(template.getModel());
        if (anchor == null) {
            throw new ExecuteException("Anchor not found for the schema");
        }
        final String xpath = generateXpath(template.getXpathTemplate(), inputParameters);
        try {
            if ("put".equalsIgnoreCase(template.getRequestType()) || "patch".equalsIgnoreCase(template.getRequestType())
                    || "post".equalsIgnoreCase(template.getRequestType())
                    || "post-list-node".equalsIgnoreCase(template.getRequestType())) {
                return cpsRestClient.addData(anchor, xpath, template.getRequestType(), payload);
            } else {
                final String result = cpsRestClient.fetchNode(anchor, xpath, template.getRequestType(),
                        template.getIncludeDescendants());
                if (StringUtils.isBlank(template.getTransformParam())) {
                    return result;
                } else {
                    final List<JsonElement> json = transform(template, result);
                    return new Gson().toJson(json);
                }
            }
        } catch (final CpsClientException e) {
            throw new ExecuteException(e.getLocalizedMessage());
        }
    }

    private List<JsonElement> transform(final Template template, final String result) {

        final JsonElement transformJsonElement = new Gson().fromJson(result, JsonElement.class);
        List<JsonElement> transformedResult;
        List<JsonElement> temp;
        List<JsonElement> processedOutput = new ArrayList<JsonElement>();
        final List<String> transformParamList =
                new ArrayList<String>(Arrays.asList(template.getTransformParam().split("\\s*,\\s*")));
        try {
            if (transformParamList.size() > 0) {
                processedOutput = find(transformParamList.get(0), transformJsonElement, new ArrayList<JsonElement>());
                transformParamList.remove(0);
                for (final String param : transformParamList) {
                    transformedResult = new ArrayList<JsonElement>();

                    for (final JsonElement json : processedOutput) {
                        temp = find(param, json, new ArrayList<JsonElement>());
                        transformedResult.addAll(temp);
                    }
                    processedOutput.clear();
                    processedOutput.addAll(transformedResult);
                }
            }
        } catch (final Exception e) {
            throw new OutputTransformationException(e.getLocalizedMessage());
        }

        return processedOutput;

    }

    private static List<JsonElement> find(final String param, final JsonElement jsonElement,
                    final List<JsonElement> output) {

        if (jsonElement.isJsonArray()) {
            for (final JsonElement je : jsonElement.getAsJsonArray()) {
                find(param, je, output);
            }
        } else {
            if (jsonElement.isJsonObject()) {
                final JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has(param)) {
                    output.add(jsonObject.getAsJsonObject().get(param));

                }
            }
        }
        return output;

    }

    private String generateXpath(final String xpathTemplate, final Map<String, String> templateParameters) {
        return new Jinjava().render(xpathTemplate, templateParameters);
    }
}