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