Search in sources :

Example 36 with Function

use of org.mozilla.javascript.Function in project LoboEvolution by LoboEvolution.

the class JavaObjectWrapper method get.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.mozilla.javascript.ScriptableObject#get(java.lang.String,
	 * org.mozilla.javascript.Scriptable)
	 */
/**
 * {@inheritDoc}
 */
@Override
public Object get(String name, Scriptable start) {
    PropertyInfo pinfo = this.classWrapper.getProperty(name);
    if (pinfo != null) {
        Method getter = pinfo.getGetter();
        if (getter == null) {
            throw new EvaluatorException("Property '" + name + "' is not readable");
        }
        try {
            // Cannot retain delegate with a strong reference.
            Object javaObject = this.getJavaObject();
            if (javaObject == null) {
                throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null.");
            }
            Object val = getter.invoke(javaObject, (Object[]) null);
            return JavaScript.getInstance().getJavascriptObject(val, start.getParentScope());
        } catch (Exception err) {
            logger.log(Level.SEVERE, err.getMessage(), err);
            return new Object();
        }
    } else {
        Function f = this.classWrapper.getFunction(name);
        if (f != null) {
            return f;
        } else {
            // Should check properties set in context
            // first. Consider element IDs should not
            // override Window variables set by user.
            Object result = super.get(name, start);
            if (result != Scriptable.NOT_FOUND) {
                return result;
            }
            PropertyInfo ni = this.classWrapper.getNameIndexer();
            if (ni != null) {
                Method getter = ni.getGetter();
                if (getter != null) {
                    // Cannot retain delegate with a strong reference.
                    Object javaObject = this.getJavaObject();
                    if (javaObject == null) {
                        throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null.");
                    }
                    try {
                        Object val = getter.invoke(javaObject, name);
                        if (val == null) {
                            // There might not be an indexer setter.
                            return super.get(name, start);
                        } else {
                            return JavaScript.getInstance().getJavascriptObject(val, start.getParentScope());
                        }
                    } catch (Exception err) {
                        logger.log(Level.SEVERE, err.getMessage(), err);
                    }
                }
            }
            return Scriptable.NOT_FOUND;
        }
    }
}
Also used : Function(org.mozilla.javascript.Function) EvaluatorException(org.mozilla.javascript.EvaluatorException) ScriptableObject(org.mozilla.javascript.ScriptableObject) Method(java.lang.reflect.Method) PropertyInfo(org.loboevolution.info.PropertyInfo) EvaluatorException(org.mozilla.javascript.EvaluatorException)

Example 37 with Function

use of org.mozilla.javascript.Function in project LoboEvolution by LoboEvolution.

the class JavaScript method defineElementClass.

public void defineElementClass(Scriptable scope, final Document document, final String jsClassName, final String elementName, Class<?> javaClass) {
    JavaInstantiator ji = () -> {
        Document d = document;
        if (d == null) {
            throw new IllegalStateException("Document not set in current context.");
        }
        return d.createElement(elementName);
    };
    JavaClassWrapper classWrapper = JavaClassWrapperFactory.getInstance().getClassWrapper(javaClass);
    Function constructorFunction = new JavaConstructorObject(jsClassName, classWrapper, ji);
    ScriptableObject.defineProperty(scope, jsClassName, constructorFunction, ScriptableObject.READONLY);
}
Also used : Function(org.mozilla.javascript.Function) Document(org.loboevolution.html.node.Document)

Example 38 with Function

use of org.mozilla.javascript.Function in project servoy-client by Servoy.

the class HeadlessClientFactoryInternal method createImportHookClient.

public static ISessionClient createImportHookClient(final Solution importHookModule, final IXMLImportUserChannel channel) throws Exception {
    final String[] loadException = new String[1];
    // assuming no login and no method args for import hooks
    SessionClient sc = new SessionClient(null, null, null, null, null, importHookModule.getName()) {

        @Override
        protected IActiveSolutionHandler createActiveSolutionHandler() {
            IApplicationServer as = ApplicationServerRegistry.getService(IApplicationServer.class);
            return new LocalActiveSolutionHandler(as, this) {

                @Override
                protected Solution loadSolution(RootObjectMetaData solutionDef) throws RemoteException, RepositoryException {
                    // grab the latest version (-1) not the active one, because the hook was not yet activated.
                    return (Solution) ((IDeveloperRepository) getRepository()).getRootObject(solutionDef.getRootObjectId(), -1);
                }
            };
        }

        @Override
        protected IExecutingEnviroment createScriptEngine() {
            return new ScriptEngine(this) {

                @Override
                public Object executeFunction(Function f, Scriptable scope, Scriptable thisObject, Object[] args, boolean focusEvent, boolean throwException) throws Exception {
                    // always throw exception
                    return super.executeFunction(f, scope, thisObject, args, focusEvent, true);
                }
            };
        }

        @Override
        public void reportError(String msg, Object detail) {
            super.reportError(msg, detail);
            loadException[0] = msg;
            if (detail instanceof JavaScriptException && ((JavaScriptException) detail).getValue() instanceof Scriptable) {
                loadException[0] += " " + Utils.getScriptableString((Scriptable) ((JavaScriptException) detail).getValue());
            }
            if (detail instanceof Exception) {
                loadException[0] += " " + ((Exception) detail).getMessage();
            }
        }
    };
    sc.setUseLoginSolution(false);
    String userName = channel.getImporterUsername();
    if (userName != null) {
        // let the import hook client run with credentials from the logged in user from the admin page.
        sc.getClientInfo().setUserUid(ApplicationServerRegistry.get().getUserManager().getUserUID(sc.getClientID(), userName));
        sc.getClientInfo().setUserName(userName);
    }
    sc.setOutputChannel(channel);
    sc.loadSolution(importHookModule.getName());
    if (loadException[0] != null) {
        sc.shutDown(true);
        throw new RepositoryException(loadException[0]);
    }
    return sc;
}
Also used : RootObjectMetaData(com.servoy.j2db.persistence.RootObjectMetaData) ISessionClient(com.servoy.j2db.ISessionClient) IApplicationServer(com.servoy.j2db.server.shared.IApplicationServer) RepositoryException(com.servoy.j2db.persistence.RepositoryException) LocalActiveSolutionHandler(com.servoy.j2db.LocalActiveSolutionHandler) Scriptable(org.mozilla.javascript.Scriptable) ScriptEngine(com.servoy.j2db.scripting.ScriptEngine) JavaScriptException(org.mozilla.javascript.JavaScriptException) RemoteException(java.rmi.RemoteException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) JavaScriptException(org.mozilla.javascript.JavaScriptException) Function(org.mozilla.javascript.Function) Solution(com.servoy.j2db.persistence.Solution)

Example 39 with Function

use of org.mozilla.javascript.Function in project servoy-client by Servoy.

the class DataAdapterList method executeInlineScript.

/**
 * @param args args to replace in script - used for HTML-triggered executeInlineScript; so calls generated via HTMLTagsConverter.convert(String, IServoyDataConverterContext, boolean) inside some piece of HTML
 * @param appendingArgs args to append in script execution - used for component/service client side code triggered executeInlineScript.
 */
@Override
public Object executeInlineScript(String script, JSONObject args, JSONArray appendingArgs) {
    String decryptedScript = HTMLTagsConverter.decryptInlineScript(script, args);
    if (appendingArgs != null && decryptedScript.endsWith("()")) {
        // this is an executeInlineScript called from component/service client-side code
        ArrayList<Object> javaArguments = new ArrayList<Object>();
        Object argObj = null;
        BrowserConverterContext dataConverterContext = new BrowserConverterContext((WebFormUI) formController.getFormUI(), PushToServerEnum.allow);
        for (int i = 0; i < appendingArgs.length(); i++) {
            try {
                argObj = ServoyJSONObject.jsonNullToNull(appendingArgs.get(i));
                if (argObj instanceof JSONObject) {
                    // $NON-NLS-1$
                    String typeHint = ((JSONObject) argObj).optString("svyType", null);
                    if (typeHint != null) {
                        IPropertyType<?> propertyType = TypesRegistry.getType(typeHint);
                        if (propertyType instanceof IPropertyConverterForBrowser<?>) {
                            javaArguments.add(((IPropertyConverterForBrowser<?>) propertyType).fromJSON(argObj, null, null, /*
											 * TODO this shouldn't be null! Make this better - maybe parse the type or just instantiate a property description
											 * if we don't want full support for what can be defined in spec file as a type
											 */
                            dataConverterContext, null));
                            continue;
                        }
                    }
                }
            } catch (JSONException e) {
                Debug.error(e);
            }
            javaArguments.add(argObj);
        }
        String functionName = decryptedScript.substring(0, decryptedScript.length() - 2);
        int startIdx = functionName.lastIndexOf('.');
        String noPrefixFunctionName = functionName.substring(startIdx > -1 ? startIdx + 1 : 0, functionName.length());
        Scriptable scope = null;
        Function f = null;
        if (functionName.startsWith("forms.")) {
            String formName = functionName.substring("forms.".length(), startIdx);
            FormScope formScope = formController.getFormScope();
            // this is a function that is on a form that is not the active window form.
            if (!formController.getName().equals(formName)) {
                formScope = getApplication().getFormManager().getForm(formName).getFormScope();
            }
            f = formScope.getFunctionByName(noPrefixFunctionName);
            if (f != null && f != Scriptable.NOT_FOUND) {
                scope = formScope;
            }
        } else if (functionName.startsWith("entity.")) {
            scope = (Scriptable) formController.getFoundSet();
            f = (Function) scope.getPrototype().get(noPrefixFunctionName, scope);
        } else {
            ScriptMethod scriptMethod = formController.getApplication().getFlattenedSolution().getScriptMethod(functionName);
            if (scriptMethod != null) {
                scope = formController.getApplication().getScriptEngine().getScopesScope().getGlobalScope(scriptMethod.getScopeName());
            }
            if (scope != null) {
                f = ((GlobalScope) scope).getFunctionByName(noPrefixFunctionName);
            }
        }
        try {
            return formController.getApplication().getScriptEngine().executeFunction(f, scope, scope, javaArguments.toArray(), false, false);
        } catch (Exception ex) {
            Debug.error(ex);
            return null;
        }
    }
    return decryptedScript != null ? formController.eval(decryptedScript) : null;
}
Also used : GlobalScope(com.servoy.j2db.scripting.GlobalScope) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) Scriptable(org.mozilla.javascript.Scriptable) JSONException(org.json.JSONException) ApplicationException(com.servoy.j2db.ApplicationException) IllegalChangeFromClientException(org.sablo.IllegalChangeFromClientException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) FormScope(com.servoy.j2db.scripting.FormScope) Function(org.mozilla.javascript.Function) JSONObject(org.json.JSONObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) IPropertyConverterForBrowser(org.sablo.specification.property.IPropertyConverterForBrowser) JSONObject(org.json.JSONObject) BaseWebObject(org.sablo.BaseWebObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) BrowserConverterContext(org.sablo.specification.property.BrowserConverterContext) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod)

Example 40 with Function

use of org.mozilla.javascript.Function in project servoy-client by Servoy.

the class NGFormManager method makeSolutionSettings.

public void makeSolutionSettings(Solution s) {
    Solution solution = s;
    Iterator<Form> e = application.getFlattenedSolution().getForms(true);
    // add all forms first, they may be referred to in the login form
    Form first = application.getFlattenedSolution().getForm(solution.getFirstFormID());
    boolean firstFormCanBeInstantiated = application.getFlattenedSolution().formCanBeInstantiated(first);
    if (!firstFormCanBeInstantiated) {
        Solution[] modules = application.getFlattenedSolution().getModules();
        if (modules != null) {
            for (Solution module : modules) {
                if (module.getFirstFormID() > 0) {
                    first = application.getFlattenedSolution().getForm(module.getFirstFormID());
                    firstFormCanBeInstantiated = application.getFlattenedSolution().formCanBeInstantiated(first);
                    if (firstFormCanBeInstantiated)
                        break;
                }
            }
        }
    }
    while (e.hasNext()) {
        Form form = e.next();
        if (application.getFlattenedSolution().formCanBeInstantiated(form)) {
            if (!firstFormCanBeInstantiated)
                first = form;
            firstFormCanBeInstantiated = true;
        }
        // add anyway, the form may be used in scripting
        addForm(form, form.equals(first));
    }
    if (firstFormCanBeInstantiated) {
        // start in browse mode
        application.getModeManager().setMode(IModeManager.EDIT_MODE);
    }
    boolean showLoginForm = (solution.getLoginFormID() > 0 && solution.getMustAuthenticate() && application.getUserUID() == null);
    if (application.getUserUID() == null) {
        ScriptMethod onBeforeLogin = application.getFlattenedSolution().getScriptMethod(solution.getOnBeforeLoginMethodID());
        if (onBeforeLogin != null) {
            try {
                Object[] paramArray = null;
                Object[] clientArray = ((ClientState) application).getPreferedSolutionMethodArguments();
                if (clientArray != null && clientArray.length > 1) {
                    paramArray = new Object[] { clientArray[1] };
                }
                application.getScriptEngine().getScopesScope().executeGlobalFunction(onBeforeLogin.getScopeName(), onBeforeLogin.getName(), Utils.arrayMerge(paramArray, Utils.parseJSExpressions(solution.getFlattenedMethodArguments("onBeforeLoginMethodID"))), false, false);
            } catch (Exception e1) {
                application.reportError(// $NON-NLS-1$
                Messages.getString("servoy.formManager.error.ExecutingOpenSolutionMethod", new Object[] { onBeforeLogin.getName() }), e1);
            }
        }
    }
    if (solution.getLoginFormID() > 0 && solution.getMustAuthenticate() && application.getUserUID() == null) {
        Form login = application.getFlattenedSolution().getForm(solution.getLoginFormID());
        if (application.getFlattenedSolution().formCanBeInstantiated(login) && loginForm == null) {
            // must set the login form early so its even correct if onload of login form is called
            loginForm = login;
            showFormInMainPanel(login.getName());
            // stop and recall this method from security.login(...)!
            return;
        }
    } else if (showLoginForm) {
        // there was a login in onBeforeLogin, so only second call to makeSolutionSettings should go further
        return;
    }
    IBasicMainContainer currentContainer = getCurrentContainer();
    if (solution.getLoginFormID() > 0 && solution.getMustAuthenticate() && application.getUserUID() != null && loginForm != null) {
        if (currentContainer.getController() != null && loginForm.getName().equals(currentContainer.getController().getForm().getName())) {
            hideFormIfVisible(currentContainer.getController());
            currentContainer.setController(null);
        }
        // clear and continue
        loginForm = null;
    }
    ScriptMethod sm = application.getFlattenedSolution().getScriptMethod(solution.getOnOpenMethodID());
    Object[] solutionOpenMethodArgs = null;
    String preferedSolutionMethodName = ((ClientState) application).getPreferedSolutionMethodNameToCall();
    if (preferedSolutionMethodName == null && ((ClientState) application).getPreferedSolutionMethodArguments() != null) {
        solutionOpenMethodArgs = ((ClientState) application).getPreferedSolutionMethodArguments();
    }
    if (sm != null) {
        try {
            application.getScriptEngine().getScopesScope().executeGlobalFunction(sm.getScopeName(), sm.getName(), Utils.arrayMerge(solutionOpenMethodArgs, Utils.parseJSExpressions(solution.getFlattenedMethodArguments("onOpenMethodID"))), false, false);
            if (application.getSolution() == null)
                return;
        } catch (Exception e1) {
            // $NON-NLS-1$
            application.reportError(Messages.getString("servoy.formManager.error.ExecutingOpenSolutionMethod", new Object[] { sm.getName() }), e1);
        }
    }
    if (first != null && getCurrentForm() == null) {
        // we only set if the solution startup did not yet show a form already
        showFormInMainPanel(first.getName());
    }
    if (preferedSolutionMethodName != null && (application.getFlattenedSolution().isMainSolutionLoaded() || solution.getSolutionType() == SolutionMetaData.LOGIN_SOLUTION)) {
        try {
            Object[] args = ((ClientState) application).getPreferedSolutionMethodArguments();
            Pair<String, String> scope = ScopesUtils.getVariableScope(preferedSolutionMethodName);
            GlobalScope gs = application.getScriptEngine().getScopesScope().getGlobalScope(scope.getLeft());
            if (// make sure the function is found before resetting preferedSolutionMethodName
            gs != null && gs.get(scope.getRight()) instanceof Function) {
                // avoid stack overflows when an execute method URL is used to open the solution, and that method does call JSSecurity login
                ((ClientState) application).resetPreferedSolutionMethodNameToCall();
                Object result = application.getScriptEngine().getScopesScope().executeGlobalFunction(scope.getLeft(), scope.getRight(), args, false, false);
                if (application.getSolution().getSolutionType() == SolutionMetaData.AUTHENTICATOR) {
                    application.getRuntimeProperties().put(IServiceProvider.RT_OPEN_METHOD_RESULT, result);
                }
            } else if (application.getFlattenedSolution().isMainSolutionLoaded()) {
                Debug.error("Preferred method '" + preferedSolutionMethodName + "' not found in " + application.getFlattenedSolution() + ".");
                ((ClientState) application).resetPreferedSolutionMethodNameToCall();
            }
        } catch (Exception e1) {
            // $NON-NLS-1$
            application.reportError(// $NON-NLS-1$
            Messages.getString("servoy.formManager.error.ExecutingOpenSolutionMethod", new Object[] { preferedSolutionMethodName }), e1);
        }
    }
}
Also used : ClientState(com.servoy.j2db.ClientState) GlobalScope(com.servoy.j2db.scripting.GlobalScope) IBasicMainContainer(com.servoy.j2db.IBasicMainContainer) Form(com.servoy.j2db.persistence.Form) FlattenedForm(com.servoy.j2db.persistence.FlattenedForm) Function(org.mozilla.javascript.Function) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod) Solution(com.servoy.j2db.persistence.Solution)

Aggregations

Function (org.mozilla.javascript.Function)126 Scriptable (org.mozilla.javascript.Scriptable)35 Context (org.mozilla.javascript.Context)33 ScriptMethod (com.servoy.j2db.persistence.ScriptMethod)27 ScriptableObject (org.mozilla.javascript.ScriptableObject)27 JSFunction (org.mozilla.javascript.annotations.JSFunction)25 MouseEventImpl (org.loboevolution.html.js.events.MouseEventImpl)11 BaseFunction (org.mozilla.javascript.BaseFunction)10 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)10 NativeObject (org.mozilla.javascript.NativeObject)10 RepositoryException (com.servoy.j2db.persistence.RepositoryException)8 GlobalScope (com.servoy.j2db.scripting.GlobalScope)7 ServoyException (com.servoy.j2db.util.ServoyException)7 IOException (java.io.IOException)7 HtmlRendererContext (org.loboevolution.http.HtmlRendererContext)7 JSONObject (org.json.JSONObject)6 ModelNode (org.loboevolution.html.dom.nodeimpl.ModelNode)6 RhinoException (org.mozilla.javascript.RhinoException)6 PropertyDescription (org.sablo.specification.PropertyDescription)6 ArrayList (java.util.ArrayList)5