summaryrefslogtreecommitdiffstats
path: root/dcaedt_validator/checker/src/main/java/org/onap/sdc/dcae/checker/JSP.java
blob: 39c1cdd2851529d301bd82fe39a1005af7708b2d (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
/*-
 * ============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.io.IOException;
import java.io.File;

import java.net.URI;

import java.util.Set;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.function.Consumer;
import java.util.function.BiFunction;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.AbstractJSObject;

import org.apache.commons.jxpath.JXPathContext;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
import org.onap.sdc.common.onaplog.enums.LogLevel;


/**
 * Java Script Processor
 * Each script is represented by a Target and the JSP processor maintains a collection of Targets, i.e. scripts.
 * A collection of targets can be used with only one JSP processor at a time (as the processor stores processor specific * compiled versions within the target). 
 */
public class JSP implements Processor<JSP> {

  private ScriptEngine engine;
	private Collection<? extends Target> targets;

  public JSP(String[] theScripts) {
		this(Arrays.stream(theScripts)
								.map(s -> new Target(s, new File(s).toURI()))
								.collect(Collectors.toList()));
	}
  
	public JSP(File[] theScripts) {
		this(Arrays.stream(theScripts)
								.map(s -> new Target(s.getName(), s.toURI()))
								.collect(Collectors.toList()));
	}
	
	public JSP(URI[] theScripts) {
		this(Arrays.stream(theScripts)
								.map(s -> new Target(s.toString(), s))
								.collect(Collectors.toList()));
	}

	/**
   * The given collection is allowed to change while used by the JSP engine but access to it needs to be synchronized.
   * The engine uses the target field of each Target to store a compiled version of each script. An external reset of
   * this field (maybe in order to indicate some change in the Target) will caue a re-compilation of the Target.
   */
	public JSP(Collection<? extends Target> theTargets) {
		this.targets = theTargets;
    ScriptEngineManager engineManager = new ScriptEngineManager();
    this.engine = engineManager.getEngineByName("nashorn");
	}

	public Collection<? extends Target> targets() {
		return this.targets;
	}

	/* pre-compiles all known targets
   */
	protected void compile() throws ProcessorException {
		synchronized (this.targets) {
			for (Target t: this.targets)
				compile(t);
		}
	}

	protected CompiledScript compile(Target theTarget) throws ProcessorException {

		CompiledScript cs = null;

		synchronized(theTarget) {		
			try {
				cs = (CompiledScript)theTarget.getTarget();
			}
			catch(ClassCastException ccx) {
				throw new ProcessorException(theTarget, "Unexpected target content");
			}

			if (cs == null) {
				try {
					cs = ((Compilable)this.engine).compile(theTarget.open());
					theTarget.setTarget(cs);
				}
  	  	catch (IOException iox) {
					throw new ProcessorException(theTarget, "Failed to read script", iox);
				}
				catch (ScriptException sx) {
					throw new ProcessorException(theTarget, "Failed to compile script", sx);
				}
			}
		}

		return cs;
	}

	public ContextBuilder process(Catalog theCatalog) {
		return new ContextBuilder(
											this.engine.createBindings())
											//new DelegateBindings(this.engine.getBindings(ScriptContext.ENGINE_SCOPE)))
								.with("catalog", new JSCatalog(theCatalog));
	}

	/**
   */
	public class ContextBuilder implements ProcessBuilder<JSP> { 

		private ScriptContext		context;

		protected ContextBuilder(Bindings theBindings) {
			this.context = new SimpleScriptContext();
			this.context.setBindings(theBindings, Process.PROCESS_SCOPE /*ScriptContext.ENGINE_SCOPE*/);
		}

		public ContextBuilder withPreprocessing(BiFunction<Target, ScriptContext, Boolean> thePreprocessing) {
			this.context.setAttribute("preprocessor", thePreprocessing, Process.PROCESS_SCOPE);
			return this;
		}

		public ContextBuilder withPostprocessing(BiFunction<Target, ScriptContext, Boolean> thePostprocessing) {
			this.context.setAttribute("postprocessor", thePostprocessing, Process.PROCESS_SCOPE);
			return this;
		}

		public ContextBuilder with(String theName, Object theValue) {
			this.context.getBindings(Process.PROCESS_SCOPE).put(theName, theValue);
			return this;
		}
		
		public ContextBuilder withOpt(String theName, Object theValue) {
			if (theValue != null)
				this.context.getBindings(Process.PROCESS_SCOPE).put(theName, theValue);
			return this;
		}

		public JSProcess process() {
 			return new JSProcess(this.context);
		}

	}

  /**
   */
  public class JSProcess implements Process<JSP> {

		private Report											report = new Report();
		private Iterator<? extends Target> 	scripts;
		private JScriptInfo									scriptInfo = new JScriptInfo();
		private	Target											script; //script currently being evaluated
		private boolean											stopped = false;
		private ScriptContext								context;

		private JSProcess(ScriptContext theContext) {

			this.context = theContext;
			this.context.getBindings(Process.PROCESS_SCOPE)
											.put("stop", new Consumer<String>() {
																			public void accept(String theMsg) {
																				JSProcess.this.stopped = true;
																				//log the message??
																			}
																		});
			this.context.getBindings(Process.PROCESS_SCOPE)
											.put("report", new Consumer<String>() {
																			public void accept(String theMsg) {
																				JSProcess.this.report.add(new ProcessorException(script, theMsg));
																			}
																		});
			this.context.getBindings(Process.PROCESS_SCOPE)
											.put("reportOnce", new Consumer<String>() {
																			public void accept(String theMsg) {
																				JSProcess.this.report.addOnce(new ProcessorException(script, theMsg));
																			}
																		});
			this.scripts = JSP.this.targets.iterator();
		}

		protected String infoName(Target theTarget) {
			String name = theTarget.getName();
			return name.substring(0, name.indexOf(".")) + "_info";
		}

		public JSP processor() {
			return JSP.this;
		}

		public boolean hasNext() {
			return !this.stopped && this.scripts.hasNext();
		}

		protected Target next() {
			if (hasNext())
				return this.script = this.scripts.next();
			else
				throw new RuntimeException("Process is completed");
		}

		protected boolean runProcessor(String theName) throws ProcessorException {
			BiFunction<Target, ScriptContext, Boolean> proc = (BiFunction<Target, ScriptContext, Boolean>)
																														this.context.getAttribute(theName, Process.PROCESS_SCOPE);
			if (proc != null) {
				try {
					return proc.apply(this.script, this.context).booleanValue();
				}
				catch (Exception x) {
					throw new ProcessorException(this.script, theName + "failed", x);
				}
			}

			return true;
		}

		public Process runNext() throws ProcessorException {
			Target target = next();
			synchronized(target) {
				String name = infoName(target);
				try {
					if (runProcessor("preprocessor")) {
						compile(target).eval(this.context);
						runProcessor("postprocessor");
					}
				}
				catch (ScriptException sx) {
					throw new ProcessorException(target, "Failed to execute validation script", sx);
				}
			}
			
			return this;
		}
		
		public Process runNextSilently() {
			try {
				return runNext();
			}
			catch (ProcessorException px) {
				this.report.add(px);
			}
			return this;
		}

		public Report run() {
			while (hasNext())
				runNextSilently();
			return this.report;
		}

		public void stop() {
			this.stopped = true;
		}

		public Report report() {
			return this.report;
		}
	}

	private static class JScriptInfo implements TargetInfo {
	
		private JSObject info;

		protected JScriptInfo() {
		}

		protected JScriptInfo setInfo(JSObject theInfo) {
			this.info = theInfo;
			return this;
		}

		public Set<String>	entryNames() {
			return this.info == null ? Collections.EMPTY_SET : this.info.keySet();
		}

		public boolean	hasEntry(String theName) {
			return this.info == null ? false : this.info.hasMember(theName);
		}

		public Object	getEntry(String theName) {
			return this.info == null ? null : 
								 this.info.hasMember(theName) ?	this.info.getMember(theName) : null;
		}
	}


  /* Exposes the catalog information in a more Java Script friendly manner.
   */
  public static class JSCatalog {

		private Catalog catalog;

		private JSCatalog(Catalog theCatalog) {
			this.catalog = theCatalog;
		}
		
		/** */
    public JSTarget[] targets() {
			return 
				this.catalog.targets()
					.stream()
					.map(t -> { return new JSTarget(t); })
					.toArray(size -> new JSTarget[size]); //or toArray(JSNode[]::new)
    }
    
		public JSTarget[] topTargets() {
			return 
				this.catalog.topTargets()
					.stream()
					.map(t -> { return new JSTarget(t); })
					.toArray(size -> new JSTarget[size]); //or toArray(JSNode[]::new)
    }

		/** */
    public String[] types(String theConstruct) {
			Set<String> names = 
							this.catalog.getConstructTypes(Enum.valueOf(Construct.class,theConstruct)).keySet();
      return names.toArray(new String[names.size()]);
    }

		/** */
		public boolean isDerivedFrom(String theConstruct, String theType, String theSuperType) {
			return this.catalog.isDerivedFrom(Enum.valueOf(Construct.class,theConstruct), theType, theSuperType);
		}

		/** */
		public JSObject facetDefinition(String theConstruct, String theType, String theFacet, String theName) {
			return new JSElement(theName,
													 this.catalog.getFacetDefinition(
															Enum.valueOf(Construct.class, theConstruct), theType, 
															Enum.valueOf(Facet.class, theFacet), theName));
		}


		/** */
/*
    public JSElement[] targetNodes(Target theTarget) {
			return 
				this.catalog.getTargetTemplates(theTarget, Construct.Node)
					.entrySet()
						.stream()
						.map(e -> { return new JSElement(e.getKey(),e.getValue()); })
						.toArray(size -> new JSElement[size]); //or toArray(JSNode[]::new)
		}
*/

		public class JSTarget {

			private Target 				tgt;
	  	private	JXPathContext jxPath;

			private JSTarget(Target theTarget) {
				this.tgt = theTarget;
				this.jxPath = JXPathContext.newContext(this.tgt.getTarget());
				this.jxPath.setLenient(true);
			}

			public String getName() { return this.tgt.getName(); }

			public JSElement resolve(String thePath) {
				Object res = jxPath.getValue(thePath);
				if (res instanceof Map) {
					return new JSElement(thePath, (Map)res);
				}
				//??
				return null;
			}

			public JSElement[] getInputs() {
				
				Map<String,Map> inputs = (Map<String,Map>)jxPath.getValue("/topology_template/inputs");
				return (inputs == null) ? 
										new JSElement[0]
									: inputs.entrySet()
											.stream()
											.map(e -> { return new JSElement(e.getKey(),e.getValue()); })
											.toArray(size -> new JSElement[size]);
			}

//			public JSElement[] getOutputs() {
//			}

      public JSElement getMetadata() {
				return new JSElement("metadata", (Map)jxPath.getValue("/metadata"));
			}

			public JSElement[] getNodes() {
				return 
					JSCatalog.this.catalog.getTargetTemplates(this.tgt, Construct.Node)
						.entrySet()
							.stream()
							.map(e -> { return new JSElement(e.getKey(),e.getValue()); })
							.toArray(size -> new JSElement[size]); //or toArray(JSElement[]::new)
			}

//			public JSElement[] getPolicies() {
//			}

		}


		/*
		 */
  	public class JSElement extends AbstractJSObject {
	

			private String 	name;
  	  private Map			def;

			private JSElement(String theName, Object theDef) {
				this.name = theName;
    	  this.def = theDef == null ? Collections.emptyMap() 
																	: (theDef instanceof Map) ? (Map)theDef
																														: Collections.singletonMap("value",theDef);
			}

			public String getName() { return this.name; }

			public boolean hasMember(String theMember) {
				return this.def.containsKey(theMember); 
			}

			public Object getMember(final String theMember) {
				Object val = this.def.get(theMember);
				if (val != null) {
					if (val instanceof Map) {
						return new JSElement(theMember, val);
					/*
						return ((Map<String,?>)obj).entrySet()
											.stream()
											.map((Map.Entry<String,?> e) -> { return new JSElement(e.getKey(),e.getValue()); })
											.toArray(size -> new JSElement[size]);
					*/
					}
					
					if (val instanceof List) {
						//a property value can be a list of: primitive types or maps (for a user defined type)
						//requirements are exposed as a list of maps
						List lval = (List)val;
						if (lval.get(0) instanceof Map) {
							return lval
											.stream()
											.map((e) -> new JSElement(theMember, e))
											.toArray(size -> new JSElement[size]);
							
						/*
							return val
											.stream()
											.map((e) -> {
																		Map.Entry<String,?> re = ((Map<String,?>)e).entrySet().iterator().next();
																		return new JSElement(re.getKey(), re.getValue());
																	})
											.toArray(size -> new JSElement[size]);
						*/
						}
					}
					
					return val;
				}
				else {
					if ("name".equals(theMember))
						return this.name;
					if ("toString".equals(theMember))
						return _toString;
					if ("hasOwnProperty".equals(theMember))
						return _hasOwnProperty;
					return super.getMember(theMember);
				}
			}		
			/* TODO: we do not expose 'name' in here */
			public Set<String> keySet() {
				return this.def.keySet(); 
			}

		}


	static final JSObject _toString = 
						new TracerJSObject("_toString") {
							public Object call(Object thiz, Object... args) {
								return ((JSElement)thiz).def.toString();
							}

							public boolean isFunction() { return true; }
						};

	static final JSObject _hasOwnProperty = 
						new TracerJSObject("_hasOwnProperty") {
							public Object call(Object thiz, Object... args) {
								return ((JSElement)thiz).def.containsKey(args[0]);
							}

							public boolean isFunction() { return true; }
						};	

	}//JSCatalog



  private static class TracerJSObject extends AbstractJSObject {

	  private static OnapLoggerError errLogger = OnapLoggerError.getInstance();
	  private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();

		private String mark;
	
		TracerJSObject(String theMark) {
			this.mark = theMark;
		}

		public Object call(Object thiz, Object... args)	{
			debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:call", this.mark);
			return super.call(thiz, args);
		}

		public Object newObject(Object... args) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:newObject", this.mark);
			return super.newObject(args);
		}

		public Object eval(String s) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:eval", this.mark);
			return super.eval(s);
		}

		public Object getMember(String name) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:getMember", this.mark);
			return super.getMember(name);
		}

		public Object getSlot(int index) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:getSlot", this.mark);
			return super.getSlot(index);
		}

		public boolean hasMember(String name) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:hasMember", this.mark);
			return super.hasMember(name);
		}

		public boolean hasSlot(int slot) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:hasSlot", this.mark);
			return super.hasSlot(slot);
		}

		public void removeMember(String name) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:removeMember", this.mark);
			super.removeMember(name);
		}

		public void setMember(String name, Object value) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:setMember", this.mark);
			super.setMember(name,value);
		}

		public void setSlot(int index, Object value) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:setSlot", this.mark);
			super.setSlot(index,value);
		}

		public Set<String> keySet() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:JSObject:keySet", this.mark);
			return super.keySet();
		}

		public Collection<Object> values() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:values", this.mark);
			return super.values();
		}

		public boolean isInstance(Object instance) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:isInstance", this.mark);
			return super.isInstance(instance);
		}

		public boolean isInstanceOf(Object clazz) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:isInstanceOf", this.mark);
			return super.isInstance(clazz);
		}

		public String getClassName() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:getClassName", this.mark);
			return super.getClassName();
		}

		public boolean isFunction() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:isFunction", this.mark);
			return super.isFunction();
    }

		public boolean isStrictFunction() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:isStrictFunction", this.mark);
			return super.isStrictFunction();
		}

		public boolean isArray() {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:isArray", this.mark);
			return super.isArray();
		}

		public Object getDefaultValue(Class<?> hint) {
            debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "{}:getDefaultValue({})", this.mark, hint);
			return super.getDefaultValue(hint);
		}
	}

}