Search in sources :

Example 11 with ScriptVariable

use of com.servoy.j2db.persistence.ScriptVariable in project servoy-client by Servoy.

the class JSSolutionModel method removeGlobalVariable.

/**
 * Removes the specified global variable.
 *
 * @sample
 * var v1 = solutionModel.newGlobalVariable('globals', 'globalVar1', JSVariable.INTEGER);
 * var v2 = solutionModel.newGlobalVariable('globals', 'globalVar2', JSVariable.TEXT);
 *
 * var success = solutionModel.removeGlobalVariable('globals', 'globalVar1');
 * if (success == false) application.output('!!! globalVar1 could not be removed !!!');
 *
 * var list = solutionModel.getGlobalVariables('globals');
 * for (var i = 0; i < list.length; i++) {
 * 	application.output(list[i].name + '[ ' + list[i].variableType + ']: ' + list[i].variableType);
 * }
 *
 * @param scopeName the scope in which the variable is declared
 * @param name the name of the global variable to be removed
 * @return true if the removal was successful, false otherwise
 */
@JSFunction
public boolean removeGlobalVariable(String scopeName, String name) {
    FlattenedSolution fs = application.getFlattenedSolution();
    ScriptVariable sv = fs.getScriptVariable(scopeName, name);
    if (sv != null) {
        fs.deletePersistCopy(sv, false);
        return true;
    }
    return false;
}
Also used : ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) FlattenedSolution(com.servoy.j2db.FlattenedSolution) JSFunction(org.mozilla.javascript.annotations.JSFunction)

Example 12 with ScriptVariable

use of com.servoy.j2db.persistence.ScriptVariable in project servoy-client by Servoy.

the class ScriptEngine method getTableScope.

public Scriptable getTableScope(final ITable table) {
    if (tableScopes == null)
        tableScopes = new HashMap<ITable, Scriptable>();
    Scriptable tableScope = null;
    synchronized (table) {
        tableScope = tableScopes.get(table);
        if (tableScope == null) {
            Context.enter();
            try {
                tableScope = new TableScope(solutionScope, this, table, application.getFlattenedSolution(), new ISupportScriptProviders() {

                    public Iterator<? extends IScriptProvider> getScriptMethods(boolean sort) {
                        return application.getFlattenedSolution().getScriptCalculations(table, false);
                    }

                    public Iterator<ScriptVariable> getScriptVariables(boolean b) {
                        return Collections.<ScriptVariable>emptyList().iterator();
                    }

                    public ScriptMethod getScriptMethod(int methodId) {
                        // is not used for calculations
                        return null;
                    }
                });
                tableScopes.put(table, tableScope);
            } finally {
                Context.exit();
            }
        }
    }
    return tableScope;
}
Also used : ISupportScriptProviders(com.servoy.j2db.persistence.ISupportScriptProviders) HashMap(java.util.HashMap) ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) Scriptable(org.mozilla.javascript.Scriptable)

Example 13 with ScriptVariable

use of com.servoy.j2db.persistence.ScriptVariable in project servoy-client by Servoy.

the class ScriptVariableScope method put.

public Object put(String name, Object val) {
    Object value = Utils.mapToNullIfUnmanageble(val);
    Integer variableType = nameType.get(name);
    int type = 0;
    boolean xmlType = false;
    if (variableType == null) {
        // global doesn't exist. dynamic new one.. so MEDIA type
        type = IColumnTypes.MEDIA;
        nameType.put(name, new Integer(type));
        // $NON-NLS-1$//$NON-NLS-2$
        Debug.trace("Warning: " + name + " is not defined in the variables, a dynamic (media type) variable is created");
    } else {
        if (variableType.intValue() == Types.OTHER) {
            type = IColumnTypes.MEDIA;
            xmlType = true;
        } else {
            type = Column.mapToDefaultType(variableType.intValue());
        }
    }
    if (type == IColumnTypes.TEXT) {
        Object txt = value;
        while (txt instanceof IDelegate<?>) {
            txt = ((IDelegate<?>) txt).getDelegate();
        }
        if (txt instanceof IDataSet) {
            IDataSet set = (IDataSet) txt;
            StringBuilder sb = new StringBuilder();
            sb.append('\n');
            for (int i = 0; i < set.getRowCount(); i++) {
                sb.append(set.getRow(i)[0]);
                sb.append('\n');
            }
            value = sb.toString();
        } else if (txt instanceof FoundSet) {
            StringBuilder sb = new StringBuilder();
            sb.append('\n');
            FoundSet fs = (FoundSet) txt;
            for (int i = 0; i < fs.getSize(); i++) {
                IRecordInternal record = fs.getRecord(i);
                sb.append(record.getPKHashKey());
                sb.append('\n');
            }
            value = sb.toString();
        }
    }
    if (value != null && variableType != null) {
        Object unwrapped = value;
        while (unwrapped instanceof Wrapper) {
            unwrapped = ((Wrapper) unwrapped).unwrap();
            if (unwrapped == value) {
                break;
            }
        }
        if (type == IColumnTypes.MEDIA) {
            if (!(unwrapped instanceof UUID)) {
                Object previousValue = get(name);
                if (previousValue instanceof UUID || previousValue == null) {
                    Iterator<ScriptVariable> scriptVariablesIte = getScriptLookup().getScriptVariables(false);
                    ScriptVariable sv;
                    while (scriptVariablesIte.hasNext()) {
                        sv = scriptVariablesIte.next();
                        if (name.equals(sv.getName())) {
                            if (UUID.class.getSimpleName().equals(getDeclaredType(sv))) {
                                value = Utils.getAsUUID(unwrapped, false);
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            value = unwrapped;
            try {
                // dont convert with timezone here, its not ui but from scripting
                value = Column.getAsRightType(variableType.intValue(), IBaseColumn.NORMAL_COLUMN, value, null, Integer.MAX_VALUE, null, true, false);
            } catch (Exception e) {
                throw new IllegalArgumentException(// $NON-NLS-1$
                Messages.getString(// $NON-NLS-1$
                "servoy.conversion.error.global", new Object[] { name, Column.getDisplayTypeString(variableType.intValue()), value }));
            }
        }
    }
    if (value instanceof Date) {
        // make copy so then when it is further used in js it won't change this one.
        value = new Date(((Date) value).getTime());
    } else if (xmlType && value instanceof String) {
        // $NON-NLS-1$
        value = evalValue(name, (String) value, "internal_anon", -1);
    }
    Object oldVar = allVars.get(name);
    allVars.put(name, value);
    if (variableType != null && !Utils.equalObjects(oldVar, value)) {
        fireModificationEvent(name, value);
    }
    return oldVar;
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) FoundSet(com.servoy.j2db.dataprocessing.FoundSet) WrappedException(org.mozilla.javascript.WrappedException) Date(java.util.Date) ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) XMLObject(org.mozilla.javascript.xml.XMLObject) IDataSet(com.servoy.j2db.dataprocessing.IDataSet) UUID(com.servoy.j2db.util.UUID) IDelegate(com.servoy.j2db.util.IDelegate)

Example 14 with ScriptVariable

use of com.servoy.j2db.persistence.ScriptVariable in project servoy-client by Servoy.

the class JSForm method removeVariable.

/**
 * Removes a form JSVariable - based on the name of the variable object.
 *
 * @sample
 * var form = solutionModel.newForm('newForm1', null, null, true, 800, 600);
 * var variable = form.newVariable('myVar', JSVariable.TEXT);
 * variable.defaultValue = "'This is a default value (with triple quotes)!'";
 * //variable.defaultValue = "{a:'First letter',b:'Second letter'}"
 * var field = form.newField(variable, JSField.TEXT_FIELD, 100, 100, 200, 200);
 * forms['newForm1'].controller.show();
 *
 * variable = form.removeVariable('myVar');
 * application.sleep(4000);
 * forms['newForm1'].controller.recreateUI();
 *
 * @param name the specified name of the variable
 *
 * @return true if removed, false otherwise (ex: no var with that name)
 */
@JSFunction
public boolean removeVariable(String name) {
    if (name == null)
        return false;
    checkModification();
    ScriptVariable variable = getForm().getScriptVariable(name);
    if (variable != null) {
        getForm().removeChild(variable);
        removeVariableFromScopes(variable);
        return true;
    }
    return false;
}
Also used : ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) JSFunction(org.mozilla.javascript.annotations.JSFunction)

Example 15 with ScriptVariable

use of com.servoy.j2db.persistence.ScriptVariable in project servoy-client by Servoy.

the class DebugUtils method getScopesAndFormsToReload.

public static Set<IFormController>[] getScopesAndFormsToReload(final ClientState clientState, Collection<IPersist> changes) {
    Set<IFormController> scopesToReload = new HashSet<IFormController>();
    final Set<IFormController> formsToReload = new HashSet<IFormController>();
    final SpecProviderState specProviderState = WebComponentSpecProvider.getSpecProviderState();
    final Set<Form> formsUpdated = new HashSet<Form>();
    for (IPersist persist : changes) {
        clientState.getFlattenedSolution().updatePersistInSolutionCopy(persist);
        if (persist instanceof ScriptMethod) {
            if (persist.getParent() instanceof Form) {
                Form form = (Form) persist.getParent();
                List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers(form);
                for (IFormController formController : cachedFormControllers) {
                    scopesToReload.add(formController);
                }
            } else if (persist.getParent() instanceof Solution) {
                LazyCompilationScope scope = clientState.getScriptEngine().getScopesScope().getGlobalScope(((ScriptMethod) persist).getScopeName());
                scope.remove((IScriptProvider) persist);
                scope.put((IScriptProvider) persist, (IScriptProvider) persist);
            } else if (persist.getParent() instanceof TableNode) {
                clientState.getFoundSetManager().reloadFoundsetMethod(((TableNode) persist.getParent()).getDataSource(), (IScriptProvider) persist);
            }
            if (clientState instanceof DebugJ2DBClient) {
                // ((DebugJ2DBClient)clientState).clearUserWindows();  no need for this as window API was refactored and it allows users to clean up dialogs
                ((DebugSwingFormMananger) ((DebugJ2DBClient) clientState).getFormManager()).fillScriptMenu();
            }
        } else if (persist instanceof ScriptVariable) {
            ScriptVariable sv = (ScriptVariable) persist;
            if (persist.getParent() instanceof Solution) {
                clientState.getScriptEngine().getScopesScope().getGlobalScope(sv.getScopeName()).put(sv);
            }
            if (persist.getParent() instanceof Form) {
                Form form = (Form) persist.getParent();
                List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers(form);
                for (IFormController formController : cachedFormControllers) {
                    FormScope scope = formController.getFormScope();
                    scope.put(sv);
                }
            }
        } else if (persist.getAncestor(IRepository.FORMS) != null) {
            final Form form = (Form) persist.getAncestor(IRepository.FORMS);
            if (form != null && form.isFormComponent().booleanValue()) {
                // if the changed form is a reference form we need to check if that is referenced by a loaded form..
                List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers();
                for (IFormController fc : cachedFormControllers) {
                    fc.getForm().acceptVisitor(new IPersistVisitor() {

                        @Override
                        public Object visit(IPersist o) {
                            if (o instanceof WebComponent) {
                                WebComponent wc = (WebComponent) o;
                                WebObjectSpecification spec = FormTemplateGenerator.getWebObjectSpecification(wc);
                                Collection<PropertyDescription> properties = spec != null ? spec.getProperties(FormComponentPropertyType.INSTANCE) : null;
                                if (properties != null && properties.size() > 0) {
                                    Form persistForm = (Form) wc.getAncestor(IRepository.FORMS);
                                    for (PropertyDescription pd : properties) {
                                        Form frm = FormComponentPropertyType.INSTANCE.getForm(wc.getProperty(pd.getName()), clientState.getFlattenedSolution());
                                        if (frm != null && (form.equals(frm) || FlattenedForm.hasFormInHierarchy(frm, form) || isReferenceFormUsedInForm(clientState, form, frm)) && !formsUpdated.contains(persistForm)) {
                                            formsUpdated.add(persistForm);
                                            List<IFormController> cfc = clientState.getFormManager().getCachedFormControllers(persistForm);
                                            for (IFormController formController : cfc) {
                                                formsToReload.add(formController);
                                            }
                                        }
                                    }
                                }
                            }
                            return IPersistVisitor.CONTINUE_TRAVERSAL;
                        }
                    });
                }
            } else if (!formsUpdated.contains(form)) {
                formsUpdated.add(form);
                List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers(form);
                for (IFormController formController : cachedFormControllers) {
                    formsToReload.add(formController);
                }
            }
            if (persist instanceof Form && clientState.getFormManager() instanceof DebugUtils.DebugUpdateFormSupport) {
                ((DebugUtils.DebugUpdateFormSupport) clientState.getFormManager()).updateForm((Form) persist);
            }
        } else if (persist instanceof ScriptCalculation) {
            ScriptCalculation sc = (ScriptCalculation) persist;
            if (((RemoteDebugScriptEngine) clientState.getScriptEngine()).recompileScriptCalculation(sc)) {
                List<String> al = new ArrayList<String>();
                al.add(sc.getDataProviderID());
                try {
                    String dataSource = clientState.getFoundSetManager().getDataSource(sc.getTable());
                    ((FoundSetManager) clientState.getFoundSetManager()).getRowManager(dataSource).clearCalcs(null, al);
                    ((FoundSetManager) clientState.getFoundSetManager()).flushSQLSheet(dataSource);
                } catch (Exception e) {
                    Debug.error(e);
                }
            }
        // if (clientState instanceof DebugJ2DBClient)
        // {
        // ((DebugJ2DBClient)clientState).clearUserWindows(); no need for this as window API was refactored and it allows users to clean up dialogs
        // }
        } else if (persist instanceof Relation) {
            ((FoundSetManager) clientState.getFoundSetManager()).flushSQLSheet((Relation) persist);
            List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers();
            try {
                String primary = ((Relation) persist).getPrimaryDataSource();
                for (IFormController formController : cachedFormControllers) {
                    if (primary.equals(formController.getDataSource())) {
                        final IFormController finalController = formController;
                        final Relation finalRelation = (Relation) persist;
                        formController.getForm().acceptVisitor(new IPersistVisitor() {

                            @Override
                            public Object visit(IPersist o) {
                                if (o instanceof Tab && Utils.equalObjects(finalRelation.getName(), ((Tab) o).getRelationName())) {
                                    formsToReload.add(finalController);
                                    return o;
                                }
                                if (o instanceof Field && ((Field) o).getValuelistID() > 0) {
                                    ValueList vl = clientState.getFlattenedSolution().getValueList(((Field) o).getValuelistID());
                                    if (vl != null && Utils.equalObjects(finalRelation.getName(), vl.getRelationName())) {
                                        formsToReload.add(finalController);
                                        return o;
                                    }
                                }
                                if (o instanceof WebComponent) {
                                    WebComponent webComponent = (WebComponent) o;
                                    WebObjectSpecification spec = specProviderState == null ? null : specProviderState.getWebComponentSpecification(webComponent.getTypeName());
                                    if (spec != null) {
                                        Collection<PropertyDescription> properties = spec.getProperties(RelationPropertyType.INSTANCE);
                                        for (PropertyDescription pd : properties) {
                                            if (Utils.equalObjects(webComponent.getFlattenedJson().opt(pd.getName()), finalRelation.getName())) {
                                                formsToReload.add(finalController);
                                                return o;
                                            }
                                        }
                                    }
                                }
                                return CONTINUE_TRAVERSAL;
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Debug.error(e);
            }
        } else if (persist instanceof ValueList) {
            ComponentFactory.flushValueList(clientState, (ValueList) persist);
            List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers();
            for (IFormController formController : cachedFormControllers) {
                final IFormController finalController = formController;
                final ValueList finalValuelist = (ValueList) persist;
                formController.getForm().acceptVisitor(new IPersistVisitor() {

                    @Override
                    public Object visit(IPersist o) {
                        if (o instanceof Field && ((Field) o).getValuelistID() > 0 && ((Field) o).getValuelistID() == finalValuelist.getID()) {
                            formsToReload.add(finalController);
                            return o;
                        }
                        if (o instanceof WebComponent) {
                            WebComponent webComponent = (WebComponent) o;
                            WebObjectSpecification spec = specProviderState == null ? null : specProviderState.getWebComponentSpecification(webComponent.getTypeName());
                            if (spec != null) {
                                Collection<PropertyDescription> properties = spec.getProperties(ValueListPropertyType.INSTANCE);
                                for (PropertyDescription pd : properties) {
                                    if (Utils.equalObjects(webComponent.getFlattenedJson().opt(pd.getName()), finalValuelist.getUUID().toString())) {
                                        formsToReload.add(finalController);
                                        return o;
                                    }
                                }
                            }
                        }
                        return CONTINUE_TRAVERSAL;
                    }
                });
            }
        } else if (persist instanceof Style) {
            ComponentFactory.flushStyle(null, ((Style) persist));
            List<IFormController> cachedFormControllers = clientState.getFormManager().getCachedFormControllers();
            String styleName = ((Style) persist).getName();
            for (IFormController formController : cachedFormControllers) {
                if (styleName.equals(formController.getForm().getStyleName())) {
                    formsToReload.add(formController);
                }
            }
        }
    }
    return new Set[] { scopesToReload, formsToReload };
}
Also used : WebObjectSpecification(org.sablo.specification.WebObjectSpecification) Set(java.util.Set) HashSet(java.util.HashSet) Form(com.servoy.j2db.persistence.Form) FlattenedForm(com.servoy.j2db.persistence.FlattenedForm) ValueList(com.servoy.j2db.persistence.ValueList) LazyCompilationScope(com.servoy.j2db.scripting.LazyCompilationScope) FormScope(com.servoy.j2db.scripting.FormScope) WebComponent(com.servoy.j2db.persistence.WebComponent) Field(com.servoy.j2db.persistence.Field) Relation(com.servoy.j2db.persistence.Relation) Style(com.servoy.j2db.persistence.Style) ValueList(com.servoy.j2db.persistence.ValueList) List(java.util.List) ArrayList(java.util.ArrayList) Solution(com.servoy.j2db.persistence.Solution) HashSet(java.util.HashSet) FoundSetManager(com.servoy.j2db.dataprocessing.FoundSetManager) DebugSwingFormMananger(com.servoy.j2db.debug.DebugJ2DBClient.DebugSwingFormMananger) RhinoException(org.mozilla.javascript.RhinoException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServoyException(com.servoy.j2db.util.ServoyException) PropertyDescription(org.sablo.specification.PropertyDescription) ScriptCalculation(com.servoy.j2db.persistence.ScriptCalculation) SpecProviderState(org.sablo.specification.SpecProviderState) Tab(com.servoy.j2db.persistence.Tab) IPersist(com.servoy.j2db.persistence.IPersist) IScriptProvider(com.servoy.j2db.persistence.IScriptProvider) TableNode(com.servoy.j2db.persistence.TableNode) ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) IPersistVisitor(com.servoy.j2db.persistence.IPersistVisitor) Collection(java.util.Collection) IFormController(com.servoy.j2db.IFormController) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod)

Aggregations

ScriptVariable (com.servoy.j2db.persistence.ScriptVariable)16 JSFunction (org.mozilla.javascript.annotations.JSFunction)6 FlattenedSolution (com.servoy.j2db.FlattenedSolution)3 Form (com.servoy.j2db.persistence.Form)3 ArrayList (java.util.ArrayList)3 Column (com.servoy.j2db.persistence.Column)2 FlattenedForm (com.servoy.j2db.persistence.FlattenedForm)2 IColumn (com.servoy.j2db.persistence.IColumn)2 IDataProvider (com.servoy.j2db.persistence.IDataProvider)2 IPersist (com.servoy.j2db.persistence.IPersist)2 IScriptProvider (com.servoy.j2db.persistence.IScriptProvider)2 ISupportScriptProviders (com.servoy.j2db.persistence.ISupportScriptProviders)2 Relation (com.servoy.j2db.persistence.Relation)2 RepositoryException (com.servoy.j2db.persistence.RepositoryException)2 ScriptMethod (com.servoy.j2db.persistence.ScriptMethod)2 ScriptNameValidator (com.servoy.j2db.persistence.ScriptNameValidator)2 TableNode (com.servoy.j2db.persistence.TableNode)2 LazyCompilationScope (com.servoy.j2db.scripting.LazyCompilationScope)2 IBaseColumn (com.servoy.base.persistence.IBaseColumn)1 IMobileSMForm (com.servoy.base.solutionmodel.mobile.IMobileSMForm)1