Fix checkstyle violations in sdc/jtosca
[sdc/sdc-tosca.git] / src / main / java / org / onap / sdc / toscaparser / api / elements / ScalarUnit.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 import org.onap.sdc.toscaparser.api.utils.ValidateUtils;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import java.util.HashMap;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 public abstract class ScalarUnit {
34
35     private static Logger log = LoggerFactory.getLogger(ScalarUnit.class.getName());
36
37     private static final String SCALAR_UNIT_SIZE = "scalar-unit.size";
38     private static final String SCALAR_UNIT_FREQUENCY = "scalar-unit.frequency";
39     private static final String SCALAR_UNIT_TIME = "scalar-unit.time";
40
41     public static final String[] SCALAR_UNIT_TYPES = {
42             SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME
43     };
44
45     private Object value;
46     private HashMap<String, Object> scalarUnitDict;
47     private String scalarUnitDefault;
48
49     public ScalarUnit(Object value) {
50         this.value = value;
51         scalarUnitDict = new HashMap<>();
52         scalarUnitDefault = "";
53     }
54
55     void putToScalarUnitDict(String key, Object value) {
56         scalarUnitDict.put(key, value);
57     }
58
59     void setScalarUnitDefault(String scalarUnitDefault) {
60         this.scalarUnitDefault = scalarUnitDefault;
61     }
62
63     private String checkUnitInScalarStandardUnits(String inputUnit) {
64         // Check whether the input unit is following specified standard
65
66         // If unit is not following specified standard, convert it to standard
67         // unit after displaying a warning message.
68
69         if (scalarUnitDict.get(inputUnit) != null) {
70             return inputUnit;
71         } else {
72             for (String key : scalarUnitDict.keySet()) {
73                 if (key.toUpperCase().equals(inputUnit.toUpperCase())) {
74                     log.debug("ScalarUnit - checkUnitInScalarStandardUnits - \n"
75                                     + "The unit {} does not follow scalar unit standards\n"
76                                     + "using {} instead",
77                             inputUnit, key);
78                     return key;
79                 }
80             }
81             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE007", String.format(
82                     "'The unit \"%s\" is not valid. Valid units are \n%s",
83                     inputUnit, scalarUnitDict.keySet().toString())));
84             return inputUnit;
85         }
86     }
87
88     public Object validateScalarUnit() {
89         Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)");
90         Matcher matcher = pattern.matcher(value.toString());
91         if (matcher.find()) {
92             ValidateUtils.strToNum(matcher.group(1));
93             String scalarUnit = checkUnitInScalarStandardUnits(matcher.group(2));
94             value = matcher.group(1) + " " + scalarUnit;
95         } else {
96             ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE134", String.format(
97                     "ValueError: \"%s\" is not a valid scalar-unit", value.toString())));
98         }
99         return value;
100     }
101
102     public double getNumFromScalarUnit(String unit) {
103         if (unit != null) {
104             unit = checkUnitInScalarStandardUnits(unit);
105         } else {
106             unit = scalarUnitDefault;
107         }
108         Pattern pattern = Pattern.compile("([0-9.]+)\\s*(\\w+)");
109         Matcher matcher = pattern.matcher(value.toString());
110         if (matcher.find()) {
111             final double minimalNum = 0.0000000000001;
112
113             ValidateUtils.strToNum(matcher.group(1));
114             String scalarUnit = checkUnitInScalarStandardUnits(matcher.group(2));
115             value = matcher.group(1) + " " + scalarUnit;
116             Object on1 = ValidateUtils.strToNum(matcher.group(1)) != null ? ValidateUtils.strToNum(matcher.group(1)) : 0;
117             Object on2 = scalarUnitDict.get(matcher.group(2)) != null ? scalarUnitDict.get(matcher.group(2)) : 0;
118             Object on3 = scalarUnitDict.get(unit) != null ? scalarUnitDict.get(unit) : 0;
119
120             Double n1 = new Double(on1.toString());
121             Double n2 = new Double(on2.toString());
122             Double n3 = new Double(on3.toString());
123             double converted = n1 * n2 / n3;
124
125             if (Math.abs(converted - Math.round(converted)) < minimalNum) {
126                 converted = Math.round(converted);
127             }
128             return converted;
129         }
130         return 0.0;
131     }
132
133     private static HashMap<String, String> scalarUnitMapping = getScalarUnitMappings();
134
135     private static HashMap<String, String> getScalarUnitMappings() {
136         HashMap<String, String> map = new HashMap<>();
137         map.put(SCALAR_UNIT_FREQUENCY, "ScalarUnitFrequency");
138         map.put(SCALAR_UNIT_SIZE, "ScalarUnitSize");
139         map.put(SCALAR_UNIT_TIME, "ScalarUnit_Time");
140         return map;
141     }
142
143     public static ScalarUnit getScalarunitClass(String type, Object val) {
144         if (type.equals(SCALAR_UNIT_SIZE)) {
145             return new ScalarUnitSize(val);
146         } else if (type.equals(SCALAR_UNIT_TIME)) {
147             return new ScalarUnitTime(val);
148         } else if (type.equals(SCALAR_UNIT_FREQUENCY)) {
149             return new ScalarUnitFrequency(val);
150         }
151         return null;
152     }
153
154     public static double getScalarunitValue(String type, Object value, String unit) {
155         if (type.equals(SCALAR_UNIT_SIZE)) {
156             return (new ScalarUnitSize(value)).getNumFromScalarUnit(unit);
157         }
158         if (type.equals(SCALAR_UNIT_TIME)) {
159             return (new ScalarUnitTime(value)).getNumFromScalarUnit(unit);
160         }
161         if (type.equals(SCALAR_UNIT_FREQUENCY)) {
162             return (new ScalarUnitFrequency(value)).getNumFromScalarUnit(unit);
163         }
164         ThreadLocalsHolder.getCollector().appendValidationIssue(new JToscaValidationIssue("JE135", String.format(
165                 "TypeError: \"%s\" is not a valid scalar-unit type", type)));
166         return 0.0;
167     }
168
169 }
170
171 /*python
172
173 from toscaparser.common.exception import ValidationIssueCollector
174 from toscaparser.utils.gettextutils import _
175 from toscaparser.utils import validateutils
176
177 log = logging.getLogger('tosca')
178
179
180 class ScalarUnit(object):
181     '''Parent class for scalar-unit type.'''
182
183     SCALAR_UNIT_TYPES = (
184         SCALAR_UNIT_SIZE, SCALAR_UNIT_FREQUENCY, SCALAR_UNIT_TIME
185     ) = (
186         'scalar-unit.size', 'scalar-unit.frequency', 'scalar-unit.time'
187     )
188
189     def __init__(self, value):
190         self.value = value
191
192     def _check_unit_in_scalar_standard_units(self, input_unit):
193         """Check whether the input unit is following specified standard
194
195         If unit is not following specified standard, convert it to standard
196         unit after displaying a warning message.
197         """
198         if input_unit in self.scalarUnitDict.keys():
199             return input_unit
200         else:
201             for key in self.scalarUnitDict.keys():
202                 if key.upper() == input_unit.upper():
203                     log.warning(_('The unit "%(unit)s" does not follow '
204                                   'scalar unit standards; using "%(key)s" '
205                                   'instead.') % {'unit': input_unit,
206                                                  'key': key})
207                     return key
208             msg = (_('The unit "%(unit)s" is not valid. Valid units are '
209                      '"%(valid_units)s".') %
210                    {'unit': input_unit,
211                     'valid_units': sorted(self.scalarUnitDict.keys())})
212             ValidationIssueCollector.appendException(ValueError(msg))
213
214     def validate_scalar_unit(self):
215         regex = re.compile('([0-9.]+)\s*(\w+)')
216         try:
217             result = regex.match(str(self.value)).groups()
218             validateutils.str_to_num(result[0])
219             scalar_unit = self._check_unit_in_scalar_standard_units(result[1])
220             self.value = ' '.join([result[0], scalar_unit])
221             return self.value
222
223         except Exception:
224             ValidationIssueCollector.appendException(
225                 ValueError(_('"%s" is not a valid scalar-unit.')
226                            % self.value))
227
228     def get_num_from_scalar_unit(self, unit=None):
229         if unit:
230             unit = self._check_unit_in_scalar_standard_units(unit)
231         else:
232             unit = self.scalarUnitDefault
233         self.validate_scalar_unit()
234
235         regex = re.compile('([0-9.]+)\s*(\w+)')
236         result = regex.match(str(self.value)).groups()
237         converted = (float(validateutils.str_to_num(result[0]))
238                      * self.scalarUnitDict[result[1]]
239                      / self.scalarUnitDict[unit])
240         if converted - int(converted) < 0.0000000000001:
241             converted = int(converted)
242         return converted
243
244
245 class ScalarUnit_Size(ScalarUnit):
246
247     scalarUnitDefault = 'B'
248     scalarUnitDict = {'B': 1, 'kB': 1000, 'KiB': 1024, 'MB': 1000000,
249                         'MiB': 1048576, 'GB': 1000000000,
250                         'GiB': 1073741824, 'TB': 1000000000000,
251                         'TiB': 1099511627776}
252
253
254 class ScalarUnit_Time(ScalarUnit):
255
256     scalarUnitDefault = 'ms'
257     scalarUnitDict = {'d': 86400, 'h': 3600, 'm': 60, 's': 1,
258                         'ms': 0.001, 'us': 0.000001, 'ns': 0.000000001}
259
260
261 class ScalarUnit_Frequency(ScalarUnit):
262
263     scalarUnitDefault = 'GHz'
264     scalarUnitDict = {'Hz': 1, 'kHz': 1000,
265                         'MHz': 1000000, 'GHz': 1000000000}
266
267
268 scalarunit_mapping = {
269     ScalarUnit.SCALAR_UNIT_FREQUENCY: ScalarUnit_Frequency,
270     ScalarUnit.SCALAR_UNIT_SIZE: ScalarUnit_Size,
271     ScalarUnit.SCALAR_UNIT_TIME: ScalarUnit_Time,
272     }
273
274
275 def get_scalarunit_class(type):
276     return scalarunit_mapping.get(type)
277
278
279 def get_scalarunit_value(type, value, unit=None):
280     if type in ScalarUnit.SCALAR_UNIT_TYPES:
281         ScalarUnit_Class = get_scalarunit_class(type)
282         return (ScalarUnit_Class(value).
283                 get_num_from_scalar_unit(unit))
284     else:
285         ValidationIssueCollector.appendException(
286             TypeError(_('"%s" is not a valid scalar-unit type.') % type))
287 */