Fix checkstyle violations in sdc/jtosca
[sdc/sdc-tosca.git] / src / main / java / org / onap / sdc / toscaparser / api / elements / constraints / Schema.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.constraints;
22
23 import com.google.common.collect.ImmutableMap;
24 import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue;
25 import org.onap.sdc.toscaparser.api.elements.enums.FileSize;
26 import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder;
27
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.LinkedHashMap;
31 import java.util.Map;
32
33
34 public class Schema {
35
36     private static final String TYPE = "type";
37     private static final String REQUIRED = "required";
38     private static final String DESCRIPTION = "description";
39     private static final String DEFAULT = "default";
40     private static final String CONSTRAINTS = "constraints";
41     private static final String STATUS = "status";
42     private static final String ENTRYSCHEMA = "entry_schema";
43     private static final String[] KEYS = {
44             TYPE, REQUIRED, DESCRIPTION, DEFAULT, CONSTRAINTS, ENTRYSCHEMA, STATUS};
45
46     public static final String INTEGER = "integer";
47     public static final String STRING = "string";
48     public static final String BOOLEAN = "boolean";
49     public static final String FLOAT = "float";
50     public static final String RANGE = "range";
51     public static final String NUMBER = "number";
52     public static final String TIMESTAMP = "timestamp";
53     public static final String LIST = "list";
54     public static final String MAP = "map";
55     public static final String SCALAR_UNIT_SIZE = "scalar-unit.size";
56     public static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency";
57     public static final String SCALAR_UNIT_TIME = "scalar-unit.time";
58     public static final String VERSION = "version";
59     public static final String PORTDEF = "PortDef";
60     public static final String PORTSPEC = "PortSpec"; //??? PortSpec.SHORTNAME
61     public static final String JSON = "json";
62
63     public static final String[] PROPERTY_TYPES = {
64             INTEGER, STRING, BOOLEAN, FLOAT, RANGE, NUMBER, TIMESTAMP, LIST, MAP,
65             SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME,
66             VERSION, PORTDEF, PORTSPEC, JSON};
67
68     public static final String[] SIMPLE_PROPERTY_TYPES = {
69             INTEGER, STRING, BOOLEAN, FLOAT, RANGE, NUMBER, TIMESTAMP,
70             SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME,
71             VERSION};
72
73     @SuppressWarnings("unused")
74     private static final String SCALAR_UNIT_SIZE_DEFAULT = "B";
75
76     private static Map<String, Long> scalarUnitSizeDict = ImmutableMap.<String, Long>builder()
77             .put("B", FileSize.B)
78             .put("KB", FileSize.KB)
79             .put("MB", FileSize.MB)
80             .put("GB", FileSize.GB)
81             .put("TB", FileSize.TB)
82             .put("KIB", FileSize.KIB)
83             .put("MIB", FileSize.MIB)
84             .put("GIB", FileSize.GIB)
85             .put("TIB", FileSize.TIB)
86             .build();
87
88
89     private String name;
90     private LinkedHashMap<String, Object> schema;
91     private int len;
92     private ArrayList<Constraint> constraintsList;
93
94
95     public Schema(String name, LinkedHashMap<String, Object> schemaDict) {
96         this.name = name;
97
98         if (!(schemaDict instanceof LinkedHashMap)) {
99             //msg = (_('Schema definition of "%(pname)s" must be a dict.')
100             //       % dict(pname=name))
101             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE117", String.format(
102                     "InvalidSchemaError: Schema definition of \"%s\" must be a dict", this.name)));
103         }
104
105         if (schemaDict.get("type") == null) {
106             //msg = (_('Schema definition of "%(pname)s" must have a "type" '
107             //         'attribute.') % dict(pname=name))
108             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE118", String.format(
109                     "InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute", this.name)));
110         }
111
112         schema = schemaDict;
113         len = 0; //??? None
114         constraintsList = new ArrayList<>();
115     }
116
117     public String getType() {
118         return (String) schema.get(TYPE);
119     }
120
121     public boolean isRequired() {
122         return (boolean) schema.getOrDefault(REQUIRED, true);
123     }
124
125     public String getDescription() {
126         return (String) schema.getOrDefault(DESCRIPTION, "");
127     }
128
129     public Object getDefault() {
130         return schema.get(DEFAULT);
131     }
132
133     public String getStatus() {
134         return (String) schema.getOrDefault(STATUS, "");
135     }
136
137     public static boolean isRequestedTypeSimple(String type) {
138         return Arrays.asList(SIMPLE_PROPERTY_TYPES).contains(type);
139     }
140
141     @SuppressWarnings("unchecked")
142     public ArrayList<Constraint> getConstraints() {
143         if (constraintsList.size() == 0) {
144             Object cob = schema.get(CONSTRAINTS);
145             if (cob instanceof ArrayList) {
146                 ArrayList<Object> constraintSchemata = (ArrayList<Object>) cob;
147                 for (Object ob : constraintSchemata) {
148                     if (ob instanceof LinkedHashMap) {
149                         for (String cClass : ((LinkedHashMap<String, Object>) ob).keySet()) {
150                             Constraint c = Constraint.factory(cClass, name, getType(), ob);
151                             if (c != null) {
152                                 constraintsList.add(c);
153                             } else {
154                                 // error
155                                 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE119", String.format(
156                                         "UnknownFieldError: Constraint type \"%s\" for property \"%s\" is not supported",
157                                         cClass, name)));
158                             }
159                             break;
160                         }
161                     }
162                 }
163             }
164         }
165         return constraintsList;
166     }
167
168     @SuppressWarnings("unchecked")
169     public LinkedHashMap<String, Object> getEntrySchema() {
170         return (LinkedHashMap<String, Object>) schema.get(ENTRYSCHEMA);
171     }
172
173     // Python intrinsic methods...
174
175     // substitute for __getitem__ (aka self[key])
176     public Object getItem(String key) {
177         return schema.get(key);
178     }
179
180     /*
181     def __iter__(self):
182         for k in self.KEYS:
183             try:
184                 self.schema[k]
185             except KeyError:
186                 pass
187             else:
188                 yield k
189     */
190
191     // substitute for __len__ (aka self.len())
192     public int getLen() {
193         int len = 0;
194         for (String k : KEYS) {
195             if (schema.get(k) != null) {
196                 len++;
197             }
198             this.len = len;
199         }
200         return this.len;
201     }
202
203     // getter
204     public LinkedHashMap<String, Object> getSchema() {
205         return schema;
206     }
207
208 }
209
210 /*python
211
212 class Schema(collections.Mapping):
213
214 KEYS = (
215     TYPE, REQUIRED, DESCRIPTION,
216     DEFAULT, CONSTRAINTS, ENTRYSCHEMA, STATUS
217 ) = (
218     'type', 'required', 'description',
219     'default', 'constraints', 'entry_schema', 'status'
220 )
221
222 PROPERTY_TYPES = (
223     INTEGER, STRING, BOOLEAN, FLOAT, RANGE,
224     NUMBER, TIMESTAMP, LIST, MAP,
225     SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME,
226     VERSION, PORTDEF, PORTSPEC
227 ) = (
228     'integer', 'string', 'boolean', 'float', 'range',
229     'number', 'timestamp', 'list', 'map',
230     'scalar-unit.size', 'scalar-unit.frequency', 'scalar-unit.time',
231     'version', 'PortDef', PortSpec.SHORTNAME
232 )
233
234 SCALAR_UNIT_SIZE_DEFAULT = 'B'
235 scalarUnitSizeDict = {'B': 1, 'KB': 1000, 'KIB': 1024, 'MB': 1000000,
236                          'MIB': 1048576, 'GB': 1000000000,
237                          'GIB': 1073741824, 'TB': 1000000000000,
238                          'TIB': 1099511627776}
239
240 def __init__(self, name, schema_dict):
241     self.name = name
242     if not isinstance(schema_dict, collections.Mapping):
243         msg = (_('Schema definition of "%(pname)s" must be a dict.')
244                % dict(pname=name))
245         ValidationIssueCollector.appendException(InvalidSchemaError(message=msg))
246
247     try:
248         schema_dict['type']
249     except KeyError:
250         msg = (_('Schema definition of "%(pname)s" must have a "type" '
251                  'attribute.') % dict(pname=name))
252         ValidationIssueCollector.appendException(InvalidSchemaError(message=msg))
253
254     self.schema = schema_dict
255     self.len = None
256     self.constraints_list = []
257
258 @property
259 def type(self):
260     return self.schema[self.TYPE]
261
262 @property
263 def required(self):
264     return self.schema.get(self.REQUIRED, True)
265
266 @property
267 def description(self):
268     return self.schema.get(self.DESCRIPTION, '')
269
270 @property
271 def default(self):
272     return self.schema.get(self.DEFAULT)
273
274 @property
275 def status(self):
276     return self.schema.get(self.STATUS, '')
277
278 @property
279 def constraints(self):
280     if not self.constraints_list:
281         constraint_schemata = self.schema.get(self.CONSTRAINTS)
282         if constraint_schemata:
283             self.constraints_list = [Constraint(self.name,
284                                                 self.type,
285                                                 cschema)
286                                      for cschema in constraint_schemata]
287     return self.constraints_list
288
289 @property
290 def entry_schema(self):
291     return self.schema.get(self.ENTRYSCHEMA)
292
293 def __getitem__(self, key):
294     return self.schema[key]
295
296 def __iter__(self):
297     for k in self.KEYS:
298         try:
299             self.schema[k]
300         except KeyError:
301             pass
302         else:
303             yield k
304
305 def __len__(self):
306     if self.len is None:
307         self.len = len(list(iter(self)))
308     return self.len
309 */