Fix checkstyle violations in sdc/jtosca
[sdc/sdc-tosca.git] / src / main / java / org / onap / sdc / toscaparser / api / elements / GroupType.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.ThreadLocalsHolder;
25
26 import java.util.ArrayList;
27 import java.util.LinkedHashMap;
28 import java.util.Map;
29
30 public class GroupType extends StatefulEntityType {
31
32     private static final String DERIVED_FROM = "derived_from";
33     private static final String VERSION = "version";
34     private static final String METADATA = "metadata";
35     private static final String DESCRIPTION = "description";
36     private static final String PROPERTIES = "properties";
37     private static final String MEMBERS = "members";
38     private static final String INTERFACES = "interfaces";
39
40     private static final String[] SECTIONS = {
41             DERIVED_FROM, VERSION, METADATA, DESCRIPTION, PROPERTIES, MEMBERS, INTERFACES};
42
43     private String groupType;
44     private LinkedHashMap<String, Object> customDef;
45     private String groupDescription;
46     private String groupVersion;
47     //private LinkedHashMap<String,Object> groupProperties;
48     //private ArrayList<String> groupMembers;
49     private LinkedHashMap<String, Object> metaData;
50
51     @SuppressWarnings("unchecked")
52     public GroupType(String groupType, LinkedHashMap<String, Object> customDef) {
53         super(groupType, GROUP_PREFIX, customDef);
54
55         this.groupType = groupType;
56         this.customDef = customDef;
57         validateFields();
58         if (defs != null) {
59             groupDescription = (String) defs.get(DESCRIPTION);
60             groupVersion = (String) defs.get(VERSION);
61             //groupProperties = (LinkedHashMap<String,Object>)defs.get(PROPERTIES);
62             //groupMembers = (ArrayList<String>)defs.get(MEMBERS);
63             Object mdo = defs.get(METADATA);
64             if (mdo instanceof LinkedHashMap) {
65                 metaData = (LinkedHashMap<String, Object>) mdo;
66             } else {
67                 metaData = null;
68             }
69
70             if (metaData != null) {
71                 validateMetadata(metaData);
72             }
73         }
74     }
75
76     public GroupType getParentType() {
77         // Return a group statefulentity of this entity is derived from.
78         if (defs == null) {
79             return null;
80         }
81         String pgroupEntity = derivedFrom(defs);
82         if (pgroupEntity != null) {
83             return new GroupType(pgroupEntity, customDef);
84         }
85         return null;
86     }
87
88     public String getDescription() {
89         return groupDescription;
90     }
91
92     public String getVersion() {
93         return groupVersion;
94     }
95
96     @SuppressWarnings("unchecked")
97     public LinkedHashMap<String, Object> getInterfaces() {
98         Object ifo = getValue(INTERFACES, null, false);
99         if (ifo instanceof LinkedHashMap) {
100             return (LinkedHashMap<String, Object>) ifo;
101         }
102         return new LinkedHashMap<String, Object>();
103     }
104
105     private void validateFields() {
106         if (defs != null) {
107             for (String name : defs.keySet()) {
108                 boolean bFound = false;
109                 for (String sect : SECTIONS) {
110                     if (name.equals(sect)) {
111                         bFound = true;
112                         break;
113                     }
114                 }
115                 if (!bFound) {
116                     ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE120", String.format(
117                             "UnknownFieldError: Group Type \"%s\" contains unknown field \"%s\"",
118                             groupType, name)));
119                 }
120             }
121         }
122     }
123
124     @SuppressWarnings("unchecked")
125     private void validateMetadata(LinkedHashMap<String, Object> metadata) {
126         String mtt = (String) metadata.get("type");
127         if (mtt != null && !mtt.equals("map") && !mtt.equals("tosca:map")) {
128             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE121", String.format(
129                     "InvalidTypeError: \"%s\" defined in group for metadata is invalid",
130                     mtt)));
131         }
132         for (String entrySchema : metadata.keySet()) {
133             Object estob = metadata.get(entrySchema);
134             if (estob instanceof LinkedHashMap) {
135                 String est = (String) ((LinkedHashMap<String, Object>) estob).get("type");
136                 if (!est.equals("string")) {
137                     ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE122", String.format(
138                             "InvalidTypeError: \"%s\" defined in group for metadata \"%s\" is invalid",
139                             est, entrySchema)));
140                 }
141             }
142         }
143     }
144
145     public String getType() {
146         return groupType;
147     }
148
149     @SuppressWarnings("unchecked")
150     public ArrayList<CapabilityTypeDef> getCapabilitiesObjects() {
151         // Return a list of capability objects
152         ArrayList<CapabilityTypeDef> typecapabilities = new ArrayList<>();
153         LinkedHashMap<String, Object> caps = (LinkedHashMap<String, Object>) getValue(CAPABILITIES, null, true);
154         if (caps != null) {
155             // 'cname' is symbolic name of the capability
156             // 'cvalue' is a dict { 'type': <capability type name> }
157             for (Map.Entry<String, Object> me : caps.entrySet()) {
158                 String cname = me.getKey();
159                 LinkedHashMap<String, String> cvalue = (LinkedHashMap<String, String>) me.getValue();
160                 String ctype = cvalue.get("type");
161                 CapabilityTypeDef cap = new CapabilityTypeDef(cname, ctype, type, customDef);
162                 typecapabilities.add(cap);
163             }
164         }
165         return typecapabilities;
166     }
167
168     public LinkedHashMap<String, CapabilityTypeDef> getCapabilities() {
169         // Return a dictionary of capability name-objects pairs
170         LinkedHashMap<String, CapabilityTypeDef> caps = new LinkedHashMap<>();
171         for (CapabilityTypeDef ctd : getCapabilitiesObjects()) {
172             caps.put(ctd.getName(), ctd);
173         }
174         return caps;
175     }
176
177 }
178
179 /*python
180
181 from toscaparser.common.exception import ValidationIssueCollector
182 from toscaparser.common.exception import InvalidTypeError
183 from toscaparser.common.exception import UnknownFieldError
184 from toscaparser.elements.statefulentitytype import StatefulEntityType
185
186
187 class GroupType(StatefulEntityType):
188     '''TOSCA built-in group type.'''
189
190     SECTIONS = (DERIVED_FROM, VERSION, METADATA, DESCRIPTION, PROPERTIES,
191                 MEMBERS, INTERFACES) = \
192                ("derived_from", "version", "metadata", "description",
193                 "properties", "members", "interfaces")
194
195     def __init__(self, grouptype, custom_def=None):
196         super(GroupType, self).__init__(grouptype, self.GROUP_PREFIX,
197                                         custom_def)
198         self.custom_def = custom_def
199         self.grouptype = grouptype
200         self._validate_fields()
201         self.group_description = None
202         if self.DESCRIPTION in self.defs:
203             self.group_description = self.defs[self.DESCRIPTION]
204
205         self.group_version = None
206         if self.VERSION in self.defs:
207             self.group_version = self.defs[self.VERSION]
208
209         self.group_properties = None
210         if self.PROPERTIES in self.defs:
211             self.group_properties = self.defs[self.PROPERTIES]
212
213         self.group_members = None
214         if self.MEMBERS in self.defs:
215             self.group_members = self.defs[self.MEMBERS]
216
217         if self.METADATA in self.defs:
218             self.meta_data = self.defs[self.METADATA]
219             self._validate_metadata(self.meta_data)
220
221     @property
222     def parent_type(self):
223         '''Return a group statefulentity of this entity is derived from.'''
224         if not hasattr(self, 'defs'):
225             return None
226         pgroup_entity = self.derived_from(self.defs)
227         if pgroup_entity:
228             return GroupType(pgroup_entity, self.custom_def)
229
230     @property
231     def description(self):
232         return self.group_description
233
234     @property
235     def version(self):
236         return self.group_version
237
238     @property
239     def interfaces(self):
240         return self.get_value(self.INTERFACES)
241
242     def _validate_fields(self):
243         if self.defs:
244             for name in self.defs.keys():
245                 if name not in self.SECTIONS:
246                     ValidationIssueCollector.appendException(
247                         UnknownFieldError(what='Group Type %s'
248                                           % self.grouptype, field=name))
249
250     def _validate_metadata(self, meta_data):
251         if not meta_data.get('type') in ['map', 'tosca:map']:
252             ValidationIssueCollector.appendException(
253                 InvalidTypeError(what='"%s" defined in group for '
254                                  'metadata' % (meta_data.get('type'))))
255         for entry_schema, entry_schema_type in meta_data.items():
256             if isinstance(entry_schema_type, dict) and not \
257                     entry_schema_type.get('type') == 'string':
258                 ValidationIssueCollector.appendException(
259                     InvalidTypeError(what='"%s" defined in group for '
260                                      'metadata "%s"'
261                                      % (entry_schema_type.get('type'),
262                                         entry_schema)))
263 */