Fix check style issues
[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.google.gson.JsonObject;
29 import com.google.gson.JsonParseException;
30 import java.lang.reflect.InvocationTargetException;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.concurrent.ConcurrentHashMap;
36 import org.apache.camel.Exchange;
37 import org.onap.clamp.clds.client.req.policy.PolicyClient;
38 import org.onap.clamp.clds.config.ClampProperties;
39 import org.onap.clamp.clds.exception.ModelBpmnException;
40 import org.onap.clamp.clds.model.CldsModel;
41 import org.onap.clamp.clds.service.CldsService;
42 import org.onap.clamp.clds.util.JsonUtils;
43
44 /**
45  * Parse model properties.
46  */
47 public class ModelProperties {
48
49     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class);
50     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
51     private ModelBpmn modelBpmn;
52     private JsonObject modelJson;
53     private final String modelName;
54     private final String controlName;
55     private final String actionCd;
56     // Flag indicate whether it is triggered by Validation Test button from UI
57     private final boolean testOnly;
58     private Global global;
59     private final Map<String, AbstractModelElement> modelElements = new ConcurrentHashMap<>();
60     private String currentModelElementId;
61     private String policyUniqueId;
62     private String guardUniqueId;
63     public static final String POLICY_GUARD_SUFFIX = "_Guard_";
64     private static final Object lock = new Object();
65     private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>();
66
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 parse
77      * 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 query are
87      *        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 = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class);
102             instantiateMissingModelElements();
103         } catch (JsonParseException 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 each
110      * ModelElement class. As new ModelElement classes could have been registered
111      * after instantiation of this ModelProperties, we need to build the missing
112      * ModelElement instances.
113      */
114     private 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().getConstructor(ModelProperties.class, ModelBpmn.class, JsonObject.class)
127                                 .newInstance(this, modelBpmn, modelJson)));
128                     } catch (InstantiationException | NoSuchMethodException | IllegalAccessException
129                         | InvocationTargetException e) {
130                         logger.warn("Unable to instantiate a ModelElement " + entry.getValue()
131                             + ", 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 The clds model
141      * @return The vf of the model
142      */
143     public static String getVf(CldsModel model) {
144         List<String> vfs = null;
145         try {
146             JsonObject modelJson = JsonUtils.GSON.fromJson(model.getPropText(), JsonObject.class);
147             Global global = new Global(modelJson);
148             vfs = global.getResourceVf();
149         } catch (JsonParseException 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 the flow
164      * @return A model Properties created from the parameters found in camelExchange
165      *         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      * Get the model name.
179      * @return the modelName
180      */
181     public String getModelName() {
182         return modelName;
183     }
184
185     /**
186      * Get the control name.
187      * @return the controlName
188      */
189     public String getControlName() {
190         return controlName;
191     }
192
193     /**
194      * Get the control name qnd policy uniqueId.
195      * @return the controlNameAndPolicyUniqueId
196      */
197     public String getControlNameAndPolicyUniqueId() {
198         return controlName + "_" + policyUniqueId;
199     }
200
201     /**
202      * Get the current policy name.
203      * @return the currentPolicyName
204      */
205     private String getCurrentPolicyName() {
206         return normalizePolicyScopeName(controlName + "_" + currentModelElementId);
207     }
208
209     private String createScopeSeparator(String policyScope) {
210         return policyScope.contains(".") ? "" : ".";
211     }
212
213     /**
214      * Get the current policy scope and policy name.
215      * @return the currentPolicyScopeAndPolicyName
216      */
217     public String getCurrentPolicyScopeAndPolicyName() {
218         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) + getCurrentPolicyName());
219     }
220
221     /**
222      * Get policy name for dcae deploy.
223      * @return The policyName that wil be used in input parameters of DCAE deploy
224      */
225     public String getPolicyNameForDcaeDeploy(ClampProperties refProp) {
226         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName)
227             + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName());
228     }
229
230     /**
231      * Get policy scope and name with uniqueid.
232      * @return the policyScopeAndNameWithUniqueId
233      */
234     public String getPolicyScopeAndNameWithUniqueId() {
235         return normalizePolicyScopeName(
236             modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId);
237     }
238
239     /**
240      * Get policy scope and name with unique guardid.
241      * @return the policyScopeAndNameWithUniqueId
242      */
243     public String getPolicyScopeAndNameWithUniqueGuardId() {
244         return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_"
245             + policyUniqueId + POLICY_GUARD_SUFFIX + guardUniqueId);
246     }
247
248     /**
249      * Get current policy scope and full policy name.
250      * @return the currentPolicyScopeAndFullPolicyName
251      */
252     public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
253         return normalizePolicyScopeName(
254             modelName + createScopeSeparator(modelName) + policyNamePrefix + getCurrentPolicyName());
255     }
256
257     /**
258      * Get policy name with scope context.
259      * @return the PolicyNameWithScopeContext
260      */
261     public String getPolicyNameWithScopeContext(String policyScope, String policyType, String vnfScope, String context,
262         String userDefinedName) {
263         return normalizePolicyScopeName(policyScope + createScopeSeparator(policyScope) + policyType + "_" + vnfScope
264             + "_" + context + "_" + modelName + "_" + userDefinedName);
265     }
266
267     /**
268      * Get policy name with prefix scope context.
269      * @return the PolicyNameWithPrefixScopeContext
270      */
271     public String getPolicyNameWithPrefixScopeContext(String policyScope, String policyType, String vnfScope,
272         String context, String userDefinedName, String policyPrefix) {
273         return normalizePolicyScopeName(policyScope + createScopeSeparator(policyScope) + policyPrefix + policyType
274             + "_" + vnfScope + "_" + context + "_" + modelName + "_" + userDefinedName);
275     }
276
277     /**
278      * Replace all '-' with '_' within policy scope and name.
279      *
280      * @param inName
281      * @return
282      */
283     private String normalizePolicyScopeName(String inName) {
284         return inName.replaceAll("-", "_");
285     }
286
287     /**
288      * Get current model element id.
289      * @return the currentModelElementId
290      */
291     public String getCurrentModelElementId() {
292         return currentModelElementId;
293     }
294
295     /**
296      * When generating a policy request for a model element, must set the id of that
297      * model element using this method. Used to generate the policy name.
298      *
299      * @param currentModelElementId
300      *        the currentModelElementId to set
301      */
302     public void setCurrentModelElementId(String currentModelElementId) {
303         this.currentModelElementId = currentModelElementId;
304     }
305
306     /**
307      * Get policy uniqueId.
308      * @return the policyUniqueId
309      */
310     public String getPolicyUniqueId() {
311         return policyUniqueId;
312     }
313
314     public String getGuardUniqueId() {
315         return guardUniqueId;
316     }
317
318     public void setGuardUniqueId(String guardUniqueId) {
319         this.guardUniqueId = guardUniqueId;
320     }
321
322     /**
323      * When generating a policy request for a model element, must set the unique id
324      * of that policy using this method. Used to generate the policy name.
325      *
326      * @param policyUniqueId
327      *        the policyUniqueId to set
328      */
329     public void setPolicyUniqueId(String policyUniqueId) {
330         this.policyUniqueId = policyUniqueId;
331     }
332
333     /**
334      * Get actioncd.
335      * @return the actionCd
336      */
337     public String getActionCd() {
338         return actionCd;
339     }
340
341     /**
342      * Get the testOnly flag value.
343      * @return the testOnly
344      */
345     public boolean isTestOnly() {
346         return testOnly;
347     }
348
349     /**
350      * Get the global value.
351      * @return the global
352      */
353     public Global getGlobal() {
354         if (global == null) {
355             global = new Global(modelJson);
356         }
357         return global;
358     }
359
360     public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass,
361         String type) {
362         if (!modelElementClasses.containsKey(modelElementClass.getClass())) {
363             modelElementClasses.put(modelElementClass, type);
364         }
365     }
366
367     public <T extends AbstractModelElement> T getType(Class<T> clazz) {
368         instantiateMissingModelElements();
369         String type = modelElementClasses.get(clazz);
370         return (type != null ? (T) modelElements.get(type) : null);
371     }
372 }