d5f3ae2283dbbfcca137a2e8a0ac417e10c0c73e
[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.fasterxml.jackson.databind.JsonNode;
29
30 import java.io.IOException;
31 import java.lang.reflect.InvocationTargetException;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.ConcurrentHashMap;
37
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.CldsEvent;
43 import org.onap.clamp.clds.model.CldsModel;
44 import org.onap.clamp.clds.service.CldsService;
45 import org.onap.clamp.clds.util.JacksonUtils;
46
47 /**
48  * Parse model properties.
49  */
50 public class ModelProperties {
51
52     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class);
53     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
54     private ModelBpmn modelBpmn;
55     private JsonNode modelJson;
56     private final String modelName;
57     private final String controlName;
58     private final String actionCd;
59     // Flag indicate whether it is triggered by Validation Test button from UI
60     private final boolean testOnly;
61     private Global global;
62     private final Map<String, AbstractModelElement> modelElements = new ConcurrentHashMap<>();
63     private String currentModelElementId;
64     private String policyUniqueId;
65     private static final Object lock = new Object();
66     private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>();
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
77      * parse 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
87      *            query are 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 = JacksonUtils.getObjectMapperInstance().readTree(modelPropText);
102             instantiateMissingModelElements();
103         } catch (IOException 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
110      * each ModelElement class. As new ModelElement classes could have been
111      * registered after instantiation of this ModelProperties, we need to build
112      * the missing ModelElement instances.
113      */
114     private final 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()
127                                             .getConstructor(ModelProperties.class, ModelBpmn.class, JsonNode.class)
128                                             .newInstance(this, modelBpmn, modelJson)));
129                         } catch (InstantiationException | NoSuchMethodException | IllegalAccessException
130                                 | InvocationTargetException e) {
131                             logger.warn("Unable to instantiate a ModelElement, exception follows: ", e);
132                         }
133                     });
134         }
135     }
136
137     /**
138      * Get the VF for a model. If return null if there is no VF.
139      *
140      * @param model
141      * @return
142      */
143     public static String getVf(CldsModel model) {
144         List<String> vfs = null;
145         try {
146             JsonNode modelJson = JacksonUtils.getObjectMapperInstance().readTree(model.getPropText());
147             Global global = new Global(modelJson);
148             vfs = global.getResourceVf();
149         } catch (IOException e) {
150             logger.warn("no VF found", e);
151         }
152         String vf = null;
153         if (vfs != null && !vfs.isEmpty()) {
154             vf = vfs.get(0);
155         }
156         return vf;
157     }
158
159     /**
160      * Create ModelProperties extracted from a CamelExchange.
161      *
162      * @param camelExchange
163      *            The camel Exchange object that contains all info provided to
164      *            the flow
165      * @return A model Properties created from the parameters found in
166      *         camelExchange object
167      */
168     public static ModelProperties create(Exchange camelExchange) {
169         String modelProp = (String) camelExchange.getProperty("modelProp");
170         String modelBpmnProp = (String) camelExchange.getProperty("modelBpmnProp");
171         String modelName = (String) camelExchange.getProperty("modelName");
172         String controlName = (String) camelExchange.getProperty("controlName");
173         String actionCd = (String) camelExchange.getProperty("actionCd");
174         boolean isTest = (boolean) camelExchange.getProperty("isTest");
175         return new ModelProperties(modelName, controlName, actionCd, isTest, modelBpmnProp, modelProp);
176     }
177
178     /**
179      * return appropriate model element given the type
180      *
181      * @param type
182      * @return
183      */
184     public AbstractModelElement getModelElementByType(String type) {
185         AbstractModelElement modelElement = modelElements.get(type);
186         if (modelElement == null) {
187             throw new IllegalArgumentException("Invalid or not found ModelElement type: " + type);
188         }
189         return modelElement;
190     }
191
192     /**
193      * @return the modelName
194      */
195     public String getModelName() {
196         return modelName;
197     }
198
199     /**
200      * @return the controlName
201      */
202     public String getControlName() {
203         return controlName;
204     }
205
206     /**
207      * @return the controlNameAndPolicyUniqueId
208      */
209     public String getControlNameAndPolicyUniqueId() {
210         return controlName + "_" + policyUniqueId;
211     }
212
213     /**
214      * @return the currentPolicyName
215      */
216     private String getCurrentPolicyName() {
217         return normalizePolicyScopeName(controlName + "_" + currentModelElementId);
218     }
219
220     private String createScopeSeparator(String policyScope) {
221         return policyScope.contains(".") ? "" : ".";
222     }
223
224     /**
225      * @return the currentPolicyScopeAndPolicyName
226      */
227     public String getCurrentPolicyScopeAndPolicyName() {
228         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) + getCurrentPolicyName());
229     }
230
231     /**
232      * @return The policyName that wil be used in input parameters of DCAE
233      *         deploy
234      */
235     public String getPolicyNameForDcaeDeploy(ClampProperties refProp) {
236         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName)
237                 + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName());
238     }
239
240     /**
241      * @return the policyScopeAndNameWithUniqueId
242      */
243     public String getPolicyScopeAndNameWithUniqueId() {
244         return normalizePolicyScopeName(
245                 modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId);
246     }
247
248     /**
249      * @return the currentPolicyScopeAndFullPolicyName
250      */
251     public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
252         return normalizePolicyScopeName(
253                 modelName + createScopeSeparator(modelName) + policyNamePrefix + getCurrentPolicyName());
254     }
255
256     /**
257      * Replace all '-' with '_' within policy scope and name.
258      *
259      * @param inName
260      * @return
261      */
262     private String normalizePolicyScopeName(String inName) {
263         return inName.replaceAll("-", "_");
264     }
265
266     /**
267      * @return the currentModelElementId
268      */
269     public String getCurrentModelElementId() {
270         return currentModelElementId;
271     }
272
273     /**
274      * When generating a policy request for a model element, must set the id of
275      * that model element using this method. Used to generate the policy name.
276      *
277      * @param currentModelElementId
278      *            the currentModelElementId to set
279      */
280     public void setCurrentModelElementId(String currentModelElementId) {
281         this.currentModelElementId = currentModelElementId;
282     }
283
284     /**
285      * @return the policyUniqueId
286      */
287     public String getPolicyUniqueId() {
288         return policyUniqueId;
289     }
290
291     /**
292      * When generating a policy request for a model element, must set the unique
293      * id of that policy using this method. Used to generate the policy name.
294      *
295      * @param policyUniqueId
296      *            the policyUniqueId to set
297      */
298     public void setPolicyUniqueId(String policyUniqueId) {
299         this.policyUniqueId = policyUniqueId;
300     }
301
302     /**
303      * @return the actionCd
304      */
305     public String getActionCd() {
306         return actionCd;
307     }
308
309     /**
310      * @return the testOnly
311      */
312     public boolean isTestOnly() {
313         return testOnly;
314     }
315
316     /**
317      * @return the isCreateRequest
318      */
319     public boolean isCreateRequest() {
320         switch (actionCd) {
321             case CldsEvent.ACTION_SUBMIT:
322             case CldsEvent.ACTION_RESTART:
323                 return true;
324         }
325         return false;
326     }
327
328     public boolean isStopRequest() {
329         switch (actionCd) {
330             case CldsEvent.ACTION_STOP:
331                 return true;
332         }
333         return false;
334     }
335
336     /**
337      * @return the global
338      */
339     public Global getGlobal() {
340         if (global == null) {
341             global = new Global(modelJson);
342         }
343         return global;
344     }
345
346     public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass,
347             String type) {
348         if (!modelElementClasses.containsKey(modelElementClass.getClass())) {
349             modelElementClasses.put(modelElementClass, type);
350         }
351     }
352
353     public <T extends AbstractModelElement> T getType(Class<T> clazz) {
354         instantiateMissingModelElements();
355         String type = modelElementClasses.get(clazz);
356         return (type != null ? (T) modelElements.get(type) : null);
357     }
358 }