Fix checkstyle violations in sdc/jtosca
[sdc/sdc-tosca.git] / src / main / java / org / onap / sdc / toscaparser / api / elements / PolicyType.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.sdc.toscaparser.api.elements;
22
23 import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue;
24 import org.onap.sdc.toscaparser.api.utils.TOSCAVersionProperty;
25 import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder;
26
27 import java.util.ArrayList;
28 import java.util.LinkedHashMap;
29
30 public class PolicyType extends StatefulEntityType {
31
32     private static final String DERIVED_FROM = "derived_from";
33     private static final String METADATA = "metadata";
34     private static final String PROPERTIES = "properties";
35     private static final String VERSION = "version";
36     private static final String DESCRIPTION = "description";
37     private static final String TARGETS = "targets";
38     private static final String TRIGGERS = "triggers";
39     private static final String TYPE = "type";
40
41     private static final String[] SECTIONS = {
42             DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS, TRIGGERS, TYPE
43     };
44
45     private LinkedHashMap<String, Object> customDef;
46     private String policyDescription;
47     private Object policyVersion;
48     private LinkedHashMap<String, Object> properties;
49     private LinkedHashMap<String, Object> parentPolicies;
50     private LinkedHashMap<String, Object> metaData;
51     private ArrayList<String> targetsList;
52
53
54     public PolicyType(String type, LinkedHashMap<String, Object> customDef) {
55         super(type, POLICY_PREFIX, customDef);
56
57         this.type = type;
58         this.customDef = customDef;
59         validateKeys();
60
61         metaData = null;
62         if (defs != null && defs.get(METADATA) != null) {
63             metaData = (LinkedHashMap<String, Object>) defs.get(METADATA);
64             validateMetadata(metaData);
65         }
66
67         properties = null;
68         if (defs != null && defs.get(PROPERTIES) != null) {
69             properties = (LinkedHashMap<String, Object>) defs.get(PROPERTIES);
70         }
71         parentPolicies = getParentPolicies();
72
73         policyVersion = null;
74         if (defs != null && defs.get(VERSION) != null) {
75             policyVersion = (new TOSCAVersionProperty(
76                     defs.get(VERSION).toString())).getVersion();
77         }
78
79         policyDescription = null;
80         if (defs != null && defs.get(DESCRIPTION) != null) {
81             policyDescription = (String) defs.get(DESCRIPTION);
82         }
83
84         targetsList = null;
85         if (defs != null && defs.get(TARGETS) != null) {
86             targetsList = (ArrayList<String>) defs.get(TARGETS);
87             validateTargets(targetsList, this.customDef);
88         }
89
90     }
91
92     private LinkedHashMap<String, Object> getParentPolicies() {
93         LinkedHashMap<String, Object> policies = new LinkedHashMap<>();
94         String parentPolicy;
95         if (getParentType() != null) {
96             parentPolicy = getParentType().getType();
97         } else {
98             parentPolicy = null;
99         }
100         if (parentPolicy != null) {
101             while (parentPolicy != null && !parentPolicy.equals("tosca.policies.Root")) {
102                 policies.put(parentPolicy, TOSCA_DEF.get(parentPolicy));
103                 parentPolicy = (String)
104                         ((LinkedHashMap<String, Object>) policies.get(parentPolicy)).get("derived_from);");
105             }
106         }
107         return policies;
108     }
109
110     public String getType() {
111         return type;
112     }
113
114     public PolicyType getParentType() {
115         // Return a policy statefulentity of this node is derived from
116         if (defs == null) {
117             return null;
118         }
119         String policyEntity = derivedFrom(defs);
120         if (policyEntity != null) {
121             return new PolicyType(policyEntity, customDef);
122         }
123         return null;
124     }
125
126     public Object getPolicy(String name) {
127         // Return the definition of a policy field by name
128         if (defs != null && defs.get(name) != null) {
129             return defs.get(name);
130         }
131         return null;
132     }
133
134     public ArrayList<String> getTargets() {
135         // Return targets
136         return targetsList;
137     }
138
139     public String getDescription() {
140         return policyDescription;
141     }
142
143     public Object getVersion() {
144         return policyVersion;
145     }
146
147     private void validateKeys() {
148         for (String key : defs.keySet()) {
149             boolean bFound = false;
150             for (String sect : SECTIONS) {
151                 if (key.equals(sect)) {
152                     bFound = true;
153                     break;
154                 }
155             }
156             if (!bFound) {
157                 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE125", String.format(
158                         "UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"",
159                         type, key)));
160             }
161         }
162     }
163
164     private void validateTargets(ArrayList<String> targetsList,
165                                  LinkedHashMap<String, Object> customDef) {
166         for (String nodetype : targetsList) {
167             if (customDef.get(nodetype) == null) {
168                 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE126", String.format(
169                         "InvalidTypeError: \"%s\" defined in targets for policy \"%s\"",
170                         nodetype, type)));
171
172             }
173         }
174     }
175
176     private void validateMetadata(LinkedHashMap<String, Object> metaData) {
177         String mtype = (String) metaData.get("type");
178         if (mtype != null && !mtype.equals("map") && !mtype.equals("tosca:map")) {
179             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE127", String.format(
180                     "InvalidTypeError: \"%s\" defined in policy for metadata",
181                     mtype)));
182         }
183         for (String entrySchema : this.metaData.keySet()) {
184             Object estob = this.metaData.get(entrySchema);
185             if (estob instanceof LinkedHashMap) {
186                 String est = (String)
187                         ((LinkedHashMap<String, Object>) estob).get("type");
188                 if (!est.equals("string")) {
189                     ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE128", String.format(
190                             "InvalidTypeError: \"%s\" defined in policy for metadata \"%s\"",
191                             est, entrySchema)));
192                 }
193             }
194         }
195     }
196
197 }
198
199 /*python
200
201 from toscaparser.common.exception import ValidationIssueCollector
202 from toscaparser.common.exception import InvalidTypeError
203 from toscaparser.common.exception import UnknownFieldError
204 from toscaparser.elements.statefulentitytype import StatefulEntityType
205 from toscaparser.utils.validateutils import TOSCAVersionProperty
206
207
208 class PolicyType(StatefulEntityType):
209
210     '''TOSCA built-in policies type.'''
211     SECTIONS = (DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS) = \
212                ('derived_from', 'metadata', 'properties', 'version',
213                 'description', 'targets')
214
215     def __init__(self, ptype, custom_def=None):
216         super(PolicyType, self).__init__(ptype, self.POLICY_PREFIX,
217                                          custom_def)
218         self.type = ptype
219         self.custom_def = custom_def
220         self._validate_keys()
221
222         self.meta_data = None
223         if self.METADATA in self.defs:
224             self.meta_data = self.defs[self.METADATA]
225             self._validate_metadata(self.meta_data)
226
227         self.properties = None
228         if self.PROPERTIES in self.defs:
229             self.properties = self.defs[self.PROPERTIES]
230         self.parent_policies = self._get_parent_policies()
231
232         self.policy_version = None
233         if self.VERSION in self.defs:
234             self.policy_version = TOSCAVersionProperty(
235                 self.defs[self.VERSION]).get_version()
236
237         self.policy_description = self.defs[self.DESCRIPTION] \
238             if self.DESCRIPTION in self.defs else None
239
240         self.targets_list = None
241         if self.TARGETS in self.defs:
242             self.targets_list = self.defs[self.TARGETS]
243             self._validate_targets(self.targets_list, custom_def)
244
245     def _get_parent_policies(self):
246         policies = {}
247         parent_policy = self.parent_type.type if self.parent_type else None
248         if parent_policy:
249             while parent_policy != 'tosca.policies.Root':
250                 policies[parent_policy] = self.TOSCA_DEF[parent_policy]
251                 parent_policy = policies[parent_policy]['derived_from']
252         return policies
253
254     @property
255     def parent_type(self):
256         '''Return a policy statefulentity of this node is derived from.'''
257         if not hasattr(self, 'defs'):
258             return None
259         ppolicy_entity = self.derived_from(self.defs)
260         if ppolicy_entity:
261             return PolicyType(ppolicy_entity, self.custom_def)
262
263     def get_policy(self, name):
264         '''Return the definition of a policy field by name.'''
265         if name in self.defs:
266             return self.defs[name]
267
268     @property
269     def targets(self):
270         '''Return targets.'''
271         return self.targets_list
272
273     @property
274     def description(self):
275         return self.policy_description
276
277     @property
278     def version(self):
279         return self.policy_version
280
281     def _validate_keys(self):
282         for key in self.defs.keys():
283             if key not in self.SECTIONS:
284                 ValidationIssueCollector.appendException(
285                     UnknownFieldError(what='Policy "%s"' % self.type,
286                                       field=key))
287
288     def _validate_targets(self, targets_list, custom_def):
289         for nodetype in targets_list:
290             if nodetype not in custom_def:
291                 ValidationIssueCollector.appendException(
292                     InvalidTypeError(what='"%s" defined in targets for '
293                                      'policy "%s"' % (nodetype, self.type)))
294
295     def _validate_metadata(self, meta_data):
296         if not meta_data.get('type') in ['map', 'tosca:map']:
297             ValidationIssueCollector.appendException(
298                 InvalidTypeError(what='"%s" defined in policy for '
299                                  'metadata' % (meta_data.get('type'))))
300
301         for entry_schema, entry_schema_type in meta_data.items():
302             if isinstance(entry_schema_type, dict) and not \
303                     entry_schema_type.get('type') == 'string':
304                 ValidationIssueCollector.appendException(
305                     InvalidTypeError(what='"%s" defined in policy for '
306                                      'metadata "%s"'
307                                      % (entry_schema_type.get('type'),
308                                         entry_schema)))
309 */