Fix checkstyle violations in sdc/jtosca
[sdc/sdc-tosca.git] / src / main / java / org / onap / sdc / toscaparser / api / elements / constraints / InRange.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 org.onap.sdc.toscaparser.api.common.JToscaValidationIssue;
24 import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder;
25
26 import java.util.Arrays;
27 import java.util.Date;
28
29 import java.util.ArrayList;
30
31 public class InRange extends Constraint {
32     // Constraint class for "in_range"
33
34     //Constrains a property or parameter to a value in range of (inclusive)
35     //the two values declared.
36
37     private static final String UNBOUNDED = "UNBOUNDED";
38
39     private Object min, max;
40
41     protected void setValues() {
42
43         setConstraintKey(IN_RANGE);
44
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");
50
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);
58
59     }
60
61     @SuppressWarnings("unchecked")
62     public InRange(String name, String type, Object c) {
63         super(name, type, c);
64
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"));
67
68         }
69
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));
75             }
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));
79             }
80         }
81         min = alcv.get(0);
82         max = alcv.get(1);
83
84     }
85
86     @Override
87     protected boolean isValid(Object value) {
88
89         // timestamps
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);
94             }
95             return false;
96         }
97
98         Double dvalue = new Double(value.toString());
99         if (!(min instanceof String)) {
100             if (dvalue < new Double(min.toString())) {
101                 return false;
102             }
103         } else if (!((String) min).equals(UNBOUNDED)) {
104             return false;
105         }
106         if (!(max instanceof String)) {
107             if (dvalue > new Double(max.toString())) {
108                 return false;
109             }
110         } else if (!((String) max).equals(UNBOUNDED)) {
111             return false;
112         }
113         return true;
114     }
115
116     @Override
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());
120     }
121
122 }
123
124 /*python
125
126 class InRange(Constraint):
127     """Constraint class for "in_range"
128
129     Constrains a property or parameter to a value in range of (inclusive)
130     the two values declared.
131     """
132     UNBOUNDED = 'UNBOUNDED'
133
134     constraint_key = Constraint.IN_RANGE
135
136     valid_types = (int, float, datetime.date,
137                    datetime.time, datetime.datetime, str)
138
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)
142
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" '
149                                              'expects a list.')))
150
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
157             # 'UNBOUNDED'
158             if(isinstance(value, str) and value != self.UNBOUNDED):
159                 ValidationIssueCollector.appendException(
160                     InvalidSchemaError(message=msg))
161
162         self.min = self.constraint_value[0]
163         self.max = self.constraint_value[1]
164
165     def _is_valid(self, value):
166         if not isinstance(self.min, str):
167             if value < self.min:
168                 return False
169         elif self.min != self.UNBOUNDED:
170             return False
171         if not isinstance(self.max, str):
172             if value > self.max:
173                 return False
174         elif self.max != self.UNBOUNDED:
175             return False
176         return True
177
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]))
185
186 */