aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/model/prop/ModelProperties.java
blob: b9effc57a946e64db3e28fcbd348895484e36a34 (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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * 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============================================
 * ===================================================================
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */

package org.onap.clamp.clds.model.prop;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.CldsModel;
import org.onap.clamp.clds.service.CldsService;

/**
 * Parse model properties.
 */
public class ModelProperties {
    protected static final EELFLogger                                 logger              = EELFManager.getInstance()
            .getLogger(CldsService.class);
    protected static final EELFLogger                                 auditLogger         = EELFManager.getInstance()
            .getAuditLogger();

    private ModelBpmn                                                 modelBpmn;
    private JsonNode                                                  modelJson;

    private final String                                              modelName;
    private final String                                              controlName;
    private final String                                              actionCd;
    // Flag indicate whether it is triggered by Validation Test button from UI
    private final boolean                                             isTest;

    private Global                                                    global;

    private final Map<String, AbstractModelElement>                   modelElements       = new ConcurrentHashMap<>();

    private String                                                    currentModelElementId;
    private String                                                    policyUniqueId;

    private static final Object                                       lock                = new Object();
    private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>();

    static {
        synchronized (lock) {
            modelElementClasses.put(Policy.class, Policy.getType());
            modelElementClasses.put(Tca.class, Tca.getType());
            modelElementClasses.put(Holmes.class, Holmes.getType());
        }
    }

    /**
     * Retain data required to parse the ModelElement objects. (Rather than
     * parse them all - parse them on demand if requested.)
     *
     * @param modelName
     *            The model name coming form the UI
     * @param controlName
     *            The closed loop name coming from the UI
     * @param actionCd
     *            Type of operation PUT,UPDATE,DELETE
     * @param isTest
     *            The test flag coming from the UI (for validation only, no
     *            query are physically executed)
     * @param modelBpmnText
     *            The BPMN flow in JSON from the UI
     * @param modelPropText
     *            The BPMN parameters for all boxes defined in modelBpmnTest
     * @throws IOException
     *             In case there is an issue with the JSON decoding
     */
    public ModelProperties(String modelName, String controlName, String actionCd, boolean isTest, String modelBpmnText,
            String modelPropText) throws IOException {
        this.modelName = modelName;
        this.controlName = controlName;
        this.actionCd = actionCd;
        this.isTest = isTest;
        modelBpmn = ModelBpmn.create(modelBpmnText);
        modelJson = new ObjectMapper().readTree(modelPropText);

        instantiateMissingModelElements();
    }

    /**
     * This method is meant to ensure that one ModelElement instance exists for
     * each ModelElement class.
     *
     * As new ModelElement classes could have been registered after
     * instantiation of this ModelProperties, we need to build the missing
     * ModelElement instances.
     */
    private final void instantiateMissingModelElements() {
        if (modelElementClasses.size() != modelElements.size()) {
            Set<String> missingTypes = new HashSet<>(modelElementClasses.values());
            missingTypes.removeAll(modelElements.keySet());
            // Parse the list of base Model Elements and build up the
            // ModelElements
            modelElementClasses.entrySet().stream().parallel()
                    .filter(entry -> (AbstractModelElement.class.isAssignableFrom(entry.getKey())
                            && missingTypes.contains(entry.getValue())))
                    .forEach(entry -> {
                        try {
                            modelElements.put(entry.getValue(),
                                    (entry.getKey()
                                            .getConstructor(ModelProperties.class, ModelBpmn.class, JsonNode.class)
                                            .newInstance(this, modelBpmn, modelJson)));
                        } catch (InstantiationException | NoSuchMethodException | IllegalAccessException
                                | InvocationTargetException e) {
                            logger.warn("Unable to instantiate a ModelElement, exception follows: " + e);
                        }
                    });
        }
    }

    /**
     * Get the VF for a model. If return null if there is no VF.
     *
     * @param model
     * @return
     */
    public static String getVf(CldsModel model) {
        List<String> vfs = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode modelJson = mapper.readTree(model.getPropText());
            Global global = new Global(modelJson);
            vfs = global.getResourceVf();
        } catch (IOException e) {
            logger.warn("no VF found", e);
        }
        String vf = null;
        if (vfs != null && !vfs.isEmpty()) {
            vf = vfs.get(0);
        }
        return vf;
    }

    /**
     * Create ModelProperties for Camunda Delegate.
     *
     * @param execution
     * @return
     * @throws JsonProcessingException
     * @throws IOException
     */
    public static ModelProperties create(DelegateExecution execution) throws IOException {
        String modelProp = new String((byte[]) execution.getVariable("modelProp"));
        String modelBpmnProp = (String) execution.getVariable("modelBpmnProp");
        String modelName = (String) execution.getVariable("modelName");
        String controlName = (String) execution.getVariable("controlName");
        String actionCd = (String) execution.getVariable("actionCd");
        boolean isTest = (boolean) execution.getVariable("isTest");

        return new ModelProperties(modelName, controlName, actionCd, isTest, modelBpmnProp, modelProp);
    }

    /**
     * return appropriate model element given the type
     *
     * @param type
     * @return
     */
    public AbstractModelElement getModelElementByType(String type) {
        AbstractModelElement modelElement = modelElements.get(type);
        if (modelElement == null) {
            throw new IllegalArgumentException("Invalid or not found ModelElement type: " + type);
        }
        return modelElement;
    }

    /**
     * @return the modelName
     */
    public String getModelName() {
        return modelName;
    }

    /**
     * @return the controlName
     */
    public String getControlName() {
        return controlName;
    }

    /**
     * @return the controlNameAndPolicyUniqueId
     */
    public String getControlNameAndPolicyUniqueId() {
        return controlName + "_" + policyUniqueId;
    }

    /**
     * @return the currentPolicyName
     */
    private String getCurrentPolicyName() {
        return normalizePolicyScopeName(controlName + "_" + currentModelElementId);
    }

    /**
     * @return the currentPolicyScopeAndPolicyName
     */
    public String getCurrentPolicyScopeAndPolicyName() {
        return normalizePolicyScopeName(modelName + "." + getCurrentPolicyName());
    }

    /**
     * @return the policyScopeAndNameWithUniqueId
     */
    public String getPolicyScopeAndNameWithUniqueId() {
        return normalizePolicyScopeName(modelName + "." + getCurrentPolicyName() + "_" + policyUniqueId);
    }

    /**
     * @return the currentPolicyScopeAndFullPolicyName
     */
    public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
        return normalizePolicyScopeName(modelName + "." + policyNamePrefix + getCurrentPolicyName());
    }

    /**
     * @return the currentPolicyScopeAndFullPolicyNameWithVersion
     */
    public String getCurrentPolicyScopeAndFullPolicyNameWithVersion(String policyNamePrefix, int version) {
        return normalizePolicyScopeName(
                modelName + "." + policyNamePrefix + getCurrentPolicyName() + "." + version + ".xml");
    }

    /**
     * Replace all '-' with '_' within policy scope and name.
     *
     * @param inName
     * @return
     */
    private String normalizePolicyScopeName(String inName) {
        return inName.replaceAll("-", "_");
    }

    /**
     * @return the currentModelElementId
     */
    public String getCurrentModelElementId() {
        return currentModelElementId;
    }

    /**
     * When generating a policy request for a model element, must set the id of
     * that model element using this method. Used to generate the policy name.
     *
     * @param currentModelElementId
     *            the currentModelElementId to set
     */
    public void setCurrentModelElementId(String currentModelElementId) {
        this.currentModelElementId = currentModelElementId;
    }

    /**
     * @return the policyUniqueId
     */
    public String getPolicyUniqueId() {
        return policyUniqueId;
    }

    /**
     * When generating a policy request for a model element, must set the unique
     * id of that policy using this method. Used to generate the policy name.
     *
     * @param policyUniqueId
     *            the policyUniqueId to set
     */
    public void setPolicyUniqueId(String policyUniqueId) {
        this.policyUniqueId = policyUniqueId;
    }

    /**
     * @return the actionCd
     */
    public String getActionCd() {
        return actionCd;
    }

    /**
     * @return the isTest
     */
    public boolean isTest() {
        return isTest;
    }

    /**
     * @return the isCreateRequest
     */
    public boolean isCreateRequest() {
        switch (actionCd) {
            case CldsEvent.ACTION_SUBMIT:
            case CldsEvent.ACTION_RESTART:
                return true;
        }
        return false;
    }

    public boolean isStopRequest() {
        switch (actionCd) {
            case CldsEvent.ACTION_STOP:
                return true;
        }
        return false;
    }

    /**
     * @return the global
     */
    public Global getGlobal() {
        if (global == null) {
            global = new Global(modelJson);
        }
        return global;
    }

    public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass,
            String type) {
        if (!modelElementClasses.containsKey(modelElementClass.getClass())) {
            modelElementClasses.put(modelElementClass, type);
        }
    }

    public <T extends AbstractModelElement> T getType(Class<T> clazz) {
        instantiateMissingModelElements();
        String type = modelElementClasses.get(clazz);
        return (type != null ? (T) modelElements.get(type) : null);
    }
}