2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.sdc.toscaparser.api.elements;
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;
27 import java.util.ArrayList;
28 import java.util.LinkedHashMap;
30 public class PolicyType extends StatefulEntityType {
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";
41 private static final String[] SECTIONS = {
42 DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS, TRIGGERS, TYPE
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;
54 public PolicyType(String type, LinkedHashMap<String, Object> customDef) {
55 super(type, POLICY_PREFIX, customDef);
58 this.customDef = customDef;
62 if (defs != null && defs.get(METADATA) != null) {
63 metaData = (LinkedHashMap<String, Object>) defs.get(METADATA);
64 validateMetadata(metaData);
68 if (defs != null && defs.get(PROPERTIES) != null) {
69 properties = (LinkedHashMap<String, Object>) defs.get(PROPERTIES);
71 parentPolicies = getParentPolicies();
74 if (defs != null && defs.get(VERSION) != null) {
75 policyVersion = (new TOSCAVersionProperty(
76 defs.get(VERSION).toString())).getVersion();
79 policyDescription = null;
80 if (defs != null && defs.get(DESCRIPTION) != null) {
81 policyDescription = (String) defs.get(DESCRIPTION);
85 if (defs != null && defs.get(TARGETS) != null) {
86 targetsList = (ArrayList<String>) defs.get(TARGETS);
87 validateTargets(targetsList, this.customDef);
92 private LinkedHashMap<String, Object> getParentPolicies() {
93 LinkedHashMap<String, Object> policies = new LinkedHashMap<>();
95 if (getParentType() != null) {
96 parentPolicy = getParentType().getType();
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);");
110 public String getType() {
114 public PolicyType getParentType() {
115 // Return a policy statefulentity of this node is derived from
119 String policyEntity = derivedFrom(defs);
120 if (policyEntity != null) {
121 return new PolicyType(policyEntity, customDef);
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);
134 public ArrayList<String> getTargets() {
139 public String getDescription() {
140 return policyDescription;
143 public Object getVersion() {
144 return policyVersion;
147 private void validateKeys() {
148 for (String key : defs.keySet()) {
149 boolean bFound = false;
150 for (String sect : SECTIONS) {
151 if (key.equals(sect)) {
157 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE125", String.format(
158 "UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"",
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\"",
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",
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\"",
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
208 class PolicyType(StatefulEntityType):
210 '''TOSCA built-in policies type.'''
211 SECTIONS = (DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, TARGETS) = \
212 ('derived_from', 'metadata', 'properties', 'version',
213 'description', 'targets')
215 def __init__(self, ptype, custom_def=None):
216 super(PolicyType, self).__init__(ptype, self.POLICY_PREFIX,
219 self.custom_def = custom_def
220 self._validate_keys()
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)
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()
232 self.policy_version = None
233 if self.VERSION in self.defs:
234 self.policy_version = TOSCAVersionProperty(
235 self.defs[self.VERSION]).get_version()
237 self.policy_description = self.defs[self.DESCRIPTION] \
238 if self.DESCRIPTION in self.defs else None
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)
245 def _get_parent_policies(self):
247 parent_policy = self.parent_type.type if self.parent_type else None
249 while parent_policy != 'tosca.policies.Root':
250 policies[parent_policy] = self.TOSCA_DEF[parent_policy]
251 parent_policy = policies[parent_policy]['derived_from']
255 def parent_type(self):
256 '''Return a policy statefulentity of this node is derived from.'''
257 if not hasattr(self, 'defs'):
259 ppolicy_entity = self.derived_from(self.defs)
261 return PolicyType(ppolicy_entity, self.custom_def)
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]
270 '''Return targets.'''
271 return self.targets_list
274 def description(self):
275 return self.policy_description
279 return self.policy_version
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,
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)))
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'))))
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 '
307 % (entry_schema_type.get('type'),