a880893eea02a30e7ac9f140bcaf0bbf417083bb
[clamp.git] / src / main / java / org / onap / clamp / clds / model / properties / ModelProperties.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END============================================
22  * ===================================================================
23  *
24  */
25
26 package org.onap.clamp.clds.model.properties;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.google.gson.JsonObject;
31 import com.google.gson.JsonParseException;
32 import java.lang.reflect.InvocationTargetException;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.concurrent.ConcurrentHashMap;
38 import org.apache.camel.Exchange;
39 import org.onap.clamp.clds.client.req.policy.PolicyClient;
40 import org.onap.clamp.clds.config.ClampProperties;
41 import org.onap.clamp.clds.exception.ModelBpmnException;
42 import org.onap.clamp.clds.model.CldsModel;
43 import org.onap.clamp.clds.service.CldsService;
44 import org.onap.clamp.clds.util.JsonUtils;
45
46 /**
47  * Parse model properties.
48  */
49 public class ModelProperties {
50
51     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class);
52     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
53     private ModelBpmn modelBpmn;
54     private JsonObject modelJson;
55     private final String modelName;
56     private final String controlName;
57     private final String actionCd;
58     // Flag indicate whether it is triggered by Validation Test button from UI
59     private final boolean testOnly;
60     private Global global;
61     private final Map<String, AbstractModelElement> modelElements = new ConcurrentHashMap<>();
62     private String currentModelElementId;
63     private String policyUniqueId;
64     private String guardUniqueId;
65     public static final String POLICY_GUARD_SUFFIX = "_Guard_";
66     private static final Object lock = new Object();
67     private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>();
68
69     static {
70         synchronized (lock) {
71             modelElementClasses.put(Policy.class, Policy.getType());
72             modelElementClasses.put(Tca.class, Tca.getType());
73             modelElementClasses.put(Holmes.class, Holmes.getType());
74         }
75     }
76
77     /**
78      * Retain data required to parse the ModelElement objects. (Rather than parse
79      * them all - parse them on demand if requested.)
80      *
81      * @param modelName
82      *        The model name coming form the UI
83      * @param controlName
84      *        The closed loop name coming from the UI
85      * @param actionCd
86      *        Type of operation PUT,UPDATE,DELETE
87      * @param isATest
88      *        The test flag coming from the UI (for validation only, no query are
89      *        physically executed)
90      * @param modelBpmnText
91      *        The BPMN flow in JSON from the UI
92      * @param modelPropText
93      *        The BPMN parameters for all boxes defined in modelBpmnTest
94      */
95     public ModelProperties(String modelName, String controlName, String actionCd, boolean isATest, String modelBpmnText,
96         String modelPropText) {
97         try {
98             this.modelName = modelName;
99             this.controlName = controlName;
100             this.actionCd = actionCd;
101             this.testOnly = isATest;
102             modelBpmn = ModelBpmn.create(modelBpmnText);
103             modelJson = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class);
104             instantiateMissingModelElements();
105         } catch (JsonParseException e) {
106             throw new ModelBpmnException("Exception occurred when trying to decode the BPMN Properties JSON", e);
107         }
108     }
109
110     /**
111      * This method is meant to ensure that one ModelElement instance exists for each
112      * ModelElement class. As new ModelElement classes could have been registered
113      * after instantiation of this ModelProperties, we need to build the missing
114      * ModelElement instances.
115      */
116     private void instantiateMissingModelElements() {
117         if (modelElementClasses.size() != modelElements.size()) {
118             Set<String> missingTypes = new HashSet<>(modelElementClasses.values());
119             missingTypes.removeAll(modelElements.keySet());
120             // Parse the list of base Model Elements and build up the
121             // ModelElements
122             modelElementClasses.entrySet().stream().parallel()
123                     .filter(entry -> (AbstractModelElement.class.isAssignableFrom(entry.getKey())
124                             && missingTypes.contains(entry.getValue())))
125                     .forEach(entry -> {
126                         try {
127                             modelElements.put(entry.getValue(),
128                                     (entry.getKey().getConstructor(ModelBpmn.class, JsonObject.class)
129                                             .newInstance(modelBpmn, modelJson)));
130                         } catch (InstantiationException | NoSuchMethodException | IllegalAccessException
131                                 | InvocationTargetException e) {
132                             logger.warn("Unable to instantiate a ModelElement " + entry.getValue()
133                                     + ", exception follows: ", e);
134                         }
135                     });
136         }
137     }
138
139     /**
140      * Get the VF for a model. If return null if there is no VF.
141      *
142      * @param model The clds model
143      * @return The vf of the model
144      */
145     public static String getVf(CldsModel model) {
146         List<String> vfs = null;
147         try {
148             JsonObject modelJson = JsonUtils.GSON.fromJson(model.getPropText(), JsonObject.class);
149             Global global = new Global(modelJson);
150             vfs = global.getResourceVf();
151         } catch (JsonParseException e) {
152             logger.warn("no VF found", e);
153         }
154         String vf = null;
155         if (vfs != null && !vfs.isEmpty()) {
156             vf = vfs.get(0);
157         }
158         return vf;
159     }
160
161     /**
162      * Create ModelProperties extracted from a CamelExchange.
163      *
164      * @param camelExchange
165      *        The camel Exchange object that contains all info provided to the flow
166      * @return A model Properties created from the parameters found in camelExchange
167      *         object
168      */
169     public static ModelProperties create(Exchange camelExchange) {
170         String modelProp = (String) camelExchange.getProperty("modelProp");
171         String modelBpmnProp = (String) camelExchange.getProperty("modelBpmnProp");
172         String modelName = (String) camelExchange.getProperty("modelName");
173         String controlName = (String) camelExchange.getProperty("controlName");
174         String actionCd = (String) camelExchange.getProperty("actionCd");
175         boolean isTest = (boolean) camelExchange.getProperty("isTest");
176         return new ModelProperties(modelName, controlName, actionCd, isTest, modelBpmnProp, modelProp);
177     }
178
179     /**
180      * Get the model name.
181      * @return the modelName
182      */
183     public String getModelName() {
184         return modelName;
185     }
186
187     /**
188      * Get the control name.
189      * @return the controlName
190      */
191     public String getControlName() {
192         return controlName;
193     }
194
195     /**
196      * Get the control name qnd policy uniqueId.
197      * @return the controlNameAndPolicyUniqueId
198      */
199     public String getControlNameAndPolicyUniqueId() {
200         return controlName + "_" + policyUniqueId;
201     }
202
203     /**
204      * Get the current policy name.
205      * @return the currentPolicyName
206      */
207     private String getCurrentPolicyName() {
208         return normalizePolicyScopeName(controlName + "_" + currentModelElementId);
209     }
210
211     private String createScopeSeparator(String policyScope) {
212         return policyScope.contains(".") ? "" : ".";
213     }
214
215     /**
216      * Get the current policy scope and policy name.
217      * @return the currentPolicyScopeAndPolicyName
218      */
219     public String getCurrentPolicyScopeAndPolicyName() {
220         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) + getCurrentPolicyName());
221     }
222
223     /**
224      * Get policy name for dcae deploy.
225      * @return The policyName that wil be used in input parameters of DCAE deploy
226      */
227     public String getPolicyNameForDcaeDeploy(ClampProperties refProp) {
228         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName)
229             + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName());
230     }
231
232     /**
233      * Get policy scope and name with uniqueid.
234      * @return the policyScopeAndNameWithUniqueId
235      */
236     public String getPolicyScopeAndNameWithUniqueId() {
237         return normalizePolicyScopeName(
238             modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId);
239     }
240
241     /**
242      * Get policy scope and name with unique guardid.
243      * @return the policyScopeAndNameWithUniqueId
244      */
245     public String getPolicyScopeAndNameWithUniqueGuardId() {
246         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_"
247             + policyUniqueId + POLICY_GUARD_SUFFIX + guardUniqueId);
248     }
249
250     /**
251      * Get current policy scope and full policy name.
252      * @return the currentPolicyScopeAndFullPolicyName
253      */
254     public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
255         return normalizePolicyScopeName(
256             modelName + createScopeSeparator(modelName) + policyNamePrefix + getCurrentPolicyName());
257     }
258
259     /**
260      * Get policy name with scope context.
261      * @return the PolicyNameWithScopeContext
262      */
263     public String getPolicyNameWithScopeContext(String policyScope, String policyType, String vnfScope, String context,
264         String userDefinedName) {
265         return normalizePolicyScopeName(policyScope + createScopeSeparator(policyScope) + policyType + "_" + vnfScope
266             + "_" + context + "_" + modelName + "_" + userDefinedName);
267     }
268
269     /**
270      * Get policy name with prefix scope context.
271      * @return the PolicyNameWithPrefixScopeContext
272      */
273     public String getPolicyNameWithPrefixScopeContext(String policyScope, String policyType, String vnfScope,
274         String context, String userDefinedName, String policyPrefix) {
275         return normalizePolicyScopeName(policyScope + createScopeSeparator(policyScope) + policyPrefix + policyType
276             + "_" + vnfScope + "_" + context + "_" + modelName + "_" + userDefinedName);
277     }
278
279     /**
280      * Replace all '-' with '_' within policy scope and name.
281      *
282      * @param inName
283      * @return
284      */
285     private String normalizePolicyScopeName(String inName) {
286         return inName.replaceAll("-", "_");
287     }
288
289     /**
290      * Get current model element id.
291      * @return the currentModelElementId
292      */
293     public String getCurrentModelElementId() {
294         return currentModelElementId;
295     }
296
297     /**
298      * When generating a policy request for a model element, must set the id of that
299      * model element using this method. Used to generate the policy name.
300      *
301      * @param currentModelElementId
302      *        the currentModelElementId to set
303      */
304     public void setCurrentModelElementId(String currentModelElementId) {
305         this.currentModelElementId = currentModelElementId;
306     }
307
308     /**
309      * Get policy uniqueId.
310      * @return the policyUniqueId
311      */
312     public String getPolicyUniqueId() {
313         return policyUniqueId;
314     }
315
316     public String getGuardUniqueId() {
317         return guardUniqueId;
318     }
319
320     public void setGuardUniqueId(String guardUniqueId) {
321         this.guardUniqueId = guardUniqueId;
322     }
323
324     /**
325      * When generating a policy request for a model element, must set the unique id
326      * of that policy using this method. Used to generate the policy name.
327      *
328      * @param policyUniqueId
329      *        the policyUniqueId to set
330      */
331     public void setPolicyUniqueId(String policyUniqueId) {
332         this.policyUniqueId = policyUniqueId;
333     }
334
335     /**
336      * Get actioncd.
337      * @return the actionCd
338      */
339     public String getActionCd() {
340         return actionCd;
341     }
342
343     /**
344      * Get the testOnly flag value.
345      * @return the testOnly
346      */
347     public boolean isTestOnly() {
348         return testOnly;
349     }
350
351     /**
352      * Get the global value.
353      * @return the global
354      */
355     public Global getGlobal() {
356         if (global == null) {
357             global = new Global(modelJson);
358         }
359         return global;
360     }
361
362     public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass,
363         String type) {
364         if (!modelElementClasses.containsKey(modelElementClass.getClass())) {
365             modelElementClasses.put(modelElementClass, type);
366         }
367     }
368
369     public <T extends AbstractModelElement> T getType(Class<T> clazz) {
370         instantiateMissingModelElements();
371         String type = modelElementClasses.get(clazz);
372         return (type != null ? (T) modelElements.get(type) : null);
373     }
374 }