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