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.constraints;
23 import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue;
24 import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder;
26 import java.util.Arrays;
27 import java.util.Date;
29 import java.util.ArrayList;
31 public class InRange extends Constraint {
32 // Constraint class for "in_range"
34 //Constrains a property or parameter to a value in range of (inclusive)
35 //the two values declared.
37 private static final String UNBOUNDED = "UNBOUNDED";
39 private Object min, max;
41 protected void setValues() {
43 setConstraintKey(IN_RANGE);
45 // timestamps are loaded as Date objects
46 addValidTypes(Arrays.asList("Integer", "Double", "Float", "String", "Date"));
47 //validTypes.add("datetime.date");
48 //validTypes.add("datetime.time");
49 //validTypes.add("datetime.datetime");
51 validPropTypes.add(Schema.INTEGER);
52 validPropTypes.add(Schema.FLOAT);
53 validPropTypes.add(Schema.TIMESTAMP);
54 validPropTypes.add(Schema.SCALAR_UNIT_SIZE);
55 validPropTypes.add(Schema.SCALAR_UNIT_FREQUENCY);
56 validPropTypes.add(Schema.SCALAR_UNIT_TIME);
57 validPropTypes.add(Schema.RANGE);
61 @SuppressWarnings("unchecked")
62 public InRange(String name, String type, Object c) {
65 if (!(constraintValue instanceof ArrayList) || ((ArrayList<Object>) constraintValue).size() != 2) {
66 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE106", "InvalidSchemaError: The property \"in_range\" expects a list"));
70 ArrayList<Object> alcv = (ArrayList<Object>) constraintValue;
71 String msg = "The property \"in_range\" expects comparable values";
72 for (Object vo : alcv) {
73 if (!validTypes.contains(vo.getClass().getSimpleName())) {
74 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE107", "InvalidSchemaError: " + msg));
76 // The only string we allow for range is the special value 'UNBOUNDED'
77 if ((vo instanceof String) && !((String) vo).equals(UNBOUNDED)) {
78 ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE108", "InvalidSchemaError: " + msg));
87 protected boolean isValid(Object value) {
90 if (value instanceof Date) {
91 if (min instanceof Date && max instanceof Date) {
92 return !((Date) value).before((Date) min)
93 && !((Date) value).after((Date) max);
98 Double dvalue = new Double(value.toString());
99 if (!(min instanceof String)) {
100 if (dvalue < new Double(min.toString())) {
103 } else if (!((String) min).equals(UNBOUNDED)) {
106 if (!(max instanceof String)) {
107 if (dvalue > new Double(max.toString())) {
110 } else if (!((String) max).equals(UNBOUNDED)) {
117 protected String errMsg(Object value) {
118 return String.format("The value \"%s\" of property \"%s\" is out of range \"(min:%s, max:%s)\"",
119 valueMsg, propertyName, min.toString(), max.toString());
126 class InRange(Constraint):
127 """Constraint class for "in_range"
129 Constrains a property or parameter to a value in range of (inclusive)
130 the two values declared.
132 UNBOUNDED = 'UNBOUNDED'
134 constraint_key = Constraint.IN_RANGE
136 valid_types = (int, float, datetime.date,
137 datetime.time, datetime.datetime, str)
139 valid_prop_types = (Schema.INTEGER, Schema.FLOAT, Schema.TIMESTAMP,
140 Schema.SCALAR_UNIT_SIZE, Schema.SCALAR_UNIT_FREQUENCY,
141 Schema.SCALAR_UNIT_TIME, Schema.RANGE)
143 def __init__(self, property_name, property_type, constraint):
144 super(InRange, self).__init__(property_name, property_type, constraint)
145 if(not isinstance(self.constraint_value, collections.Sequence) or
146 (len(constraint[self.IN_RANGE]) != 2)):
147 ValidationIssueCollector.appendException(
148 InvalidSchemaError(message=_('The property "in_range" '
151 msg = _('The property "in_range" expects comparable values.')
152 for value in self.constraint_value:
153 if not isinstance(value, self.valid_types):
154 ValidationIssueCollector.appendException(
155 InvalidSchemaError(message=msg))
156 # The only string we allow for range is the special value
158 if(isinstance(value, str) and value != self.UNBOUNDED):
159 ValidationIssueCollector.appendException(
160 InvalidSchemaError(message=msg))
162 self.min = self.constraint_value[0]
163 self.max = self.constraint_value[1]
165 def _is_valid(self, value):
166 if not isinstance(self.min, str):
169 elif self.min != self.UNBOUNDED:
171 if not isinstance(self.max, str):
174 elif self.max != self.UNBOUNDED:
178 def _err_msg(self, value):
179 return (_('The value "%(pvalue)s" of property "%(pname)s" is out of '
180 'range "(min:%(vmin)s, max:%(vmax)s)".') %
181 dict(pname=self.property_name,
182 pvalue=self.value_msg,
183 vmin=self.constraint_value_msg[0],
184 vmax=self.constraint_value_msg[1]))