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