summaryrefslogtreecommitdiffstats
path: root/dcaedt_validator/checker/src/main/java/org/onap/sdc/dcae/checker/Data.java
blob: 3e85a40293635f5a85ecd2cf8f806ebf15852ab3 (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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.sdc.dcae.checker;

import java.util.Collection;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.EnumSet;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.enums.LogLevel;

/*
 * String -- 'primitive tosca type' converters, used in verifying valuations
 */
public class Data {
	private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();

	private Data() {
	}


	@FunctionalInterface
	public static interface Evaluator {
		public boolean eval(Object theExpr, Map theDef, Checker.CheckContext theCtx);	
	}


  /* data type processing */

	private static Map<String,Type>	typesByName = new HashMap<>();
	static {
	}

	public static Data.Type typeByName(String theName) {
		return typesByName.getOrDefault(theName, userType);
	}

	/* Needs a better name ?? RValue?? 
	 * This is not an rvalue (C def) per se but the construct who's instances
	 * yield rvalues. It is a construct that yields data, not the data (yield)
	 * itself.
	 */
	public static interface Type {
		
		public String name();

		public Evaluator evaluator();

		public Evaluator constraintsEvaluator();
	}

	/* generic placeholder
	 */
	private static Type userType = new Type() {
	
		public String name() {
			return null;
		}

		public Evaluator evaluator() {
			return Data::evalUser;
		}

		public Evaluator constraintsEvaluator() {
			return Data::evalUserConstraints;
		}
	};


	public static enum CoreType implements Type {

    String("string",
					(expr,def,ctx) -> expr != null && expr instanceof String,
					Data::evalScalarConstraints),
    Integer("integer",
					(expr,def,ctx) -> Data.valueOf(ctx, expr, Integer.class),
					Data::evalScalarConstraints),
		Float("float",
					(expr,def,ctx) -> Data.valueOf(ctx, expr, Double.class, Integer.class),
					Data::evalScalarConstraints),
 	  Boolean("boolean",
					(expr,def,ctx) -> Data.valueOf(ctx, expr, Boolean.class),
					Data::evalScalarConstraints),
 	  Null("null",
					(expr,def,ctx) -> "null".equals(expr),
					null),
   	Timestamp("timestamp",
					(expr,def,ctx) -> timestampRegex.matcher(expr.toString()).matches(),
					null),
    List("list", Data::evalList, Data::evalListConstraints),
    Map("map", Data::evalMap, Data::evalMapConstraints),
		Version("version",
					(expr,def,ctx) -> versionRegex.matcher(expr.toString()).matches(),
					null),
		/* use a scanner and check that the upper bound is indeed greater than
		 * the lower bound */
    Range("range",
					(expr,def,ctx) -> rangeRegex.matcher(expr.toString()).matches(),
					null ),
    Size("scalar-unit.size",
				 (expr,def,ctx) -> sizeRegex.matcher(expr.toString()).matches(),
					null),
    Time("scalar-unit.time",
				 (expr,def,ctx) -> timeRegex.matcher(expr.toString()).matches(),
					null),
    Frequency("scalar-unit.frequency",
				 (expr,def,ctx) -> frequencyRegex.matcher(expr.toString()).matches(),
					null);


		private String 		toscaName;
		private Evaluator	valueEvaluator, constraintsEvaluator;



		private CoreType(String theName, Evaluator theValueEvaluator, Evaluator theConstraintsEvaluator) {
			this.toscaName = theName;
			this.valueEvaluator = theValueEvaluator;
			this.constraintsEvaluator = theConstraintsEvaluator;

			if (typesByName == null) {
				throw new RuntimeException("No type index available!");
			}

			typesByName.put(this.toscaName, this);
		}



		@Override
		public String toString() {
			return this.toscaName;
		}

		public Evaluator evaluator() {
			return this.valueEvaluator;
		}
		
		public Evaluator constraintsEvaluator() {
			return this.constraintsEvaluator;
		}
	}

	private static Pattern timestampRegex = null,
												 versionRegex = null,
												 rangeRegex = null,
												 sizeRegex = null,
												 timeRegex = null,
												 frequencyRegex = null;

	static {
		try {
			timestampRegex = Pattern.compile(
					"\\p{Digit}+"); //?? where to find the definition

			//<major_version>.<minor_version>[.<fix_version>[.<qualifier>[-<build_version]]]
			versionRegex = Pattern.compile(
					"\\p{Digit}+\\.\\p{Digit}+?(\\.\\p{Digit}+(\\.\\p{Alpha}+(\\-\\p{Digit}+))*)*");
			
			rangeRegex = Pattern.compile(
					"\\[[ ]*\\p{Digit}+(\\.\\p{Digit}+)?[ ]*\\,[ ]*(\\p{Digit}+(\\.\\p{Digit}+)?|UNBOUNDED)[ ]*\\]");
			
			sizeRegex = Pattern.compile(
					"\\p{Digit}+(\\.\\p{Digit}+)?[ ]*(B|kB|KiB|MB|MiB|GB|GiB|TB|TiB)");
			
			timeRegex = Pattern.compile(
					"\\p{Digit}+(\\.\\p{Digit}+)?[ ]*(d|h|m|s|ms|us|ns)");
			
			frequencyRegex = Pattern.compile(
					"\\p{Digit}+(\\.\\p{Digit}+)?[ ]*(Hz|kHz|MHz|GHz)");
		}
		catch (PatternSyntaxException psx) {
			throw new RuntimeException("Bad patterns", psx);
		}
	}

	/* */	
	public static boolean evalScalarConstraints(Object theVal,
																 							Map theDef,
																 							Checker.CheckContext theCtx) {
		Data.Type type = typeByName((String)theDef.get("type"));
		List<Map<String,Object>> constraints =
															(List<Map<String,Object>>)theDef.get("constraints");
		if (constraints == null) {
			return true;
		}

		//check value against constraints
		boolean res = true;
		for (Map<String,Object> constraintDef: constraints) {
			Map.Entry<String,Object> constraintEntry =
																		constraintDef.entrySet().iterator().next();
			Data.Constraint constraint = constraintByName(constraintEntry.getKey());

// the def passed here includes all constraints, not necessary! we can pass
// simple constraintEntry.getValue()
			Evaluator constraintEvaluator = getTypeConstraintEvaluator(type, constraint);
			if (constraintEvaluator == null) {
				debugLogger.log(LogLevel.DEBUG, Data.class.getName(), "No constant evaluator available for {}/{}", type, constraint);
				continue;
			}

			if (!constraintEvaluator.eval(theVal, theDef, theCtx)) {
				theCtx.addError("Value " + theVal + " failed constraint " + constraintEntry, null);
				res = false;
			}
		}
		return res;
	}

	/*
	 * It assumes the specification is complete, i.e. it contains a valid
	 * entry_schema section.
	 * TODO: check constraints, i.e. entrySchema.get("constraints")
	 */
	public static boolean evalList(Object theVal,
																 Map theDef,
																 Checker.CheckContext theCtx) {
		try {
			return evalCollection((List)theVal, theDef, theCtx);
		}
		catch (ClassCastException ccx) {
			theCtx.addError("Value " + theVal + " not a list", null);
			return false;
		}
	}
	
	public static boolean evalMap(Object theVal,
																Map theDef,
																Checker.CheckContext theCtx) {
		try {
			return evalCollection(((Map)theVal).values(), theDef, theCtx);
		}
		catch (ClassCastException ccx) {
			theCtx.addError("Value " + theVal + " not a map", null);
			return false;
		}
	}


	/**
	 * The elements of a collection can be of a core type or user defined type.
   */
	private static boolean evalCollection(Collection theVals,
																 				Map theDef,
																 				Checker.CheckContext theCtx) {
		Data.Type entryType = null;
		Map entryTypeDef = (Map)theDef.get("entry_schema");
		if (null != entryTypeDef) {
			entryType = typeByName((String) entryTypeDef.get("type"));
		}

		boolean res = true;
		for (Object val: theVals) {
			//check if the value is not a function call
			Data.Function f = Data.function(val);
			if (f != null &&
					f.evaluator().eval(val, entryTypeDef, theCtx)) {
				res = false;
			}
			else if (entryType != null && !entryType.evaluator().eval(val, entryTypeDef, theCtx)) {
				res = false;
			}
		}
		return res;
	}
	
	public static boolean evalListConstraints(Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return evalCollectionConstraints((List)theVal, theDef, theCtx);
	}
	
	public static boolean evalMapConstraints(Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return evalCollectionConstraints(((Map)theVal).values(), theDef, theCtx);
	}

	private static boolean evalCollectionConstraints(Collection theVals, Map theDef, Checker.CheckContext theCtx) {
		//should check overall constraints 

		if (theVals == null) {
			return true;
		}

		Map entryTypeDef = (Map)theDef.get("entry_schema");
		if (null == entryTypeDef) {
			return true;
		}

		String entryTypeName = (String)entryTypeDef.get("type");
		Data.Type entryType = typeByName(entryTypeName);

		boolean res = true;
		for (Object val: theVals) {
			Evaluator entryEvaluator = entryType.constraintsEvaluator();
			if (entryEvaluator != null && !entryEvaluator.eval(val, entryTypeDef, theCtx)) {
				res= false;
			}
		}
		return res;
	}

	/*
	 * All required properties across the hierarchical defintion must be present
	 * TODO:  The expr cannot contain any entry not specified in the type definition
	 */
	public static boolean evalUser(Object theVal,
																 Map theDef,
																 Checker.CheckContext theCtx) {

		boolean res = true;
		Map val = (Map)theVal;
		//must be done with respect to the super-type(s) definition
		Iterator<Map.Entry> props =	theCtx.catalog()
																				.facets(Construct.Data,
																								Facet.properties,
																					 			(String)theDef.get("type"));	
		while (props.hasNext()) {
			Map.Entry propEntry = props.next();
			Map propDef = (Map)propEntry.getValue();
			Object propVal = val.get(propEntry.getKey());

			if (propVal != null) {
				Data.Type propType = typeByName((String)propDef.get("type"));

				if (!propType.evaluator().eval(propVal, propDef, theCtx)) {
					res= false;
					//the constraints evaluator should have already added an error
					//theCtx.addError("Property " + propEntry.getKey() + " failed evaluation for " + propVal, null);
				}
			}
		}
		return res;
	}
	
	public static boolean evalUserConstraints(Object theVal,
																 						Map theDef,
																 						Checker.CheckContext theCtx) {
		boolean res = true;
		Map val = (Map)theVal;
		Iterator<Map.Entry> props =	theCtx.catalog()
																				.facets(Construct.Data,
																								Facet.properties,
																					 			(String)theDef.get("type"));	
		while (props.hasNext()) {
			Map.Entry propEntry = props.next();
			Map propDef = (Map)propEntry.getValue();
			Object propVal = val.get(propEntry.getKey());
		
			if (propVal != null) {
				Data.Type propType = typeByName((String)propDef.get("type"));

				if (propType.constraintsEvaluator() != null && !propType.constraintsEvaluator().eval(propVal, propDef, theCtx)) {
					res= false;
				}
			}
			else {
				if (Boolean.TRUE == propDef.getOrDefault("required", Boolean.FALSE) &&	!propDef.containsKey("default")) {
					theCtx.addError("Property " + propEntry.getKey() + " failed 'required' constraint; definition is " + propDef, null);
					res = false;
				}
			}	
		}
		return res;
	}

	private static boolean valueOf(Checker.CheckContext theCtx,
																 Object theExpr,
																 Class ... theTypes) {
		for (Class type: theTypes) {
			if (type.isAssignableFrom(theExpr.getClass())) {
				return true;
			}
		}
				
		theCtx.addError("Expression " + theExpr + " as " + theExpr.getClass().getName() + " is not compatible with any of required types: " + Arrays.toString(theTypes), null);
		return false;
	}

	/* 
	 * Function e(valuation)
	 * ?
	 * note to self : is there a more efficient way of retrieving a map's 
	 * single entry? (without knowing the key)
	 *
	 * ! Function evaluators have to handle null definition (i.e. perform argument checking) so that
	 * we can use them in the  context of collections with without entry_schemas
	 */
	
	//just as Type but is it worth expressing this 'commonality'??
	
	public static interface Function {
		
		public String name();

		public Evaluator evaluator();
	}

	/*
	 * This is a heuristic induced from the tosca specification .. it answers the
	 * question of wether the given expression is a function
	 */
	public static Function function(Object theExpr) {
		if (theExpr instanceof Map &&
				((Map)theExpr).size() == 1) {
			try {
				return Enum.valueOf(CoreFunction.class,	functionName(theExpr));
			}
			catch (IllegalArgumentException iax) {
				//no such function but we cannot really record an error as we only guessed the expression as being a function ..
				debugLogger.log(LogLevel.DEBUG, Data.class.getName(), "Failed attempt to interpret {} as a function call", theExpr);
			}
		}
		
		return null;
	}

	/*
	 */
	public static String functionName(Object theExpr) {
		return	(String)
							((Map.Entry)
								((Map)theExpr).entrySet().iterator().next())
									.getKey();
	}

	/*
	 */
	public static Data.Function functionByName(String theName) {
		return Enum.valueOf(CoreFunction.class, theName);
	}

	/*
	 */	
	public static enum CoreFunction implements Function {

		concat(Data::evalConcat),
		token(Data::evalToken),
		get_input(Data::evalGetInput),
		get_property(Data::evalGetProperty),
		get_attribute(Data::evalGetAttribute),
		get_operation_output((expr,def,ctx) -> true),
		get_nodes_of_type(Data::evalGetNodesOfType),
		get_artifact((expr,def,ctx) -> true);
				 
		private Evaluator	evaluator;

		private CoreFunction(Evaluator theEval) {
			this.evaluator = theEval;
		}
		
		public Evaluator evaluator() {
			return this.evaluator;
		}
	}

	private static boolean evalConcat(Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return true;
	}
	
	private static boolean evalToken(Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return true;
	}

	private static boolean evalGetInput(Object theVal, Map theDef, Checker.CheckContext theCtx) {
		Map val = (Map)theVal;
		Map.Entry entry = (Map.Entry)val.entrySet().iterator().next();

		if (!(entry.getValue() instanceof String)) {
			theCtx.addError("get_input: argument must be a String" ,null);
			return false;
		}

		//check that an input with the given name exists and has a compatible type
		Map inputDef = theCtx.catalog()
													.getTemplate(theCtx.target(), Construct.Data, (String)entry.getValue());
		if (inputDef == null) {
			theCtx.addError("get_input: no such input " + entry.getValue(), null);
			return false;
		}

		if (theDef == null) {
			return true;
		}

		//the output must be type compatible with the input
		String targetType = (String)theDef.get("type");
		if (targetType != null) {
			String inputType = (String)inputDef.get("type");

			if (!theCtx.catalog()
									.isDerivedFrom(Construct.Data, inputType, targetType)) {
				theCtx.addError("get_input: input type " + inputType + " is incompatible with the target type " + targetType, null);
				return false;
			}
		}

		return true;
	}

	/*
	 * Who's the smarty that decided to define optional arguments in between
	 * required ones ?!
	 * (factors the evaluation of get_attribute and get_property)
	 */
	private static boolean evalGetData(
						Object theVal, Map theDef,
						EnumSet<Facet> theFacets, Checker.CheckContext theCtx) {

		Map val = (Map) theVal;
		Map.Entry entry = (Map.Entry) val.entrySet().iterator().next();

		if (!(entry.getValue() instanceof List)) {
			theCtx.addError("get_property: argument must be a List", null);
			return false;
		}

		List args = (List) entry.getValue();
		if (args.size() < 2) {
			theCtx.addError("'get_property' has at least 2 arguments", null);
			return false;
		}

		//the first argument is a node or relationship template
		String tmpl = (String) args.get(0);
		Construct tmplConstruct;
		Map tmplSpec;

		if ("SELF".equals(tmpl)) {
			tmpl = theCtx.enclosingConstruct(Construct.Node);
			if (tmpl == null) {
				tmpl = theCtx.enclosingConstruct(Construct.Relationship);
				if (tmpl == null) {
					theCtx.addError("'get_property' invalid SELF reference: no node or relationship template in scope at " + theCtx.getPath(), null);
					return false;
				} else {
					tmplConstruct = Construct.Relationship;
				}
			} else {
				tmplConstruct = Construct.Node;
			}
			tmplSpec = theCtx.catalog().getTemplate(theCtx.target(), tmplConstruct, tmpl);
		} else if ("SOURCE".equals("tmpl")) {
			//we are in the scope of a relationship template and this is the source node template.
			tmpl = theCtx.enclosingConstruct(Construct.Relationship);
			if (tmpl == null) {
				theCtx.addError("'get_property' invalid SOURCE reference: no relationship template in scope at " + theCtx.getPath(), null);
				return false;
			}

			return true;
		} else if ("TARGET".equals("tmpl")) {
			//we are in the scope of a relationship template and this is the target node template.
			tmpl = theCtx.enclosingConstruct(Construct.Relationship);
			if (tmpl == null) {
				theCtx.addError("'get_property' invalid TARGET reference: no relationship template in scope at " + theCtx.getPath(), null);
				return false;
			}

			return true;
		} else if ("HOST".equals("tmpl")) {
			tmpl = theCtx.enclosingConstruct(Construct.Node);
			if (tmpl == null) {
				theCtx.addError("'get_property' invalid HOST reference: no node template in scope at " + theCtx.getPath(), null);
				return false;
			}

			return true;
		} else {
			//try node template first
			tmplSpec = theCtx.catalog().getTemplate(theCtx.target(), Construct.Node, tmpl);
			if (tmplSpec == null) {
				//try relationship
				tmplSpec = theCtx.catalog().getTemplate(theCtx.target(), Construct.Relationship, tmpl);
				if (tmplSpec == null) {
					theCtx.addError("'get_data' invalid template reference '" + tmpl + "': no node or relationship template with this name", null);
					return false;
				} else {
					tmplConstruct = Construct.Relationship;
				}
			} else {
				tmplConstruct = Construct.Node;
			}
		}

		int facetNameIndex = 1;
		Construct facetConstruct = tmplConstruct; //who's construct the facet is supposed to belong to
		Map facetConstructSpec = null;
		String facetConstructType = null;

		if (tmplConstruct.equals(Construct.Node) &&
				args.size() > 2) {
			//the second arg might be a capability or requirement name. If it is a
			//capability than the third argument becomes a property of the
			//coresponding capability type. If it is a requirement than the
			//requirement definition indicates a capability who's type has a
			//property with the name indicated in the third argument ..
			//
			//while the spec does not make it explicit this can only take place
			//if the first argument turned out to be a node template (as relationship
			//templates/types do not have capabilities/requirements
			String secondArg = (String) args.get(1);
			if ((facetConstructSpec = theCtx.catalog().getFacetDefinition(
					tmplConstruct,
					(String) tmplSpec.get("type"),
					Facet.capabilities,
					secondArg)) != null) {
				facetNameIndex = 2;
				facetConstruct = Construct.Capability;
				facetConstructType = (String) facetConstructSpec.get("type");
			} else if ((facetConstructSpec = theCtx.catalog().getRequirementDefinition(
					tmplConstruct,
					(String) tmplSpec.get("type"),
					secondArg)) != null) {
				facetNameIndex = 2;
				facetConstruct = Construct.Capability;

				//find the specof the capability this requirement points to
				//TODO: check, can the capability reference be anything else but a capability tyep?
				facetConstructType = (String) facetConstructSpec.get("capability");
			}
		} else {
			//we'll attempt to handle it as a property of the node template
			facetConstruct = Construct.Node;
			facetConstructSpec = tmplSpec;
			facetConstructType = (String) facetConstructSpec.get("type");
		}

		//validate the facet name
		Map facetSpec = null;

		String facetName = (String) args.get(facetNameIndex);
		for (Facet facet : theFacets) {
			facetSpec = theCtx.catalog()
					.getFacetDefinition(
							facetConstruct,
							facetConstructType,
							facet,
							facetName);
			if (facetSpec != null) {
				break;
			}
		}

		if (facetSpec == null) {
//TODO: not the greatest message if the call strated with a requirement ..
			theCtx.addError("'get_data' invalid reference, '" + facetConstruct + "' " + facetConstructType + " has no " + theFacets + " with name " + facetName, null);
			return false;
		}


		return true;
	}
	
	/**/
	private static boolean evalGetProperty(
						Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return evalGetData(theVal, theDef, EnumSet.of(Facet.properties), theCtx);
	}

	/*
	 * get_property and get_attribute are identical, just operating on different
	 * facets, with one exception: there is an intrinsec attribute for every 
	 * declared property.
	 */
	private static boolean evalGetAttribute(
						Object theVal, Map theDef, Checker.CheckContext theCtx) {
		return evalGetData(theVal, theDef, EnumSet.of(Facet.attributes, Facet.properties), theCtx);
	}

	private static boolean evalGetNodesOfType(
						Object theVal, Map theDef, Checker.CheckContext theCtx) {
		
		Map val = (Map)theVal;
		Map.Entry entry = (Map.Entry)val.entrySet().iterator().next();

		if (!(entry.getValue() instanceof String)) {
			theCtx.addError("get_nodes_of_type: argument must be a String", null);
			return false;
		}

		String arg = (String)entry.getValue();

		if (null == theCtx.catalog().getTypeDefinition(Construct.Node, arg)) {
			theCtx.addError("get_nodes_of_type: no such node type " + arg, null);
			return false;
		}
		else {
			return true;
		}
	}

	/* */
	public static Constraint constraintByName(String theName) {
		return Enum.valueOf(Constraint.class,	theName);
	}

	/* */	
	public static Constraint constraint(Object theExpr) {
		if (theExpr instanceof Map &&
				((Map)theExpr).size() == 1) {
			return constraintByName(constraintName(theExpr));
		}
		
		return null;
	}

	/* */
	public static String constraintName(Object theExpr) {
		return	(String)
							((Map.Entry)
								((Map)theExpr).entrySet().iterator().next())
									.getKey();
	}

	private static Object getConstraintValue(Map theDef,
																					 Constraint theConstraint) {
		List<Map> constraints = (List<Map>)theDef.get("constraints");
		if (null == constraints) {
			return null;
		}

		for(Map constraint: constraints) {
			Object val = constraint.get(theConstraint.toString());
			if (val != null) {
				return val;
			}
		}
		return null;
	}

	public static enum Constraint {
		equal,
		greater_than,
		greater_or_equal,
		less_than,
		less_or_equal,
		in_range,
		valid_values,
		length,
		min_length,
		max_length,
		pattern;
	}

	/* hold the constraint evaluators for pairs of type/constraint.
	 * If a pair is not present than the given constraint does not apply
	 * to the type.
	 */
	private static Table<Type,Constraint,Evaluator> typeConstraintEvaluator = null;

	public static Evaluator getTypeConstraintEvaluator(Type theType, Constraint theConstraint) {
		if (typeConstraintEvaluator == null) {
			typeConstraintEvaluator = HashBasedTable.create();

			typeConstraintEvaluator.put(CoreType.String, Constraint.equal,
				(val,def,ctx) -> val.equals(getConstraintValue(def,Constraint.equal)));
			typeConstraintEvaluator.put(CoreType.String, Constraint.valid_values,
				(val,def,ctx) -> ((List)getConstraintValue(def,Constraint.valid_values)).contains(val));
			typeConstraintEvaluator.put(CoreType.String, Constraint.length,
				(val,def,ctx) -> ((String)val).length() == ((Number)getConstraintValue(def,Constraint.length)).intValue());
			typeConstraintEvaluator.put(CoreType.String, Constraint.min_length, 
				(val,def,ctx) -> ((String)val).length() >= ((Number)getConstraintValue(def,Constraint.min_length)).intValue());
			typeConstraintEvaluator.put(CoreType.String, Constraint.max_length, 
				(val,def,ctx) -> ((String)val).length() <= ((Number)getConstraintValue(def,Constraint.max_length)).intValue());
			typeConstraintEvaluator.put(CoreType.String, Constraint.pattern,
				(val,def,ctx) -> Pattern.compile((String)getConstraintValue(def,Constraint.pattern))
																	.matcher((String)val)
																		.matches());

			typeConstraintEvaluator.put(CoreType.Integer, Constraint.equal,
				(val,def,ctx) -> ((Integer)val).compareTo((Integer)getConstraintValue(def,Constraint.equal)) == 0);
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.greater_than,
				(val,def,ctx) -> ((Integer)val).compareTo((Integer)getConstraintValue(def,Constraint.greater_than)) > 0);
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.greater_or_equal,
				(val,def,ctx) -> ((Integer)val).compareTo((Integer)getConstraintValue(def,Constraint.greater_or_equal)) >= 0);
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.less_than,
				(val,def,ctx) -> ((Integer)val).compareTo((Integer)getConstraintValue(def,Constraint.less_than)) < 0);
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.less_or_equal,
				(val,def,ctx) -> ((Integer)val).compareTo((Integer)getConstraintValue(def,Constraint.less_or_equal)) <= 0);
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.in_range,
				(val,def,ctx) -> { List<Integer> range = (List<Integer>)getConstraintValue(def, Constraint.in_range);
													 return ((Integer)val).compareTo(range.get(0)) >= 0 &&
																	((Integer)val).compareTo(range.get(1)) <= 0;
												});
			typeConstraintEvaluator.put(CoreType.Integer, Constraint.valid_values,
				(val,def,ctx) -> ((List<Integer>)getConstraintValue(def, Constraint.valid_values)).contains((Integer)val));
		
//yaml parser represents yaml floats as java Double and we are even more tolerant as many double values
//get represented as ints and the parser will substitute an Integer	
			typeConstraintEvaluator.put(CoreType.Float, Constraint.equal,
				(val,def,ctx) -> ((Number)val).doubleValue() == ((Number)getConstraintValue(def,Constraint.equal)).doubleValue());
			typeConstraintEvaluator.put(CoreType.Float, Constraint.greater_than,
				(val,def,ctx) -> ((Number)val).doubleValue() > ((Number)getConstraintValue(def,Constraint.greater_than)).doubleValue());
			typeConstraintEvaluator.put(CoreType.Float, Constraint.greater_or_equal,
				(val,def,ctx) -> ((Number)val).doubleValue() >= ((Number)getConstraintValue(def,Constraint.greater_or_equal)).doubleValue());
			typeConstraintEvaluator.put(CoreType.Float, Constraint.less_than,
				(val,def,ctx) -> ((Number)val).doubleValue() < ((Number)getConstraintValue(def,Constraint.less_than)).doubleValue());
			typeConstraintEvaluator.put(CoreType.Float, Constraint.less_or_equal,
				(val,def,ctx) -> ((Number)val).doubleValue() <= ((Number)getConstraintValue(def,Constraint.less_or_equal)).doubleValue());
			typeConstraintEvaluator.put(CoreType.Float, Constraint.in_range,
				(val,def,ctx) -> { List<Number> range = (List<Number>)getConstraintValue(def, Constraint.in_range);
													 return ((Number)val).doubleValue() >= range.get(0).doubleValue() &&
																	((Number)val).doubleValue() <= range.get(1).doubleValue();
												});
			typeConstraintEvaluator.put(CoreType.Float, Constraint.valid_values,
				(val,def,ctx) -> ((List<Number>)getConstraintValue(def, Constraint.valid_values)).contains((Number)val));
		}

		Evaluator eval = typeConstraintEvaluator.get(theType, theConstraint);

		return eval == null ? (expr,def,ctx) -> true
												: eval;
	}

	
	private static boolean stringValidValues(String theVal,
																 					 List<String> theValidValues,
																 					 Checker.CheckContext theCtx) {
		if (!theValidValues.contains(theVal)) {
			theCtx.addError("not a valid value: " + theVal + " not part of " + theValidValues, null);
			return false;
		}

		return true;
	}

	public static final void main(String[] theArgs) {
		Data.CoreType dt = Enum.valueOf(Data.CoreType.class, theArgs[0]);
		debugLogger.log(LogLevel.DEBUG, Data.class.getName(), "{} > {}", theArgs[1], dt.evaluator().eval(theArgs[1], null, null));
	}
}