summaryrefslogtreecommitdiffstats
path: root/jtosca/src/main/java/org/openecomp/sdc/toscaparser/utils/ValidateUtils.java
blob: 7f9fac75f299c1b07f24c599ea5f4d4888157e20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package org.openecomp.sdc.toscaparser.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;

import org.openecomp.sdc.toscaparser.common.ExceptionCollector;

public class ValidateUtils {
	
	private static final String RANGE_UNBOUNDED = "UNBOUNDED";

	public static Object strToNum(Object value) {
	    // Convert a string representation of a number into a numeric type
	    // tODO(TBD) we should not allow numeric values in, input should be str
		if(value instanceof Number) {
			return value;
		}
		if(!(value instanceof String)) {
			
		}
		try {
			return Integer.parseInt((String)value);
		}
		catch(NumberFormatException e) {
		}
		try {
			return Float.parseFloat((String)value);
		}
		catch(Exception e) {
		}
		return null;
	}
	
	public static Object validateNumeric(Object value) {
		if(!(value instanceof Number)) {
	        ExceptionCollector.appendException(String.format(
		            "ValueError: \"%s\" is not a numeric",value.toString()));
		}
		return value;
	}

	public static Object validateInteger(Object value) {
		if(!(value instanceof Integer)) {
			// allow "true" and "false"
			if(value instanceof Boolean) {
				return (Boolean)value ? 1 : 0;
			}
            ExceptionCollector.appendException(String.format(
	            "ValueError: \"%s\" is not an integer",value.toString()));
		}
	    return value;
	}

	public static Object validateFloat(Object value) {
		if(!(value instanceof Float || value instanceof Double)) {
            ExceptionCollector.appendException(String.format(
	            "ValueError: \"%s\" is not a float",value.toString()));
		}
	    return value;
	}

	public static Object validateString(Object value) {
		if(!(value instanceof String)) {
            ExceptionCollector.appendException(String.format(
	            "ValueError: \'%s\' is not a string",value.toString()));
		}
	    return value;
	}

	public static Object validateList(Object value) {
		if(!(value instanceof ArrayList)) {
            ExceptionCollector.appendException(String.format(
	            "ValueError: \"%s\" is not a list",value.toString()));
		}
	    return value;
	}

	
	@SuppressWarnings("unchecked")
	public static Object validateRange(Object range) {
	    // list class check
	    validateList(range);
	    // validate range list has a min and max
	    if(range instanceof ArrayList && ((ArrayList<Object>)range).size() != 2) {
	        ExceptionCollector.appendException(String.format(
	            "ValueError: \"%s\" is not a valid range",range.toString()));
	        // too dangerous to continue...
	        return range;
	    }
	    // validate min and max are numerics or the keyword UNBOUNDED
	    boolean minTest = false;
	    boolean maxTest = false;
	    Object r0 = ((ArrayList<Object>)range).get(0);
	    Object r1 = ((ArrayList<Object>)range).get(1);
	    
	    if(!(r0 instanceof Integer) && !(r0 instanceof Float) ||
	       !(r1 instanceof Integer) && !(r1 instanceof Float)) {
	        ExceptionCollector.appendException(String.format(
		            "ValueError: \"%s\" is not a valid range",range.toString()));
		        // too dangerous to continue...
	        return range;
	    }
		
	    Float min = 0.0F;
	    Float max = 0.0F;
	    if(r0 instanceof String && ((String)r0).equals(RANGE_UNBOUNDED)) {
	    	minTest = true;
	    }
	    else {
	    	min = r0 instanceof Integer ? ((Integer)r0).floatValue() : (Float)r0;
	    }
	    if(r1 instanceof String && ((String)r1).equals(RANGE_UNBOUNDED)) {
	    	maxTest = true;
	    }
	    else {
	    	max = r1 instanceof Integer ? ((Integer)r1).floatValue() : (Float)r1;
	    }
	    
	    // validate the max > min (account for UNBOUNDED)
	    if(!minTest && !maxTest) {
	        // Note: min == max is allowed
	        if(min > max) {
	            ExceptionCollector.appendException(String.format(
	                "ValueError:\"%s\" is not a valid range",range.toString()));
	        }
	    }
	    return range;
	}

	@SuppressWarnings("unchecked")
	public static Object validateValueInRange(Object value,Object range,String propName) {
		// verify all 3 are numeric and convert to Floats
		if(!(value instanceof Integer || value instanceof Float)) {
            ExceptionCollector.appendException(String.format(
	                "ValueError: validateInRange: \"%s\" is not a number",range.toString()));
            return value;
	    }
		Float fval = value instanceof Integer ? ((Integer)value).floatValue() : (Float)value;
		
		//////////////////////////
	    //"validateRange(range);"
		//////////////////////////
	    // better safe than sorry...
	    // validate that range list has a min and max
	    if(range instanceof ArrayList && ((ArrayList<Object>)range).size() != 2) {
	        ExceptionCollector.appendException(String.format(
	            "ValueError: \"%s\" is not a valid range",range.toString()));
	        // too dangerous to continue...
	        return value;
	    }
	    // validate min and max are numerics or the keyword UNBOUNDED
	    boolean minTest = false;
	    boolean maxTest = false;
	    Object r0 = ((ArrayList<Object>)range).get(0);
	    Object r1 = ((ArrayList<Object>)range).get(1);
	    
	    if(!(r0 instanceof Integer) && !(r0 instanceof Float) ||
	       !(r1 instanceof Integer) && !(r1 instanceof Float)) {
	        ExceptionCollector.appendException(String.format(
		            "ValueError: \"%s\" is not a valid range",range.toString()));
		        // too dangerous to continue...
	        return value;
	    }
		
	    Float min = 0.0F;
	    Float max = 0.0F;
	    if(r0 instanceof String && ((String)r0).equals(RANGE_UNBOUNDED)) {
	    	minTest = true;
	    }
	    else {
	    	min = r0 instanceof Integer ? ((Integer)r0).floatValue() : (Float)r0;
	    }
	    if(r1 instanceof String && ((String)r1).equals(RANGE_UNBOUNDED)) {
	    	maxTest = true;
	    }
	    else {
	    	max = r1 instanceof Integer ? ((Integer)r1).floatValue() : (Float)r1;
	    }
	    
	    // validate the max > min (account for UNBOUNDED)
	    if(!minTest && !maxTest) {
	        // Note: min == max is allowed
	        if(min > max) {
	            ExceptionCollector.appendException(String.format(
	                "ValueError:\"%s\" is not a valid range",range.toString()));
	        }
	    }
	    // finally...
	    boolean bError = false;
	    //Note: value is valid if equal to min
	    if(!minTest) {
	        if(fval < min) {
	        	bError = true;
	        }
	    }
	    // Note: value is valid if equal to max
	    if(!maxTest) {
	        if(fval > max) {
	        	bError = true;
	        }
	    }
	    if(bError) {
            ExceptionCollector.appendException(String.format(
	                "RangeValueError: Property \"%s\", \"%s\" not in range [\"%s\" - \"%s\"",
	                propName,value.toString(),r0.toString(),r1.toString()));
	    }
	    return value;
	}
	
	public static Object validateMap(Object ob) {
		if(!(ob instanceof LinkedHashMap)) {
	        ExceptionCollector.appendException(String.format(
	            "ValueError\"%s\" is not a map.",ob.toString()));
		}
	    return ob;
	}

	public static Object validateBoolean(Object value) {
		if(value instanceof Boolean) { 
			return value;
		}
		if(value instanceof String) {  
			String normalized = ((String)value).toLowerCase();
			if(normalized.equals("true") || normalized.equals("false")) {
				return normalized.equals("true");
			}
		}
	    ExceptionCollector.appendException(String.format(
		        "ValueError: \"%s\" is not a boolean",value.toString()));
	    return value;
	}

	public static Object validateTimestamp(Object value) {
		/*
	    try:
	        # Note: we must return our own exception message
	        # as dateutil's parser returns different types / values on
	        # different systems. OSX, for example, returns a tuple
	        # containing a different error message than Linux
	        dateutil.parser.parse(value)
	    except Exception as e:
	        original_err_msg = str(e)
	        log.error(original_err_msg)
	        ExceptionCollector.appendException(
	            ValueError(_('"%(val)s" is not a valid timestamp. "%(msg)s"') %
	                       {'val': value, 'msg': original_err_msg}))
		*/
		
		// timestamps are loaded as Date objects by the YAML parser
		if(!(value instanceof Date)) {
	        ExceptionCollector.appendException(String.format(
		        "ValueError: \"%s\" is not a valid timestamp",
		        value.toString()));
			
		}
		return value;
	}
	
}

/*python

from toscaparser.elements import constraints
from toscaparser.common.exception import ExceptionCollector
from toscaparser.common.exception import InvalidTOSCAVersionPropertyException
from toscaparser.common.exception import RangeValueError
from toscaparser.utils.gettextutils import _

log = logging.getLogger('tosca')

RANGE_UNBOUNDED = 'UNBOUNDED'


def str_to_num(value):
    '''Convert a string representation of a number into a numeric type.'''
    # tODO(TBD) we should not allow numeric values in, input should be str
    if isinstance(value, numbers.Number):
        return value
    try:
        return int(value)
    except ValueError:
        return float(value)


def validate_numeric(value):
    if not isinstance(value, numbers.Number):
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a numeric.') % value))
    return value


def validate_integer(value):
    if not isinstance(value, int):
        try:
            value = int(value)
        except Exception:
            ExceptionCollector.appendException(
                ValueError(_('"%s" is not an integer.') % value))
    return value


def validate_float(value):
    if not isinstance(value, float):
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a float.') % value))
    return value


def validate_string(value):
    if not isinstance(value, six.string_types):
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a string.') % value))
    return value


def validate_list(value):
    if not isinstance(value, list):
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a list.') % value))
    return value


def validate_range(range):
    # list class check
    validate_list(range)
    # validate range list has a min and max
    if len(range) != 2:
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a valid range.') % range))
    # validate min and max are numerics or the keyword UNBOUNDED
    min_test = max_test = False
    if not range[0] == RANGE_UNBOUNDED:
        min = validate_numeric(range[0])
    else:
        min_test = True
    if not range[1] == RANGE_UNBOUNDED:
        max = validate_numeric(range[1])
    else:
        max_test = True
    # validate the max > min (account for UNBOUNDED)
    if not min_test and not max_test:
        # Note: min == max is allowed
        if min > max:
            ExceptionCollector.appendException(
                ValueError(_('"%s" is not a valid range.') % range))

    return range


def validate_value_in_range(value, range, prop_name):
    validate_numeric(value)
    validate_range(range)

    # Note: value is valid if equal to min
    if range[0] != RANGE_UNBOUNDED:
        if value < range[0]:
            ExceptionCollector.appendException(
                RangeValueError(pname=prop_name,
                                pvalue=value,
                                vmin=range[0],
                                vmax=range[1]))
    # Note: value is valid if equal to max
    if range[1] != RANGE_UNBOUNDED:
        if value > range[1]:
            ExceptionCollector.appendException(
                RangeValueError(pname=prop_name,
                                pvalue=value,
                                vmin=range[0],
                                vmax=range[1]))
    return value


def validate_map(value):
    if not isinstance(value, collections.Mapping):
        ExceptionCollector.appendException(
            ValueError(_('"%s" is not a map.') % value))
    return value


def validate_boolean(value):
    if isinstance(value, bool):
        return value

    if isinstance(value, str):
        normalised = value.lower()
        if normalised in ['true', 'false']:
            return normalised == 'true'

    ExceptionCollector.appendException(
        ValueError(_('"%s" is not a boolean.') % value))


def validate_timestamp(value):
    try:
        # Note: we must return our own exception message
        # as dateutil's parser returns different types / values on
        # different systems. OSX, for example, returns a tuple
        # containing a different error message than Linux
        dateutil.parser.parse(value)
    except Exception as e:
        original_err_msg = str(e)
        log.error(original_err_msg)
        ExceptionCollector.appendException(
            ValueError(_('"%(val)s" is not a valid timestamp. "%(msg)s"') %
                       {'val': value, 'msg': original_err_msg}))
    return

*/