Search in sources :

Example 1 with GlobalScope

use of com.servoy.j2db.scripting.GlobalScope 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)

Example 2 with GlobalScope

use of com.servoy.j2db.scripting.GlobalScope 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 3 with GlobalScope

use of com.servoy.j2db.scripting.GlobalScope in project servoy-client by Servoy.

the class FoundSetManager method getTriggerFunctions.

private List<TriggerFunction> getTriggerFunctions(ITable table, TypedProperty<Integer> property, Scriptable foundsetScope) {
    FlattenedSolution solutionRoot = getApplication().getFlattenedSolution();
    IExecutingEnviroment scriptEngine = getApplication().getScriptEngine();
    return stream(solutionRoot.getTableNodes(table)).map(tableNode -> {
        Object function = null;
        Scriptable scope = null;
        ScriptMethod scriptMethod = solutionRoot.getScriptMethod(((Integer) tableNode.getProperty(property.getPropertyName())).intValue());
        if (scriptMethod != null) {
            if (scriptMethod.getParent() instanceof Solution) {
                // global method
                GlobalScope gs = scriptEngine.getScopesScope().getGlobalScope(scriptMethod.getScopeName());
                if (gs != null) {
                    scope = gs;
                    function = gs.get(scriptMethod.getName());
                }
            } else if (foundsetScope != null) {
                // foundset method
                scope = foundsetScope;
                function = scope.getPrototype().get(scriptMethod.getName(), scope);
            }
        }
        if (function instanceof Function) {
            return new TriggerFunction((Function) function, scope, tableNode);
        }
        return null;
    }).filter(Objects::nonNull).collect(toList());
}
Also used : GlobalScope(com.servoy.j2db.scripting.GlobalScope) Function(org.mozilla.javascript.Function) IExecutingEnviroment(com.servoy.j2db.scripting.IExecutingEnviroment) FlattenedSolution(com.servoy.j2db.FlattenedSolution) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) Scriptable(org.mozilla.javascript.Scriptable) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod) FlattenedSolution(com.servoy.j2db.FlattenedSolution) Solution(com.servoy.j2db.persistence.Solution)

Example 4 with GlobalScope

use of com.servoy.j2db.scripting.GlobalScope in project servoy-client by Servoy.

the class DisplaysAdapter method setRecord.

/**
 * Push new state in this data adapter
 *
 * @param state the state to work with.
 */
public void setRecord(IRecordInternal state) {
    this.record = state;
    Object obj = null;
    if (dataProviderID != null) {
        Pair<String, String> scope = ScopesUtils.getVariableScope(dataProviderID);
        if (scope.getLeft() != null) {
            GlobalScope gs = application.getScriptEngine().getScopesScope().getGlobalScope(scope.getLeft());
            obj = gs == null ? null : gs.get(scope.getRight());
        } else if (relatedData != null) {
            if (state != null)
                obj = state.getValue(dataProviderID);
        } else if (dal.getFormScope() != null && /* design component */
        dal.getFormScope().has(dataProviderID, dal.getFormScope())) {
            obj = dal.getFormScope().get(dataProviderID);
        } else if (state != null) {
            obj = state.getValue(dataProviderID);
        }
        // it means that the foundset has no records, so count/avg/sum is 0;
        if (obj == null && dal.isCountOrAvgOrSumAggregateDataProvider(this))
            obj = Integer.valueOf(0);
    }
    if (obj == Scriptable.NOT_FOUND) {
        obj = null;
    }
    setValueToDisplays(obj);
}
Also used : GlobalScope(com.servoy.j2db.scripting.GlobalScope)

Example 5 with GlobalScope

use of com.servoy.j2db.scripting.GlobalScope in project servoy-client by Servoy.

the class DataAdapterList method isGlobalDataprovider.

protected final boolean isGlobalDataprovider(String dataprovider) {
    if (dataprovider == null)
        return false;
    ScopesScope ss = formController.getApplication().getScriptEngine().getScopesScope();
    Pair<String, String> scope = ScopesUtils.getVariableScope(dataprovider);
    if (scope.getLeft() != null) {
        GlobalScope gs = ss.getGlobalScope(scope.getLeft());
        return gs != null && gs.has(scope.getRight(), gs);
    }
    return false;
}
Also used : GlobalScope(com.servoy.j2db.scripting.GlobalScope) ScopesScope(com.servoy.j2db.scripting.ScopesScope)

Aggregations

GlobalScope (com.servoy.j2db.scripting.GlobalScope)12 Function (org.mozilla.javascript.Function)7 Scriptable (org.mozilla.javascript.Scriptable)7 ScriptMethod (com.servoy.j2db.persistence.ScriptMethod)6 RepositoryException (com.servoy.j2db.persistence.RepositoryException)4 ServoyException (com.servoy.j2db.util.ServoyException)4 Solution (com.servoy.j2db.persistence.Solution)3 FormScope (com.servoy.j2db.scripting.FormScope)3 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)3 IJSFoundSet (com.servoy.base.scripting.api.IJSFoundSet)2 ApplicationException (com.servoy.j2db.ApplicationException)2 FoundSet (com.servoy.j2db.dataprocessing.FoundSet)2 IFoundSet (com.servoy.j2db.dataprocessing.IFoundSet)2 ISwingFoundSet (com.servoy.j2db.dataprocessing.ISwingFoundSet)2 RelatedFoundSet (com.servoy.j2db.dataprocessing.RelatedFoundSet)2 ViewFoundSet (com.servoy.j2db.dataprocessing.ViewFoundSet)2 Form (com.servoy.j2db.persistence.Form)2 ITwoNativeJavaObject (com.servoy.j2db.scripting.ITwoNativeJavaObject)2 ServoyJSONObject (com.servoy.j2db.util.ServoyJSONObject)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2