You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ze...@apache.org on 2021/11/24 10:59:56 UTC

[incubator-streampipes] 01/02: [STREAMPIPES-475] Replace Nashorn engine to run JavaScript Code within a processing element

This is an automated email from the ASF dual-hosted git repository.

zehnder pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/incubator-streampipes.git

commit b32d7186c6124f33d0ad2920b7ad5c3192d499a5
Author: Philipp Zehnder <ze...@fzi.de>
AuthorDate: Wed Nov 24 11:59:10 2021 +0100

    [STREAMPIPES-475] Replace Nashorn engine to run JavaScript Code within a processing element
---
 streampipes-extensions/pom.xml                     | 11 ++++++
 .../streampipes-processors-enricher-jvm/pom.xml    |  8 +++++
 .../enricher/jvm/processor/jseval/JSEval.java      | 39 +++++++++-------------
 ui/cypress/support/model/PipelineElementInput.ts   |  2 ++
 ui/cypress/support/model/UserInput.ts              |  2 +-
 ui/cypress/support/utils/DataLakeUtils.ts          |  2 +-
 ui/cypress/support/utils/PipelineUtils.ts          |  2 ++
 ui/cypress/support/utils/StaticPropertyUtils.ts    |  7 ++--
 ui/package.json                                    |  3 +-
 .../static-code-input.component.html               | 19 ++++++++---
 .../static-code-input.component.ts                 | 39 ++++++++++++----------
 .../static-property.component.html                 |  4 +--
 .../user-defined-output.component.html             | 23 ++++++++++---
 13 files changed, 105 insertions(+), 56 deletions(-)

diff --git a/streampipes-extensions/pom.xml b/streampipes-extensions/pom.xml
index 451a1b8..c806db2 100644
--- a/streampipes-extensions/pom.xml
+++ b/streampipes-extensions/pom.xml
@@ -81,6 +81,7 @@
         <ddogleg.version>0.16</ddogleg.version>
         <errorprone-annotations.version>2.2.0</errorprone-annotations.version>
         <google-maps-services.version>0.10.0</google-maps-services.version>
+        <graalvm.js.version>21.3.0</graalvm.js.version>
         <iotdb.version>0.12.0</iotdb.version>
         <jackson.version>2.10.0</jackson.version>
         <java-websocket.version>1.4.0</java-websocket.version>
@@ -251,6 +252,16 @@
                 <version>${eclipse.milo.version}</version>
             </dependency>
             <dependency>
+                <groupId>org.graalvm.js</groupId>
+                <artifactId>js</artifactId>
+                <version>${graalvm.js.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.graalvm.js</groupId>
+                <artifactId>js-scriptengine</artifactId>
+                <version>${graalvm.js}</version>
+            </dependency>
+            <dependency>
                 <groupId>com.github.shyiko</groupId>
                 <artifactId>mysql-binlog-connector-java</artifactId>
                 <version>${mysql-binlog-connector.version}</version>
diff --git a/streampipes-extensions/streampipes-processors-enricher-jvm/pom.xml b/streampipes-extensions/streampipes-processors-enricher-jvm/pom.xml
index 8be96d8..4434115 100644
--- a/streampipes-extensions/streampipes-processors-enricher-jvm/pom.xml
+++ b/streampipes-extensions/streampipes-processors-enricher-jvm/pom.xml
@@ -37,6 +37,14 @@
             <artifactId>streampipes-sdk-bundle</artifactId>
             <version>0.69.0-SNAPSHOT</version>
         </dependency>
+        <dependency>
+            <groupId>org.graalvm.js</groupId>
+            <artifactId>js</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.graalvm.js</groupId>
+            <artifactId>js-scriptengine</artifactId>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/streampipes-extensions/streampipes-processors-enricher-jvm/src/main/java/org/apache/streampipes/processors/enricher/jvm/processor/jseval/JSEval.java b/streampipes-extensions/streampipes-processors-enricher-jvm/src/main/java/org/apache/streampipes/processors/enricher/jvm/processor/jseval/JSEval.java
index 9f9b44e..537a14c 100644
--- a/streampipes-extensions/streampipes-processors-enricher-jvm/src/main/java/org/apache/streampipes/processors/enricher/jvm/processor/jseval/JSEval.java
+++ b/streampipes-extensions/streampipes-processors-enricher-jvm/src/main/java/org/apache/streampipes/processors/enricher/jvm/processor/jseval/JSEval.java
@@ -22,30 +22,23 @@ import org.apache.streampipes.model.runtime.Event;
 import org.apache.streampipes.wrapper.context.EventProcessorRuntimeContext;
 import org.apache.streampipes.wrapper.routing.SpOutputCollector;
 import org.apache.streampipes.wrapper.runtime.EventProcessor;
+import org.graalvm.polyglot.Context;
+import org.graalvm.polyglot.Value;
+import org.graalvm.polyglot.proxy.ProxyObject;
 
 import java.util.HashMap;
 import java.util.Map;
-import javax.script.Invocable;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
 
 public class JSEval implements EventProcessor<JSEvalParameters> {
-    private static final String ENGINE_NAME = "JavaScript";
-    private ScriptEngine engine;
-    private String code;
+    private Context polyglot;
+    private Value function;
 
     @Override
     public void onInvocation(JSEvalParameters parameters, SpOutputCollector spOutputCollector,
                              EventProcessorRuntimeContext runtimeContext) throws SpRuntimeException {
-        ScriptEngineManager factory = new ScriptEngineManager();
-        engine = factory.getEngineByName(ENGINE_NAME);
-        code = parameters.getCode();
-        try {
-            engine.eval(code);
-        } catch (ScriptException e) {
-            throw new SpRuntimeException("Error in script: " + e.getMessage());
-        }
+        polyglot = Context.create();
+        String code = parameters.getCode();
+        function = polyglot.eval("js", "(" + code + ")");
     }
 
     @Override
@@ -53,19 +46,18 @@ public class JSEval implements EventProcessor<JSEvalParameters> {
         // create new event with input event's source info and schema info.
         Event outEvent = new Event(new HashMap<>(), event.getSourceInfo(), event.getSchemaInfo());
         try {
+
             final Map<String, Object> eventData = event.getRaw();
-            Object result = ((Invocable) engine).invokeFunction("process", eventData);
-            if (result != null) {
-                Map<String, Object> output = (Map<String, Object>) result;
-                output.forEach(outEvent::addField);
+
+            Object result = function.execute(ProxyObject.fromMap(eventData));
+            Map<String, Object> resultEvent =  ((Value) result).as(java.util.Map.class);
+            if (resultEvent != null) {
+                resultEvent.forEach(outEvent::addField);
                 outputCollector.collect(outEvent);
             }
-        } catch (ScriptException e) {
-            throw new SpRuntimeException("Error in script: " + e.getMessage());
+
         } catch (ClassCastException e) {
             throw new SpRuntimeException("`process` method must return a map with new event data.");
-        } catch (NoSuchMethodException e) {
-            throw new SpRuntimeException("`process(event){ return {}; };` method not found in script: " + code);
         }
     }
 
@@ -73,4 +65,5 @@ public class JSEval implements EventProcessor<JSEvalParameters> {
     public void onDetach() {
         // do nothing.
     }
+
 }
diff --git a/ui/cypress/support/model/PipelineElementInput.ts b/ui/cypress/support/model/PipelineElementInput.ts
index 025bc76..c58d5d3 100644
--- a/ui/cypress/support/model/PipelineElementInput.ts
+++ b/ui/cypress/support/model/PipelineElementInput.ts
@@ -17,8 +17,10 @@
  */
 
 import { UserInput } from './UserInput';
+import { OutputStrategyConfig } from './OutputStrategyConfig';
 
 export class PipelineElementInput {
     name: string;
     config: UserInput[];
+    output: OutputStrategyConfig;
 }
diff --git a/ui/cypress/support/model/UserInput.ts b/ui/cypress/support/model/UserInput.ts
index c431074..b940a6d 100644
--- a/ui/cypress/support/model/UserInput.ts
+++ b/ui/cypress/support/model/UserInput.ts
@@ -17,7 +17,7 @@
  */
 
 export class UserInput {
-    type: string | 'checkbox' | 'input' | 'file' | 'drop-down' | 'radio';
+    type: 'checkbox' | 'input' | 'file' | 'drop-down' | 'radio' | 'code-input' | 'click';
     selector: string;
     value: string;
 }
diff --git a/ui/cypress/support/utils/DataLakeUtils.ts b/ui/cypress/support/utils/DataLakeUtils.ts
index 21c73b4..3c54acf 100644
--- a/ui/cypress/support/utils/DataLakeUtils.ts
+++ b/ui/cypress/support/utils/DataLakeUtils.ts
@@ -197,7 +197,7 @@ export class DataLakeUtils {
       .type(`${value.toLocaleString()}{enter}`);
   }
 
-  private static resultEqual(actual: string, expected: string) {
+  private static resultEqual(expected: string, actual: string) {
     const expectedResult = DataLakeUtils.parseCsv(expected);
     const actualResult = DataLakeUtils.parseCsv(actual);
     expect(expectedResult).to.deep.equal(actualResult);
diff --git a/ui/cypress/support/utils/PipelineUtils.ts b/ui/cypress/support/utils/PipelineUtils.ts
index 762e461..5b998f9 100644
--- a/ui/cypress/support/utils/PipelineUtils.ts
+++ b/ui/cypress/support/utils/PipelineUtils.ts
@@ -18,6 +18,7 @@
 
 import { PipelineInput } from '../model/PipelineInput';
 import { StaticPropertyUtils } from './StaticPropertyUtils';
+import { OutputStrategyUtils } from './OutputStrategyUtils';
 
 export class PipelineUtils {
 
@@ -69,6 +70,7 @@ export class PipelineUtils {
     if (pipelineInput.processingElement) {
       cy.dataCy('sp-compatible-elements-' + pipelineInput.processingElement.name).click();
       StaticPropertyUtils.input(pipelineInput.processingElement.config);
+      OutputStrategyUtils.input(pipelineInput.processingElement.output);
       // Save configuration
       cy.dataCy('sp-element-configuration-save').click();
       // Select sink
diff --git a/ui/cypress/support/utils/StaticPropertyUtils.ts b/ui/cypress/support/utils/StaticPropertyUtils.ts
index 5216e02..708287c 100644
--- a/ui/cypress/support/utils/StaticPropertyUtils.ts
+++ b/ui/cypress/support/utils/StaticPropertyUtils.ts
@@ -32,9 +32,12 @@ export class StaticPropertyUtils {
         cy.dataCy(config.selector + config.value).click();
       } else if (config.type === 'click') {
         cy.dataCy(config.selector).click({ force: true });
+      } else if (config.type === 'code-input') {
+        cy.dataCy('reset-code-' + config.selector).click();
+        cy.dataCy('code-editor-' + config.selector).type(config.value);
       } else {
-        cy.dataCy(config.selector).type(config.value);
-      }
+          cy.dataCy(config.selector).type(config.value);
+        }
     });
   }
 }
diff --git a/ui/package.json b/ui/package.json
index 1e23aaf..186651a 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -85,8 +85,8 @@
     "rxjs": "6.6.2",
     "shepherd.js": "2.4.0",
     "showdown": "1.9.1",
-    "systemjs": "0.21.6",
     "swagger-ui": "^3.42.0",
+    "systemjs": "0.21.6",
     "tslib": "^2.0.0",
     "zone.js": "~0.11.4"
   },
@@ -99,6 +99,7 @@
     "@types/angular": "^1.7.4",
     "@types/jasmine": "~3.6.0",
     "@types/jqueryui": "^1.12.13",
+    "@types/jshint": "^2.12.1",
     "@types/leaflet": "^1.5.19",
     "@types/node": "^12.19.3",
     "@types/rx": "^4.1.2",
diff --git a/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.html b/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.html
index c7aec95..f754631 100644
--- a/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.html
+++ b/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.html
@@ -18,16 +18,27 @@
 
 <div fxFlex="100" fxLayout="column">
     <div fxFlex="100" fxLayout="row" fxLayoutAlign="start center">
-        <button mat-button mat-raised-button color="accent" class="small-button" (click)="resetCode()"
+        <button mat-button
+                mat-raised-button
+                color="accent"
+                class="small-button"
+                (click)="resetCode()"
                 style="margin-right:10px;margin-bottom:10px;">Reset code template
         </button>
+        <button mat-button
+                mat-raised-button
+                color="accent"
+                class="small-button"
+                (click)="cleanCode()"
+                [attr.data-cy]="'reset-code-' + fieldName"
+                style="margin-right:10px;margin-bottom:10px;">Clean code
+        </button>
     </div>
     <div fxFlex="100" fxLayout="row">
-
         <ngx-codemirror style="width:100%;"
                 [(ngModel)]="staticProperty.value"
-                [options]="editorOptions">
-
+                [options]="editorOptions"
+                [attr.data-cy]="'code-editor-' + fieldName">
         </ngx-codemirror>
 
     </div>
diff --git a/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.ts b/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.ts
index 38e5ed9..eb81268 100644
--- a/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.ts
+++ b/ui/src/app/core-ui/static-properties/static-code-input/static-code-input.component.ts
@@ -16,9 +16,9 @@
  *
  */
 
-import { CodeInputStaticProperty } from "../../../core-model/gen/streampipes-model";
-import { AbstractValidatedStaticPropertyRenderer } from "../base/abstract-validated-static-property";
-import { AfterViewInit, Component, OnInit } from "@angular/core";
+import { CodeInputStaticProperty } from '../../../core-model/gen/streampipes-model';
+import { AbstractValidatedStaticPropertyRenderer } from '../base/abstract-validated-static-property';
+import { AfterViewInit, Component, OnInit } from '@angular/core';
 
 import 'codemirror/mode/javascript/javascript';
 import 'codemirror/mode/python/python';
@@ -28,12 +28,12 @@ import 'codemirror/addon/hint/javascript-hint';
 import 'codemirror/addon/lint/javascript-lint';
 import 'codemirror/addon/lint/lint';
 import { JSHINT } from 'jshint';
-import * as CodeMirror from "codemirror";
+import * as CodeMirror from 'codemirror';
 
-(<any>window).JSHINT = JSHINT;
+(window as any).JSHINT = JSHINT;
 
 @Component({
-  selector: 'app-static-code-input',
+  selector: 'sp-static-code-input',
   templateUrl: './static-code-input.component.html',
   styleUrls: ['./static-code-input.component.scss']
 })
@@ -41,16 +41,16 @@ export class StaticCodeInputComponent
     extends AbstractValidatedStaticPropertyRenderer<CodeInputStaticProperty> implements OnInit, AfterViewInit {
 
   editorOptions = {
-    mode: "javascript",
+    mode: 'javascript',
     autoRefresh: true,
     theme: 'dracula',
     autoCloseBrackets: true,
     lineNumbers: true,
     lineWrapping: true,
-    gutters: ["CodeMirror-lint-markers"],
+    gutters: ['CodeMirror-lint-markers'],
     lint: true,
     extraKeys: {
-      "Ctrl-Space": "autocomplete"
+      'Ctrl-Space': 'autocomplete'
     }
   };
 
@@ -60,7 +60,7 @@ export class StaticCodeInputComponent
 
   ngOnInit() {
     this.applyLanguage();
-    if (!this.staticProperty.value || this.staticProperty.value === "") {
+    if (!this.staticProperty.value || this.staticProperty.value === '') {
       this.staticProperty.value = this.staticProperty.codeTemplate;
     }
   }
@@ -85,19 +85,24 @@ export class StaticCodeInputComponent
     this.staticProperty.value = this.staticProperty.codeTemplate;
   }
 
+  cleanCode() {
+    this.staticProperty.value = '';
+  }
+
+
   enableCodeHints() {
     if (this.editorOptions.mode === 'javascript') {
-      var jsHint = (CodeMirror as any).hint.javascript;
+      const jsHint = (CodeMirror as any).hint.javascript;
       (CodeMirror as any).hint.javascript = (cm) => {
-        let cursor = cm.getCursor();
-        let token = cm.getTokenAt(cursor);
+        const cursor = cm.getCursor();
+        const token = cm.getTokenAt(cursor);
         let inner = {from: cm.getCursor(), to: cm.getCursor(), list: []};
-        let previousCursor = {line: cursor.line, ch: (cursor.ch - 1), sticky: null}
-        let previousToken = cm.getTokenAt(previousCursor);
-        if (token.string === "." && previousToken.string === "event") {
+        const previousCursor = {line: cursor.line, ch: (cursor.ch - 1), sticky: null};
+        const previousToken = cm.getTokenAt(previousCursor);
+        if (token.string === '.' && previousToken.string === 'event') {
           this.eventSchemas[0].eventProperties.forEach(ep => {
             inner.list.unshift(ep.runtimeName);
-          })
+          });
         } else {
           inner = jsHint(cm);
         }
diff --git a/ui/src/app/core-ui/static-properties/static-property.component.html b/ui/src/app/core-ui/static-properties/static-property.component.html
index 006842a..2547720 100644
--- a/ui/src/app/core-ui/static-properties/static-property.component.html
+++ b/ui/src/app/core-ui/static-properties/static-property.component.html
@@ -24,13 +24,13 @@
             <mat-hint class="description">{{staticProperty.description}}</mat-hint>
         </div>
         <div fxFlex="100">
-            <app-static-code-input *ngIf="isCodeInputStaticProperty(staticProperty)"
+            <sp-static-code-input *ngIf="isCodeInputStaticProperty(staticProperty)"
                                    [staticProperty]="staticProperty"
                                    [parentForm]="parentForm"
                                    [eventSchemas]="eventSchemas"
                                    [fieldName]="fieldName"
                                    (updateEmitter)="emitUpdate($event)">
-            </app-static-code-input>
+            </sp-static-code-input>
 
             <app-static-secret-input *ngIf="isSecretStaticProperty(staticProperty)"
                                      [staticProperty]="staticProperty"
diff --git a/ui/src/app/editor/components/output-strategy/user-defined-output/user-defined-output.component.html b/ui/src/app/editor/components/output-strategy/user-defined-output/user-defined-output.component.html
index 952b8c0..17b3838 100644
--- a/ui/src/app/editor/components/output-strategy/user-defined-output/user-defined-output.component.html
+++ b/ui/src/app/editor/components/output-strategy/user-defined-output/user-defined-output.component.html
@@ -20,7 +20,9 @@
     <div fxFlex="100" fxLayout="row" fxLayoutAlign="start center" style="margin-bottom:20px;">
         <button mat-button mat-raised-button color="accent" class="small-button"
                 (click)="applyDefaultSchema()"
-                style="margin-right:10px;margin-left:10px;" [disabled]="restrictedEditMode">Use input schema
+                style="margin-right:10px;margin-left:10px;"
+                [disabled]="restrictedEditMode"
+                data-cy="use-input-schema">Use input schema
         </button>
     </div>
 
@@ -28,14 +30,18 @@
         <div fxLayout="column" fxFlex="30">
             <mat-form-field fxFlex>
                 <mat-label>Runtime name</mat-label>
-                <input [(ngModel)]="ep.runtimeName" fxFlex
+                <input [(ngModel)]="ep.runtimeName"
+                       data-cy="runtime-name"
+                       fxFlex
                        matInput>
             </mat-form-field>
         </div>
         <div fxLayout="column" fxFlex="30">
             <mat-form-field class="example-full-width">
                 <mat-label>Runtime type</mat-label>
-                <mat-select [(ngModel)]="ep.runtimeType" [disabled]="restrictedEditMode">
+                <mat-select [(ngModel)]="ep.runtimeType"
+                            [disabled]="restrictedEditMode"
+                            data-cy="runtime-type">
                     <mat-option *ngFor="let primitive of primitiveClasses" [value]="primitive.id">
                         {{primitive.label}}
                     </mat-option>
@@ -45,7 +51,10 @@
         <div fxLayout="column" fxFlex="30">
             <mat-form-field fxFlex>
                 <mat-label>Semantic type</mat-label>
-                <input [(ngModel)]="ep.domainProperties[0]" [disabled]="restrictedEditMode" fxFlex
+                <input [(ngModel)]="ep.domainProperties[0]"
+                       [disabled]="restrictedEditMode"
+                       data-cy="semantic-type"
+                       fxFlex
                        matInput>
             </mat-form-field>
         </div>
@@ -56,7 +65,11 @@
         </div>
     </div>
     <div>
-        <button mat-button mat-flat-button (click)="addProperty()" [disabled]="restrictedEditMode">
+        <button mat-button
+                mat-flat-button
+                (click)="addProperty()"
+                [disabled]="restrictedEditMode"
+                data-cy="add-field">
             <mat-icon class="icon">add</mat-icon>
             <span>Add field</span>
         </button>