Remove ECOMP in headers
[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     /**
221      * @return the currentPolicyScopeAndPolicyName
222      */
223     public String getCurrentPolicyScopeAndPolicyName() {
224         return normalizePolicyScopeName(modelName + "." + getCurrentPolicyName());
225     }
226
227     /**
228      * @return The policyName that wil be used in input parameters of DCAE
229      *         deploy
230      */
231     public String getPolicyNameForDcaeDeploy(ClampProperties refProp) {
232         return normalizePolicyScopeName(modelName + "."
233                 + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName());
234     }
235
236     /**
237      * @return the policyScopeAndNameWithUniqueId
238      */
239     public String getPolicyScopeAndNameWithUniqueId() {
240         return normalizePolicyScopeName(modelName + "." + getCurrentPolicyName() + "_" + policyUniqueId);
241     }
242
243     /**
244      * @return the currentPolicyScopeAndFullPolicyName
245      */
246     public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
247         return normalizePolicyScopeName(modelName + "." + policyNamePrefix + getCurrentPolicyName());
248     }
249
250     /**
251      * @return the currentPolicyScopeAndFullPolicyNameWithVersion
252      */
253     public String getCurrentPolicyScopeAndFullPolicyNameWithVersion(String policyNamePrefix, int version) {
254         return normalizePolicyScopeName(
255                 modelName + "." + policyNamePrefix + getCurrentPolicyName() + "." + version + ".xml");
256     }
257
258     /**
259      * Replace all '-' with '_' within policy scope and name.
260      *
261      * @param inName
262      * @return
263      */
264     private String normalizePolicyScopeName(String inName) {
265         return inName.replaceAll("-", "_");
266     }
267
268     /**
269      * @return the currentModelElementId
270      */
271     public String getCurrentModelElementId() {
272         return currentModelElementId;
273     }
274
275     /**
276      * When generating a policy request for a model element, must set the id of
277      * that model element using this method. Used to generate the policy name.
278      *
279      * @param currentModelElementId
280      *            the currentModelElementId to set
281      */
282     public void setCurrentModelElementId(String currentModelElementId) {
283         this.currentModelElementId = currentModelElementId;
284     }
285
286     /**
287      * @return the policyUniqueId
288      */
289     public String getPolicyUniqueId() {
290         return policyUniqueId;
291     }
292
293     /**
294      * When generating a policy request for a model element, must set the unique
295      * id of that policy using this method. Used to generate the policy name.
296      *
297      * @param policyUniqueId
298      *            the policyUniqueId to set
299      */
300     public void setPolicyUniqueId(String policyUniqueId) {
301         this.policyUniqueId = policyUniqueId;
302     }
303
304     /**
305      * @return the actionCd
306      */
307     public String getActionCd() {
308         return actionCd;
309     }
310
311     /**
312      * @return the testOnly
313      */
314     public boolean isTestOnly() {
315         return testOnly;
316     }
317
318     /**
319      * @return the isCreateRequest
320      */
321     public boolean isCreateRequest() {
322         switch (actionCd) {
323             case CldsEvent.ACTION_SUBMIT:
324             case CldsEvent.ACTION_RESTART:
325                 return true;
326         }
327         return false;
328     }
329
330     public boolean isStopRequest() {
331         switch (actionCd) {
332             case CldsEvent.ACTION_STOP:
333                 return true;
334         }
335         return false;
336     }
337
338     /**
339      * @return the global
340      */
341     public Global getGlobal() {
342         if (global == null) {
343             global = new Global(modelJson);
344         }
345         return global;
346     }
347
348     public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass,
349             String type) {
350         if (!modelElementClasses.containsKey(modelElementClass.getClass())) {
351             modelElementClasses.put(modelElementClass, type);
352         }
353     }
354
355     public <T extends AbstractModelElement> T getType(Class<T> clazz) {
356         instantiateMissingModelElements();
357         String type = modelElementClasses.get(clazz);
358         return (type != null ? (T) modelElements.get(type) : null);
359     }
360 }