Search in sources :

Example 21 with Scriptable

use of org.mozilla.javascript.Scriptable in project sling by apache.

the class RhinoJavaScriptEngineFactory method getRootScope.

@SuppressWarnings("unchecked")
private Scriptable getRootScope() {
    if (rootScope == null) {
        final Context rhinoContext = Context.enter();
        try {
            rhinoContext.setOptimizationLevel(optimizationLevel);
            Scriptable tmpScope = rhinoContext.initStandardObjects(new ImporterTopLevel(rhinoContext), false);
            // default classes
            addHostObjects(tmpScope, (Class<? extends ScriptableObject>[]) HOSTOBJECT_CLASSES);
            // provided classes
            for (RhinoHostObjectProvider provider : hostObjectProvider) {
                addHostObjects(tmpScope, provider.getHostObjectClasses());
                addImportedClasses(rhinoContext, tmpScope, provider.getImportedClasses());
                addImportedPackages(rhinoContext, tmpScope, provider.getImportedPackages());
            }
            // only assign the root scope when complete set up
            rootScope = tmpScope;
        } finally {
            // ensure the context is exited after setting up the
            // the new root scope
            Context.exit();
        }
    }
    return rootScope;
}
Also used : ComponentContext(org.osgi.service.component.ComponentContext) Context(org.mozilla.javascript.Context) BundleContext(org.osgi.framework.BundleContext) ImporterTopLevel(org.mozilla.javascript.ImporterTopLevel) ScriptableObject(org.mozilla.javascript.ScriptableObject) RhinoHostObjectProvider(org.apache.sling.scripting.javascript.RhinoHostObjectProvider) NativeJavaClass(org.mozilla.javascript.NativeJavaClass) Scriptable(org.mozilla.javascript.Scriptable)

Example 22 with Scriptable

use of org.mozilla.javascript.Scriptable in project sling by apache.

the class RhinoJavaScriptEngineFactory method addHostObjects.

// ---------- internal
private void addHostObjects(Scriptable scope, Class<? extends Scriptable>[] classes) {
    if (classes != null) {
        for (Class<? extends Scriptable> clazz : classes) {
            try {
                // register the host object
                ScriptableObject.defineClass(scope, clazz);
                if (SlingWrapper.class.isAssignableFrom(clazz)) {
                    // SlingWrappers can map to several classes if needed
                    final SlingWrapper hostWrapper = (SlingWrapper) clazz.newInstance();
                    for (Class<?> c : hostWrapper.getWrappedClasses()) {
                        getWrapFactory().registerWrapper(c, hostWrapper.getClassName());
                    }
                } else {
                    // but other Scriptable host objects need to be
                    // registered as well
                    final Scriptable host = clazz.newInstance();
                    getWrapFactory().registerWrapper(host.getClass(), host.getClassName());
                }
            } catch (Throwable t) {
                log.warn("addHostObjects: Cannot prepare host object " + clazz, t);
            }
        }
    }
}
Also used : SlingWrapper(org.apache.sling.scripting.javascript.SlingWrapper) Scriptable(org.mozilla.javascript.Scriptable)

Example 23 with Scriptable

use of org.mozilla.javascript.Scriptable in project gradle by gradle.

the class RhinoWorkerUtils method parseRhino.

public static <T> T parseRhino(File rhinoScript, ScopeOperation<T> operation) {
    Context context = Context.enter();
    try {
        operation.initContext(context);
        Scriptable scope = context.initStandardObjects();
        String printFunction = "function print(message) {}";
        context.evaluateString(scope, printFunction, "print", 1, null);
        context.evaluateString(scope, readFile(rhinoScript, "UTF-8"), rhinoScript.getName(), 1, null);
        return operation.action(scope, context);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) Scriptable(org.mozilla.javascript.Scriptable)

Example 24 with Scriptable

use of org.mozilla.javascript.Scriptable in project gradle by gradle.

the class RhinoWorkerUtils method parse.

public static Scriptable parse(File source, String encoding, Action<Context> contextConfig) {
    Context context = Context.enter();
    if (contextConfig != null) {
        contextConfig.execute(context);
    }
    Scriptable scope = context.initStandardObjects();
    try {
        Reader reader = new InputStreamReader(new FileInputStream(source), encoding);
        try {
            context.evaluateReader(scope, reader, source.getName(), 0, null);
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        Context.exit();
    }
    return scope;
}
Also used : Context(org.mozilla.javascript.Context) UncheckedIOException(org.gradle.api.UncheckedIOException) UncheckedIOException(org.gradle.api.UncheckedIOException) Scriptable(org.mozilla.javascript.Scriptable)

Example 25 with Scriptable

use of org.mozilla.javascript.Scriptable in project pentaho-kettle by pentaho.

the class ScriptDialog method test.

private boolean test(boolean getvars, boolean popup) {
    boolean retval = true;
    StyledTextComp wScript = getStyledTextComp();
    String scr = wScript.getText();
    KettleException testException = null;
    Context jscx;
    Scriptable jsscope;
    // Script jsscript;
    // Making Refresh to get Active Script State
    refreshScripts();
    jscx = ContextFactory.getGlobal().enterContext();
    jscx.setOptimizationLevel(-1);
    jsscope = jscx.initStandardObjects(null, false);
    // Adding the existing Scripts to the Context
    for (int i = 0; i < folder.getItemCount(); i++) {
        StyledTextComp sItem = getStyledTextComp(folder.getItem(i));
        Scriptable jsR = Context.toObject(sItem.getText(), jsscope);
        jsscope.put(folder.getItem(i).getText(), jsscope, jsR);
    }
    // Adding the Name of the Transformation to the Context
    jsscope.put("_TransformationName_", jsscope, this.stepname);
    try {
        RowMetaInterface rowMeta = transMeta.getPrevStepFields(stepname);
        if (rowMeta != null) {
            ScriptDummy dummyStep = new ScriptDummy(rowMeta, transMeta.getStepFields(stepname));
            Scriptable jsvalue = Context.toObject(dummyStep, jsscope);
            jsscope.put("_step_", jsscope, jsvalue);
            // Modification for Additional Script parsing
            try {
                if (input.getAddClasses() != null) {
                    for (int i = 0; i < input.getAddClasses().length; i++) {
                        Object jsOut = Context.javaToJS(input.getAddClasses()[i].getAddObject(), jsscope);
                        ScriptableObject.putProperty(jsscope, input.getAddClasses()[i].getJSName(), jsOut);
                    }
                }
            } catch (Exception e) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddToContext", e.toString()));
                retval = false;
            }
            // Adding some default JavaScriptFunctions to the System
            try {
                Context.javaToJS(ScriptAddedFunctions.class, jsscope);
                ((ScriptableObject) jsscope).defineFunctionProperties(jsFunctionList, ScriptAddedFunctions.class, ScriptableObject.DONTENUM);
            } catch (Exception ex) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddDefaultFunctions", ex.toString()));
                retval = false;
            }
            // Adding some Constants to the JavaScript
            try {
                jsscope.put("SKIP_TRANSFORMATION", jsscope, Integer.valueOf(SKIP_TRANSFORMATION));
                jsscope.put("ABORT_TRANSFORMATION", jsscope, Integer.valueOf(ABORT_TRANSFORMATION));
                jsscope.put("ERROR_TRANSFORMATION", jsscope, Integer.valueOf(ERROR_TRANSFORMATION));
                jsscope.put("CONTINUE_TRANSFORMATION", jsscope, Integer.valueOf(CONTINUE_TRANSFORMATION));
            } catch (Exception ex) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddTransformationConstants", ex.toString()));
                retval = false;
            }
            try {
                Object[] row = new Object[rowMeta.size()];
                Scriptable jsRowMeta = Context.toObject(rowMeta, jsscope);
                jsscope.put("rowMeta", jsscope, jsRowMeta);
                for (int i = 0; i < rowMeta.size(); i++) {
                    ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
                    Object valueData = null;
                    // 
                    if (valueMeta.isDate()) {
                        valueData = new Date();
                    }
                    if (valueMeta.isString()) {
                        valueData = "test value test value test value test value test " + "value test value test value test value test value test value";
                    }
                    if (valueMeta.isInteger()) {
                        valueData = Long.valueOf(0L);
                    }
                    if (valueMeta.isNumber()) {
                        valueData = new Double(0.0);
                    }
                    if (valueMeta.isBigNumber()) {
                        valueData = BigDecimal.ZERO;
                    }
                    if (valueMeta.isBoolean()) {
                        valueData = Boolean.TRUE;
                    }
                    if (valueMeta.isBinary()) {
                        valueData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    }
                    if (valueMeta.isStorageBinaryString()) {
                        valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
                    }
                    row[i] = valueData;
                    Scriptable jsarg = Context.toObject(valueData, jsscope);
                    jsscope.put(valueMeta.getName(), jsscope, jsarg);
                }
                // OK, for these input values, we're going to allow the user to edit the default values...
                // We are displaying a
                // 2)
                // Add support for Value class (new Value())
                Scriptable jsval = Context.toObject(Value.class, jsscope);
                jsscope.put("Value", jsscope, jsval);
                // Add the old style row object for compatibility reasons...
                // 
                Scriptable jsRow = Context.toObject(row, jsscope);
                jsscope.put("row", jsscope, jsRow);
            } catch (Exception ev) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddInputFields", ev.toString()));
                retval = false;
            }
            try {
                // Checking for StartScript
                if (strActiveStartScript != null && !folder.getSelection().getText().equals(strActiveStartScript) && strActiveStartScript.length() > 0) {
                    String strStartScript = getStyledTextComp(folder.getItem(getCTabPosition(strActiveStartScript))).getText();
                    /* Object startScript = */
                    jscx.evaluateString(jsscope, strStartScript, "trans_Start", 1, null);
                }
            } catch (Exception e) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldProcessStartScript", e.toString()));
                retval = false;
            }
            try {
                Script evalScript = jscx.compileString(scr, "script", 1, null);
                evalScript.exec(jscx, jsscope);
                if (getvars) {
                    ScriptNode tree = parseVariables(jscx, jsscope, scr, "script", 1, null);
                    for (int i = 0; i < tree.getParamAndVarCount(); i++) {
                        String varname = tree.getParamOrVarName(i);
                        if (!varname.equalsIgnoreCase("row") && !varname.equalsIgnoreCase("trans_Status")) {
                            int type = ValueMetaInterface.TYPE_STRING;
                            int length = -1, precision = -1;
                            Object result = jsscope.get(varname, jsscope);
                            if (result != null) {
                                String classname = result.getClass().getName();
                                if (classname.equalsIgnoreCase("java.lang.Byte")) {
                                    // MAX = 127
                                    type = ValueMetaInterface.TYPE_INTEGER;
                                    length = 3;
                                    precision = 0;
                                } else if (classname.equalsIgnoreCase("java.lang.Integer")) {
                                    // MAX = 2147483647
                                    type = ValueMetaInterface.TYPE_INTEGER;
                                    length = 9;
                                    precision = 0;
                                } else if (classname.equalsIgnoreCase("java.lang.Long")) {
                                    // MAX = 9223372036854775807
                                    type = ValueMetaInterface.TYPE_INTEGER;
                                    length = 18;
                                    precision = 0;
                                } else if (classname.equalsIgnoreCase("java.lang.Double")) {
                                    type = ValueMetaInterface.TYPE_NUMBER;
                                    length = 16;
                                    precision = 2;
                                } else if (classname.equalsIgnoreCase("org.mozilla.javascript.NativeDate") || classname.equalsIgnoreCase("java.util.Date")) {
                                    type = ValueMetaInterface.TYPE_DATE;
                                } else if (classname.equalsIgnoreCase("java.lang.Boolean")) {
                                    type = ValueMetaInterface.TYPE_BOOLEAN;
                                }
                            }
                            TableItem ti = new TableItem(wFields.table, SWT.NONE);
                            ti.setText(1, varname);
                            ti.setText(2, "");
                            ti.setText(3, ValueMetaFactory.getValueMetaName(type));
                            ti.setText(4, length >= 0 ? ("" + length) : "");
                            ti.setText(5, precision >= 0 ? ("" + precision) : "");
                            // If the variable name exists in the input, suggest to replace the value
                            // 
                            ti.setText(6, (rowMeta.indexOfValue(varname) >= 0) ? YES_NO_COMBO[1] : YES_NO_COMBO[0]);
                        }
                    }
                    wFields.removeEmptyRows();
                    wFields.setRowNums();
                    wFields.optWidth(true);
                }
            // End Script!
            } catch (EvaluatorException e) {
                String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
                String message = BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position);
                testException = new KettleException(message, e);
                retval = false;
            } catch (JavaScriptException e) {
                String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
                String message = BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position);
                testException = new KettleException(message, e);
                retval = false;
            } catch (Exception e) {
                testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript2"), e);
                retval = false;
            }
        } else {
            testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotGetFields"));
            retval = false;
        }
        if (popup) {
            if (retval) {
                if (!getvars) {
                    MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
                    mb.setMessage(BaseMessages.getString(PKG, "ScriptDialog.ScriptCompilationOK") + Const.CR);
                    mb.setText("OK");
                    mb.open();
                }
            } else {
                new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogMessage"), testException);
            }
        }
    } catch (KettleException ke) {
        retval = false;
        new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogMessage"), ke);
    } finally {
        if (jscx != null) {
            Context.exit();
        }
    }
    return retval;
}
Also used : StyledTextComp(org.pentaho.di.ui.core.widget.StyledTextComp) Context(org.mozilla.javascript.Context) KettleException(org.pentaho.di.core.exception.KettleException) Script(org.mozilla.javascript.Script) ScriptValuesScript(org.pentaho.di.trans.steps.script.ScriptValuesScript) ScriptableObject(org.mozilla.javascript.ScriptableObject) TableItem(org.eclipse.swt.widgets.TableItem) ErrorDialog(org.pentaho.di.ui.core.dialog.ErrorDialog) RowMetaInterface(org.pentaho.di.core.row.RowMetaInterface) Scriptable(org.mozilla.javascript.Scriptable) ScriptNode(org.mozilla.javascript.ast.ScriptNode) Point(org.eclipse.swt.graphics.Point) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) KettleException(org.pentaho.di.core.exception.KettleException) Date(java.util.Date) ValueMetaInterface(org.pentaho.di.core.row.ValueMetaInterface) JavaScriptException(org.mozilla.javascript.JavaScriptException) MessageBox(org.eclipse.swt.widgets.MessageBox) EvaluatorException(org.mozilla.javascript.EvaluatorException) ScriptableObject(org.mozilla.javascript.ScriptableObject) ScriptDummy(org.pentaho.di.trans.steps.script.ScriptDummy)

Aggregations

Scriptable (org.mozilla.javascript.Scriptable)151 Context (org.mozilla.javascript.Context)67 ScriptableObject (org.mozilla.javascript.ScriptableObject)47 Test (org.junit.Test)17 ContextAction (org.mozilla.javascript.ContextAction)12 Script (org.mozilla.javascript.Script)10 Function (org.mozilla.javascript.Function)9 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)9 ArrayList (java.util.ArrayList)8 NativeObject (org.mozilla.javascript.NativeObject)8 Date (java.util.Date)7 RhinoException (org.mozilla.javascript.RhinoException)7 IOException (java.io.IOException)6 Map (java.util.Map)6 BProgram (il.ac.bgu.cs.bp.bpjs.model.BProgram)5 Notifier (org.apache.cxf.javascript.JavascriptTestUtilities.Notifier)5 KettleException (org.pentaho.di.core.exception.KettleException)5 File (java.io.File)4 InputStreamReader (java.io.InputStreamReader)4 EvaluatorException (org.mozilla.javascript.EvaluatorException)4