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