Search in sources :

Example 1 with WalkHelper

use of com.twinsoft.convertigo.engine.helpers.WalkHelper in project convertigo by convertigo.

the class CreateMobileApplicationTranslationsFileAction method run.

public void run() {
    Display display = Display.getDefault();
    Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
    Shell shell = getParentShell();
    shell.setCursor(waitCursor);
    try {
        ProjectExplorerView explorerView = getProjectExplorerView();
        if (explorerView != null) {
            TreeObject treeObject = explorerView.getFirstSelectedTreeObject();
            Object databaseObject = treeObject.getObject();
            List<String> textList = new ArrayList<String>();
            if ((databaseObject != null) && (databaseObject instanceof ApplicationComponent)) {
                ApplicationComponent application = (ApplicationComponent) databaseObject;
                new WalkHelper() {

                    @Override
                    protected void walk(DatabaseObject databaseObject) throws Exception {
                        String text = null;
                        if (databaseObject instanceof PageComponent) {
                            PageComponent page = (PageComponent) databaseObject;
                            text = page.getTitle();
                        } else if (databaseObject instanceof UIUseShared) {
                            UIUseShared uius = (UIUseShared) databaseObject;
                            UISharedComponent uisc = uius.getTargetSharedComponent();
                            if (uisc != null && !uius.isRecursive()) {
                                super.walk(uisc);
                            }
                        } else if (databaseObject instanceof UIText) {
                            UIText uiText = (UIText) databaseObject;
                            MobileSmartSourceType msst = uiText.getTextSmartType();
                            if (Mode.PLAIN.equals(msst.getMode())) {
                                text = msst.getValue();
                            }
                        }
                        if (text != null && !textList.contains(text)) {
                            textList.add(text);
                        }
                        super.walk(databaseObject);
                    }
                }.init(application);
                MobileApplicationTranslationsDialog dlg = new MobileApplicationTranslationsDialog(shell);
                int ret = dlg.open();
                if (ret != Window.OK) {
                    return;
                }
                Locale from = dlg.getLocaleFrom();
                Locale to = dlg.getLocaleTo();
                boolean auto = dlg.isAuto();
                File i18nDir = new File(application.getProject().getDirPath(), "DisplayObjects/mobile/assets/i18n");
                // store source file
                File source = new File(i18nDir, from.getLanguage() + ".json");
                TranslateUtils.storeTranslations(textList, source);
                ConvertigoPlugin.logDebug(source.getName() + " file successfully created or updated.");
                // store target file
                if (!to.equals(from)) {
                    File target = new File(i18nDir, to.getLanguage() + ".json");
                    // translate with google api
                    if (auto) {
                        ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
                        dialog.run(true, false, new IRunnableWithProgress() {

                            @Override
                            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                                monitor.beginTask("translating", IProgressMonitor.UNKNOWN);
                                Translator translator = TranslateUtils.newTranslator();
                                try {
                                    translator.translate(from, source, to, target);
                                    ConvertigoPlugin.logDebug(target.getName() + " file successfully translated.");
                                } catch (Exception e) {
                                    ConvertigoPlugin.logError(e.getMessage(), false);
                                    try {
                                        TranslateUtils.storeTranslations(textList, target);
                                    } catch (Exception ex) {
                                    }
                                }
                                monitor.done();
                            }
                        });
                    } else // do not translate
                    {
                        TranslateUtils.storeTranslations(textList, target);
                    }
                    ConvertigoPlugin.logDebug(target.getName() + " file successfully created or updated.");
                }
                // regenerate app templates
                try {
                    application.markApplicationAsDirty();
                    for (PageComponent page : application.getPageComponentList()) {
                        if (page.isEnabled()) {
                            page.markPageAsDirty();
                        }
                    }
                } catch (Throwable t) {
                }
                ConvertigoPlugin.logInfo("Translations file(s) successfully created or updated.", true);
            }
        }
    } catch (Throwable e) {
        ConvertigoPlugin.logException(e, "Unable to create the Mobile application translations file(s)!");
    } finally {
        shell.setCursor(null);
        waitCursor.dispose();
    }
}
Also used : Locale(java.util.Locale) MobileApplicationTranslationsDialog(com.twinsoft.convertigo.eclipse.dialogs.MobileApplicationTranslationsDialog) MobileSmartSourceType(com.twinsoft.convertigo.beans.mobile.components.MobileSmartSourceType) UIUseShared(com.twinsoft.convertigo.beans.mobile.components.UIUseShared) ArrayList(java.util.ArrayList) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper) Cursor(org.eclipse.swt.graphics.Cursor) UISharedComponent(com.twinsoft.convertigo.beans.mobile.components.UISharedComponent) PageComponent(com.twinsoft.convertigo.beans.mobile.components.PageComponent) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Shell(org.eclipse.swt.widgets.Shell) Translator(com.twinsoft.convertigo.engine.mobile.TranslateUtils.Translator) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) UIText(com.twinsoft.convertigo.beans.mobile.components.UIText) ProjectExplorerView(com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView) ApplicationComponent(com.twinsoft.convertigo.beans.mobile.components.ApplicationComponent) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) File(java.io.File) Display(org.eclipse.swt.widgets.Display)

Example 2 with WalkHelper

use of com.twinsoft.convertigo.engine.helpers.WalkHelper in project convertigo by convertigo.

the class CreateNgxApplicationTranslationsFileAction method run.

public void run() {
    Display display = Display.getDefault();
    Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
    Shell shell = getParentShell();
    shell.setCursor(waitCursor);
    try {
        ProjectExplorerView explorerView = getProjectExplorerView();
        if (explorerView != null) {
            TreeObject treeObject = explorerView.getFirstSelectedTreeObject();
            Object databaseObject = treeObject.getObject();
            List<String> textList = new ArrayList<String>();
            if ((databaseObject != null) && (databaseObject instanceof ApplicationComponent)) {
                ApplicationComponent application = (ApplicationComponent) databaseObject;
                new WalkHelper() {

                    @Override
                    protected void walk(DatabaseObject databaseObject) throws Exception {
                        String text = null;
                        if (databaseObject instanceof PageComponent) {
                            PageComponent page = (PageComponent) databaseObject;
                            text = page.getTitle();
                        } else if (databaseObject instanceof UIUseShared) {
                            UIUseShared uius = (UIUseShared) databaseObject;
                            UISharedComponent uisc = uius.getTargetSharedComponent();
                            if (uisc != null && !uius.isRecursive()) {
                                super.walk(uisc);
                            }
                        } else if (databaseObject instanceof UIText) {
                            UIText uiText = (UIText) databaseObject;
                            MobileSmartSourceType msst = uiText.getTextSmartType();
                            if (Mode.PLAIN.equals(msst.getMode())) {
                                text = msst.getValue();
                            }
                        }
                        if (text != null && !textList.contains(text)) {
                            textList.add(text);
                        }
                        super.walk(databaseObject);
                    }
                }.init(application);
                MobileApplicationTranslationsDialog dlg = new MobileApplicationTranslationsDialog(shell);
                int ret = dlg.open();
                if (ret != Window.OK) {
                    return;
                }
                Locale from = dlg.getLocaleFrom();
                Locale to = dlg.getLocaleTo();
                boolean auto = dlg.isAuto();
                File i18nDir = new File(application.getProject().getDirPath(), "DisplayObjects/mobile/assets/i18n");
                // store source file
                File source = new File(i18nDir, from.getLanguage() + ".json");
                TranslateUtils.storeTranslations(textList, source);
                ConvertigoPlugin.logDebug(source.getName() + " file successfully created or updated.");
                // store target file
                if (!to.equals(from)) {
                    File target = new File(i18nDir, to.getLanguage() + ".json");
                    // translate with google api
                    if (auto) {
                        ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
                        dialog.run(true, false, new IRunnableWithProgress() {

                            @Override
                            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                                monitor.beginTask("translating", IProgressMonitor.UNKNOWN);
                                Translator translator = TranslateUtils.newTranslator();
                                try {
                                    translator.translate(from, source, to, target);
                                    ConvertigoPlugin.logDebug(target.getName() + " file successfully translated.");
                                } catch (Exception e) {
                                    ConvertigoPlugin.logError(e.getMessage(), false);
                                    try {
                                        TranslateUtils.storeTranslations(textList, target);
                                    } catch (Exception ex) {
                                    }
                                }
                                monitor.done();
                            }
                        });
                    } else // do not translate
                    {
                        TranslateUtils.storeTranslations(textList, target);
                    }
                    ConvertigoPlugin.logDebug(target.getName() + " file successfully created or updated.");
                }
                // regenerate app templates
                try {
                    application.markApplicationAsDirty();
                    for (PageComponent page : application.getPageComponentList()) {
                        if (page.isEnabled()) {
                            page.markPageAsDirty();
                        }
                    }
                } catch (Throwable t) {
                }
                ConvertigoPlugin.logInfo("Translations file(s) successfully created or updated.", true);
            }
        }
    } catch (Throwable e) {
        ConvertigoPlugin.logException(e, "Unable to create the Mobile application translations file(s)!");
    } finally {
        shell.setCursor(null);
        waitCursor.dispose();
    }
}
Also used : Locale(java.util.Locale) MobileApplicationTranslationsDialog(com.twinsoft.convertigo.eclipse.dialogs.MobileApplicationTranslationsDialog) MobileSmartSourceType(com.twinsoft.convertigo.beans.ngx.components.MobileSmartSourceType) UIUseShared(com.twinsoft.convertigo.beans.ngx.components.UIUseShared) ArrayList(java.util.ArrayList) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper) Cursor(org.eclipse.swt.graphics.Cursor) UISharedComponent(com.twinsoft.convertigo.beans.ngx.components.UISharedComponent) PageComponent(com.twinsoft.convertigo.beans.ngx.components.PageComponent) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Shell(org.eclipse.swt.widgets.Shell) Translator(com.twinsoft.convertigo.engine.mobile.TranslateUtils.Translator) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) UIText(com.twinsoft.convertigo.beans.ngx.components.UIText) ProjectExplorerView(com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView) ApplicationComponent(com.twinsoft.convertigo.beans.ngx.components.ApplicationComponent) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) File(java.io.File) Display(org.eclipse.swt.widgets.Display)

Example 3 with WalkHelper

use of com.twinsoft.convertigo.engine.helpers.WalkHelper in project convertigo by convertigo.

the class UIDynamicAnimate method getAnimatableId.

private String getAnimatableId() {
    if (!identifiable.isEmpty()) {
        String p_name = identifiable.substring(0, identifiable.indexOf('.'));
        Project project = this.getProject();
        if (project != null) {
            Project p = null;
            try {
                // p = p_name.equals(project.getName()) ? project: Engine.theApp.databaseObjectsManager.getOriginalProjectByName(p_name);
                p = Engine.theApp.referencedProjectManager.importProjectFrom(project, p_name);
            } catch (Exception e) {
                Engine.logBeans.warn("(UIDynamicAnimate) For \"" + this.toString() + "\", targeted project \"" + p_name + "\" is missing !");
            }
            if (p != null) {
                Map<String, DatabaseObject> map = new HashMap<String, DatabaseObject>();
                try {
                    new WalkHelper() {

                        @Override
                        protected void walk(DatabaseObject databaseObject) throws Exception {
                            map.put(databaseObject.getQName(), databaseObject);
                            super.walk(databaseObject);
                        }
                    }.init(p);
                    DatabaseObject animatable = map.get(identifiable);
                    if (animatable != null && animatable instanceof UIElement) {
                        return ((UIElement) animatable).getIdentifier();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return "";
}
Also used : Project(com.twinsoft.convertigo.beans.core.Project) HashMap(java.util.HashMap) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper)

Example 4 with WalkHelper

use of com.twinsoft.convertigo.engine.helpers.WalkHelper in project convertigo by convertigo.

the class NewObjectWizard method doFinish.

private void doFinish(IProgressMonitor monitor) throws CoreException {
    String dboName, name;
    boolean bContinue = true;
    int index = 0;
    try {
        int total = 0;
        Class<?> c = getCreatedBeanClass();
        if (c != null) {
            total = 4;
            if (c.equals(WebServiceReference.class)) {
                total += ImportWsReference.getTotalTaskNumber();
            }
        }
        monitor.beginTask("Creating new object", total);
        newBean = getCreatedBean();
        if (newBean != null) {
            monitor.setTaskName("Object created");
            monitor.worked(1);
            dboName = newBean.getName();
            if (!StringUtils.isNormalized(dboName))
                throw new EngineException("Bean name is not normalized : \"" + dboName + "\".");
            // Verify if a child object with same name exist and change name
            while (bContinue) {
                if (index == 0)
                    name = dboName;
                else
                    name = dboName + index;
                newBean.setName(name);
                newBean.hasChanged = true;
                newBean.bNew = true;
                try {
                    new WalkHelper() {

                        boolean root = true;

                        boolean find = false;

                        @Override
                        protected boolean before(DatabaseObject dbo, Class<? extends DatabaseObject> dboClass) {
                            boolean isInstance = dboClass.isInstance(newBean);
                            find |= isInstance;
                            return isInstance;
                        }

                        @Override
                        protected void walk(DatabaseObject dbo) throws Exception {
                            if (root) {
                                root = false;
                                super.walk(dbo);
                                if (!find) {
                                    throw new EngineException("You cannot add to a " + newBean.getClass().getSimpleName() + " a database object of type " + parentObject.getClass().getSimpleName());
                                }
                            } else {
                                if (newBean.getName().equalsIgnoreCase(dbo.getName())) {
                                    throw new ObjectWithSameNameException("Unable to add the object because an object with the same name already exists in target.");
                                }
                            }
                        }
                    }.init(parentObject);
                    bContinue = false;
                } catch (ObjectWithSameNameException owsne) {
                    if ((parentObject instanceof HtmlTransaction) && (newBean instanceof Statement)) {
                        throw new EngineException("HtmlTransaction already contains a statement named \"" + name + "\".", owsne);
                    }
                    // Silently ignore
                    index++;
                } catch (EngineException ee) {
                    throw ee;
                } catch (Exception e) {
                    throw new EngineException("Exception in create", e);
                }
            }
            // Now add bean to target
            try {
                boolean hasChanged = parentObject.hasChanged;
                if ((newBean instanceof Statement) && (parentObject instanceof Transaction)) {
                    newBean.priority = 0;
                }
                if (newBean instanceof ScreenClass)
                    newBean.priority = parentObject.priority + 1;
                if (newBean instanceof Criteria) {
                    Connector connector = parentObject.getConnector();
                    if (parentObject.equals(((IScreenClassContainer<?>) connector).getDefaultScreenClass()))
                        throw new EngineException("You cannot add a new criterion on default screenclass.");
                }
                parentObject.add(newBean);
                monitor.setTaskName("Object added");
                monitor.worked(1);
                if (newBean instanceof HTTPStatement) {
                    HTTPStatement httpStatement = (HTTPStatement) newBean;
                    HtmlConnector connector = (HtmlConnector) httpStatement.getParentTransaction().getParent();
                    httpStatement.setMethod("GET");
                    httpStatement.setHost(connector.getServer());
                    httpStatement.setPort(connector.getPort());
                    httpStatement.setHttps(connector.isHttps());
                }
                if (newBean instanceof ContinueWithSiteClipperStatement) {
                    Project project = newBean.getProject();
                    if (project != null) {
                        String[] connectorWithSiteClipperConnector = ContinueWithSiteClipperStatement.getSiteClippersConnectorNames(project);
                        if (connectorWithSiteClipperConnector.length > 0) {
                            ((ContinueWithSiteClipperStatement) newBean).setSiteClipperConnectorName(connectorWithSiteClipperConnector[0]);
                        }
                    }
                }
                if (newBean instanceof Connector) {
                    Project project = (Project) parentObject;
                    if (project.getDefaultConnector() == null)
                        project.setDefaultConnector((Connector) newBean);
                    Connector.setupConnector(newBean);
                }
                if (newBean instanceof PageComponent) {
                    ApplicationComponent application = (ApplicationComponent) parentObject;
                    if (application.getRootPage() == null)
                        application.setRootPage((PageComponent) newBean);
                }
                if (newBean instanceof SequenceStep) {
                    Project project = newBean.getProject();
                    ((SequenceStep) newBean).setSourceSequence(project.getName() + TransactionStep.SOURCE_SEPARATOR + project.getSequencesList().get(0));
                }
                if (newBean instanceof TransactionStep) {
                    Project project = newBean.getProject();
                    Connector connector = project.getDefaultConnector();
                    Transaction transaction = connector.getDefaultTransaction();
                    ((TransactionStep) newBean).setSourceTransaction(project.getName() + TransactionStep.SOURCE_SEPARATOR + connector.getName() + TransactionStep.SOURCE_SEPARATOR + transaction.getName());
                }
                if (newBean instanceof IThenElseContainer) {
                    ThenStep thenStep = new ThenStep();
                    ((IThenElseContainer) newBean).addStep(thenStep);
                    ElseStep elseStep = new ElseStep();
                    ((IThenElseContainer) newBean).addStep(elseStep);
                }
                if (newBean instanceof IThenElseStatementContainer) {
                    ThenStatement thenStatement = new ThenStatement();
                    ((IThenElseStatementContainer) newBean).addStatement(thenStatement);
                    ElseStatement elseStatement = new ElseStatement();
                    ((IThenElseStatementContainer) newBean).addStatement(elseStatement);
                }
                if (newBean instanceof Sheet) {
                    InputStream is = null;
                    try {
                        String sheetName = newBean.getName() + ".xsl";
                        is = new FileInputStream(new File(Engine.XSL_PATH + "/customsheet.xsl"));
                        String projectName = ((DatabaseObject) parentObject).getProject().getName();
                        IProject project = ConvertigoPlugin.getDefault().getProjectPluginResource(projectName);
                        final IFile file = project.getFile(sheetName);
                        if (!file.exists())
                            file.create(is, true, null);
                        ((Sheet) newBean).setUrl(sheetName);
                    } catch (Exception e) {
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                }
                if (newBean instanceof TestCase) {
                    TestCase testCase = (TestCase) newBean;
                    testCase.importRequestableVariables((RequestableObject) testCase.getParent());
                }
                if (newBean instanceof RequestableHttpVariable) {
                    RequestableHttpVariable variable = (RequestableHttpVariable) newBean;
                    AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) variable.getParent();
                    HttpMethodType httpMethodType = httpTransaction.getHttpVerb();
                    boolean isVarPost = httpMethodType.equals(HttpMethodType.PUT) || httpMethodType.equals(HttpMethodType.POST);
                    variable.setHttpMethod(isVarPost ? HttpMethodType.POST.name() : HttpMethodType.GET.name());
                    if (!(httpTransaction instanceof HtmlTransaction)) {
                        variable.setHttpName(variable.getName());
                    }
                }
                if (newBean instanceof WebServiceReference) {
                    try {
                        Project project = (Project) parentObject;
                        WebServiceReference webServiceReference = (WebServiceReference) newBean;
                        ImportWsReference wsr = new ImportWsReference(webServiceReference);
                        wsr.importInto(project);
                    } catch (Exception e) {
                        if (newBean != null) {
                            parentObject.remove(newBean);
                            parentObject.hasChanged = hasChanged;
                        }
                        throw new Exception(e);
                    }
                }
                if (newBean instanceof RestServiceReference) {
                    try {
                        Project project = (Project) parentObject;
                        RestServiceReference restServiceReference = (RestServiceReference) newBean;
                        ImportWsReference wsr = new ImportWsReference(restServiceReference);
                        wsr.importInto(project);
                    } catch (Exception e) {
                        if (newBean != null) {
                            parentObject.remove(newBean);
                            parentObject.hasChanged = hasChanged;
                        }
                        throw new Exception(e);
                    }
                }
                if (newBean instanceof SqlTransaction) {
                    SqlTransaction sqlTransaction = (SqlTransaction) newBean;
                    sqlTransaction.setSqlQuery(sqlQueriesWizardPage.getSQLQueries());
                    sqlTransaction.initializeQueries(true);
                }
                if (newBean instanceof SapJcoLogonTransaction) {
                    SapJcoLogonTransaction sapLogonTransaction = (SapJcoLogonTransaction) newBean;
                    sapLogonTransaction.addCredentialsVariables();
                }
                if (newBean instanceof AbstractCouchDbTransaction) {
                    AbstractCouchDbTransaction abstractCouchDbTransaction = (AbstractCouchDbTransaction) newBean;
                    List<CouchVariable> selectedVariables = objectInfoPage.getSelectedParameters();
                    abstractCouchDbTransaction.createVariables(selectedVariables);
                }
                ConvertigoPlugin.logInfo("New object class '" + this.className + "' named '" + newBean.getName() + "' has been added");
                monitor.setTaskName("Object setted up");
                monitor.worked(1);
                bContinue = false;
            } catch (com.twinsoft.convertigo.engine.ObjectWithSameNameException owsne) {
                if (newBean instanceof HandlerStatement) {
                    throw owsne;
                }
            }
        } else {
            throw new Exception("Could not instantiate bean!");
        }
    } catch (Exception e) {
        String message = "Unable to create a new object from class '" + this.className + "'.";
        ConvertigoPlugin.logException(e, message);
        if (objectExplorerPage != null) {
            objectExplorerPage.doCancel();
        }
    }
}
Also used : RestServiceReference(com.twinsoft.convertigo.beans.references.RestServiceReference) RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) ContinueWithSiteClipperStatement(com.twinsoft.convertigo.beans.statements.ContinueWithSiteClipperStatement) IThenElseContainer(com.twinsoft.convertigo.beans.steps.IThenElseContainer) ElseStep(com.twinsoft.convertigo.beans.steps.ElseStep) HttpMethodType(com.twinsoft.convertigo.engine.enums.HttpMethodType) ScreenClass(com.twinsoft.convertigo.beans.core.ScreenClass) EngineException(com.twinsoft.convertigo.engine.EngineException) HTTPStatement(com.twinsoft.convertigo.beans.statements.HTTPStatement) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) SequenceStep(com.twinsoft.convertigo.beans.steps.SequenceStep) AbstractCouchDbTransaction(com.twinsoft.convertigo.beans.transactions.couchdb.AbstractCouchDbTransaction) ThenStatement(com.twinsoft.convertigo.beans.statements.ThenStatement) FileInputStream(java.io.FileInputStream) IProject(org.eclipse.core.resources.IProject) Project(com.twinsoft.convertigo.beans.core.Project) SqlTransaction(com.twinsoft.convertigo.beans.transactions.SqlTransaction) SapJcoLogonTransaction(com.twinsoft.convertigo.beans.transactions.SapJcoLogonTransaction) Transaction(com.twinsoft.convertigo.beans.core.Transaction) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) AbstractCouchDbTransaction(com.twinsoft.convertigo.beans.transactions.couchdb.AbstractCouchDbTransaction) HtmlTransaction(com.twinsoft.convertigo.beans.transactions.HtmlTransaction) ElseStatement(com.twinsoft.convertigo.beans.statements.ElseStatement) IFile(org.eclipse.core.resources.IFile) File(java.io.File) CouchVariable(com.twinsoft.convertigo.beans.transactions.couchdb.CouchVariable) HtmlConnector(com.twinsoft.convertigo.beans.connectors.HtmlConnector) Connector(com.twinsoft.convertigo.beans.core.Connector) SqlConnector(com.twinsoft.convertigo.beans.connectors.SqlConnector) IFile(org.eclipse.core.resources.IFile) SapJcoLogonTransaction(com.twinsoft.convertigo.beans.transactions.SapJcoLogonTransaction) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper) Criteria(com.twinsoft.convertigo.beans.core.Criteria) HandlerStatement(com.twinsoft.convertigo.beans.statements.HandlerStatement) PageComponent(com.twinsoft.convertigo.beans.mobile.components.PageComponent) ThenStep(com.twinsoft.convertigo.beans.steps.ThenStep) ImportWsReference(com.twinsoft.convertigo.engine.util.ImportWsReference) IThenElseStatementContainer(com.twinsoft.convertigo.beans.statements.IThenElseStatementContainer) HtmlConnector(com.twinsoft.convertigo.beans.connectors.HtmlConnector) ElseStatement(com.twinsoft.convertigo.beans.statements.ElseStatement) HTTPStatement(com.twinsoft.convertigo.beans.statements.HTTPStatement) Statement(com.twinsoft.convertigo.beans.core.Statement) ContinueWithSiteClipperStatement(com.twinsoft.convertigo.beans.statements.ContinueWithSiteClipperStatement) ThenStatement(com.twinsoft.convertigo.beans.statements.ThenStatement) HandlerStatement(com.twinsoft.convertigo.beans.statements.HandlerStatement) ApplicationComponent(com.twinsoft.convertigo.beans.mobile.components.ApplicationComponent) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HtmlTransaction(com.twinsoft.convertigo.beans.transactions.HtmlTransaction) SqlTransaction(com.twinsoft.convertigo.beans.transactions.SqlTransaction) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) EngineException(com.twinsoft.convertigo.engine.EngineException) IOException(java.io.IOException) ObjectWithSameNameException(com.twinsoft.convertigo.engine.ObjectWithSameNameException) IProject(org.eclipse.core.resources.IProject) TransactionStep(com.twinsoft.convertigo.beans.steps.TransactionStep) ObjectWithSameNameException(com.twinsoft.convertigo.engine.ObjectWithSameNameException) TestCase(com.twinsoft.convertigo.beans.core.TestCase) WebServiceReference(com.twinsoft.convertigo.beans.references.WebServiceReference) Sheet(com.twinsoft.convertigo.beans.core.Sheet) ObjectWithSameNameException(com.twinsoft.convertigo.engine.ObjectWithSameNameException)

Example 5 with WalkHelper

use of com.twinsoft.convertigo.engine.helpers.WalkHelper in project convertigo by convertigo.

the class SharedComponentWizard method scanForVariables.

private void scanForVariables(final UIComponent origin) throws Exception {
    final Set<String> identifierSet = new HashSet<String>();
    try {
        new WalkHelper() {

            private void addDeclaration(String var_name, String var_value) {
                if (var_name != null && !var_name.isEmpty() && !main_map.containsKey(var_name)) {
                    main_map.put(var_name, var_value == null ? "''" : var_value);
                }
            }

            private void getMainDeclarations() {
                try {
                    List<String> declarations = new ArrayList<String>();
                    String c8o_Declarations = "", markerId = "";
                    if (isInPage(origin)) {
                        markerId = "PageDeclaration";
                        String c8o_UserCustoms = origin.getPage().getScriptContent().getString();
                        c8o_Declarations = Ionic3Builder.getMarker(c8o_UserCustoms, markerId);
                    } else if (isInSharedComponent(origin)) {
                        markerId = "SharedCompDeclaration";
                        UISharedComponent uisc = origin.getSharedComponent();
                        for (UICompVariable var : uisc.getVariables()) {
                            c8o_Declarations += "let " + var.getVariableName() + " = " + var.getVariableValue() + ";" + System.lineSeparator();
                        }
                    } else if (isInApplication(origin)) {
                        markerId = "AppDeclaration";
                        String c8o_UserCustoms = origin.getApplication().getComponentScriptContent().getString();
                        c8o_Declarations = Ionic3Builder.getMarker(c8o_UserCustoms, markerId);
                    }
                    if (!c8o_Declarations.isEmpty()) {
                        for (String line : Arrays.asList(c8o_Declarations.split(System.lineSeparator()))) {
                            line = line.trim();
                            if (!line.isEmpty() && line.indexOf(markerId) == -1) {
                                declarations.add(line);
                            }
                        }
                    }
                    for (String line : declarations) {
                        // "(((\\w+)\\s(\\w+)([^\\=]+))(\\=([^\\=]+))?)"
                        Matcher matcher = d_var.matcher(line);
                        while (matcher.find()) {
                            String var_name = matcher.group(4);
                            String var_value = matcher.group(7);
                            if (var_value != null) {
                                var_value = var_value.trim();
                                if (var_value.charAt(var_value.length() - 1) == ';') {
                                    var_value = var_value.substring(0, var_value.length() - 1);
                                }
                                var_value = escapeString(var_value);
                            }
                            addDeclaration(var_name, var_value);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            private boolean isInForDirective(UIComponent uic) {
                return getForDirective(uic) != null;
            }

            private UIControlDirective getForDirective(UIComponent uic) {
                DatabaseObject databaseObject = uic;
                while (databaseObject != null && (!(databaseObject instanceof UIControlDirective) || !AttrDirective.ForEach.name().equals(((UIControlDirective) databaseObject).getDirectiveName()))) {
                    databaseObject = databaseObject.getParent();
                }
                if (databaseObject == null)
                    return null;
                else
                    return (UIControlDirective) databaseObject;
            }

            private void getForDirectiveVariables(UIComponent uic) {
                UIComponent uicomponent = uic;
                while (isInForDirective(uicomponent)) {
                    UIControlDirective uicd = getForDirective(uicomponent);
                    if (!uic.equals(uicd)) {
                        String item = "item" + uicd.priority;
                        addDeclaration(item, "[]");
                        addMapVariable(item, item, "this._params_." + item);
                        addMapVariable(item, uicd.toString() + " : found  variable which stands for the iterator's item");
                        String itemName = uicd.getDirectiveItemName();
                        addDeclaration(itemName, "{}");
                        addMapVariable(itemName, itemName, "this._params_." + itemName);
                        addMapVariable(itemName, uicd.toString() + " : found variable which stands for the customized iterator's item");
                        String indexName = uicd.getDirectiveIndexName();
                        addDeclaration(indexName, "0");
                        addMapVariable(indexName, indexName, "this._params_." + indexName);
                        addMapVariable(indexName, uicd.toString() + " : found variable which stands for the customized iterator's index");
                        String expression = uicd.getDirectiveExpression();
                        if (!expression.isEmpty()) {
                            Matcher matcher = null;
                            List<String> list = Arrays.asList(expression.split("\\;"));
                            for (String s : list) {
                                matcher = d_var_let.matcher(s);
                                while (matcher.find()) {
                                    String expvar = matcher.group(3);
                                    addDeclaration(expvar, "''");
                                    addMapVariable(expvar, expvar, "this._params_." + expvar);
                                    addMapVariable(expvar, uicd.toString() + " : found variable used by the customized iterator's expression");
                                }
                                matcher = d_var_as.matcher(s);
                                while (matcher.find()) {
                                    String expvar = matcher.group(4);
                                    addDeclaration(expvar, "''");
                                    addMapVariable(expvar, expvar, "this._params_." + expvar);
                                    addMapVariable(expvar, uicd.toString() + " : found variable used by the customized iterator's expression");
                                }
                            }
                        }
                    }
                    DatabaseObject dbo = uicd.getParent();
                    uicomponent = dbo instanceof UIComponent ? (UIComponent) dbo : null;
                }
            }

            private boolean checkVariable(String name) {
                if (name == null || name.isEmpty())
                    return false;
                if (identifierSet.contains(name)) {
                    return false;
                }
                if ("global".equals(name))
                    return false;
                if ("router".equals(name))
                    return false;
                return true;
            }

            private void addMapVariable(String name, String target, String replacement) {
                if (checkVariable(name)) {
                    String normalized_name = StringUtils.normalize(name);
                    String var_name = normalized_name;
                    if (ovarMap.containsKey(var_name)) {
                    // System.out.println("var_name: "+ var_name + " already in ovarMap");
                    } else {
                        ovarMap.put(var_name, new HashMap<String, String>());
                    }
                    ovarMap.get(var_name).put(target, replacement.replace("_params_." + name, "_params_.") + var_name);
                }
            }

            private void addMapVariable(String name, String infos) {
                if (checkVariable(name)) {
                    String normalized_name = StringUtils.normalize(name);
                    String var_name = normalized_name;
                    if (infoMap.containsKey(var_name)) {
                    // System.out.println("var_name: "+ var_name + " already in infoMap");
                    } else {
                        infoMap.put(var_name, infos);
                    }
                }
            }

            private void scanSmartSource(UIComponent uic, String p_name, MobileSmartSourceType msst) throws Exception {
                boolean extended = !forTemplate(uic);
                String s = null;
                if (Mode.SCRIPT.equals(msst.getMode())) {
                    s = msst.getValue(extended);
                }
                if (Mode.SOURCE.equals(msst.getMode())) {
                    s = msst.getSmartSource().toJsonString();
                }
                if (s != null) {
                    String infos = uic.toString() + " : found variable used by '" + p_name + "' property";
                    Matcher matcher = p_var.matcher(s);
                    while (matcher.find()) {
                        String group1 = matcher.group(1);
                        String group2 = matcher.group(2);
                        // String group3 = matcher.group(3);
                        String group4 = matcher.group(4);
                        String name = group4;
                        String target = group1;
                        String replacement = group2 + "._params_." + name;
                        if (isInControlEvent(uic)) {
                            if (forTemplate(uic)) {
                                replacement = "_params_." + name;
                            } else {
                                replacement = "scope._params_." + name;
                            }
                        }
                        addMapVariable(name, target, replacement);
                        addMapVariable(name, infos);
                    }
                }
            }

            @Override
            public void init(DatabaseObject databaseObject) throws Exception {
                getMainDeclarations();
                if (isInForDirective(origin)) {
                    getForDirectiveVariables(origin);
                }
                super.init(databaseObject);
            }

            @Override
            protected void walk(DatabaseObject databaseObject) throws Exception {
                if (databaseObject instanceof UIComponent) {
                    UIComponent uic = (UIComponent) databaseObject;
                    if (uic.isEnabled() && !isInControlEvent(uic)) {
                        if (databaseObject instanceof UIDynamicElement) {
                            String identifier = ((UIDynamicElement) databaseObject).getIdentifier();
                            if (!identifier.isEmpty()) {
                                identifierSet.add(identifier);
                            }
                        }
                        for (java.beans.PropertyDescriptor pd : CachedIntrospector.getBeanInfo(databaseObject).getPropertyDescriptors()) {
                            if (pd.getPropertyEditorClass() != null) {
                                if (pd.getPropertyEditorClass().getSimpleName().equals("MobileSmartSourcePropertyDescriptor")) {
                                    Method getter = pd.getReadMethod();
                                    Object value = getter.invoke(databaseObject, new Object[] {});
                                    if (value != null && value instanceof MobileSmartSourceType) {
                                        MobileSmartSourceType msst = (MobileSmartSourceType) value;
                                        if (Mode.SCRIPT.equals(msst.getMode()) || Mode.SOURCE.equals(msst.getMode())) {
                                            scanSmartSource(uic, pd.getName(), msst);
                                        }
                                    }
                                }
                            }
                        }
                        if (databaseObject instanceof UIDynamicElement) {
                            UIDynamicElement uide = (UIDynamicElement) databaseObject;
                            IonBean ionBean = uide.getIonBean();
                            if (ionBean != null) {
                                for (IonProperty property : ionBean.getProperties().values()) {
                                    Object p_value = property.getValue();
                                    if (!p_value.equals(false)) {
                                        MobileSmartSourceType msst = property.getSmartType();
                                        if (Mode.SCRIPT.equals(msst.getMode()) || Mode.SOURCE.equals(msst.getMode())) {
                                            scanSmartSource(uide, property.getName(), msst);
                                        }
                                    }
                                }
                            }
                        }
                        super.walk(databaseObject);
                    }
                }
            }
        }.init(origin);
    } catch (Exception e) {
        throw new Exception("Unable to scan for variables", e);
    }
}
Also used : UICompVariable(com.twinsoft.convertigo.beans.mobile.components.UICompVariable) IonProperty(com.twinsoft.convertigo.beans.mobile.components.dynamic.IonProperty) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MobileSmartSourceType(com.twinsoft.convertigo.beans.mobile.components.MobileSmartSourceType) IonBean(com.twinsoft.convertigo.beans.mobile.components.dynamic.IonBean) UIComponent(com.twinsoft.convertigo.beans.mobile.components.UIComponent) UIControlDirective(com.twinsoft.convertigo.beans.mobile.components.UIControlDirective) UIDynamicElement(com.twinsoft.convertigo.beans.mobile.components.UIDynamicElement) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper) Method(java.lang.reflect.Method) UISharedComponent(com.twinsoft.convertigo.beans.mobile.components.UISharedComponent) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) ArrayList(java.util.ArrayList) List(java.util.List) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) HashSet(java.util.HashSet)

Aggregations

WalkHelper (com.twinsoft.convertigo.engine.helpers.WalkHelper)25 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)24 Project (com.twinsoft.convertigo.beans.core.Project)14 EngineException (com.twinsoft.convertigo.engine.EngineException)10 IOException (java.io.IOException)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 CoreException (org.eclipse.core.runtime.CoreException)8 Transaction (com.twinsoft.convertigo.beans.core.Transaction)7 Step (com.twinsoft.convertigo.beans.core.Step)6 ArrayList (java.util.ArrayList)6 JSONException (org.codehaus.jettison.json.JSONException)6 Connector (com.twinsoft.convertigo.beans.core.Connector)5 Criteria (com.twinsoft.convertigo.beans.core.Criteria)5 ScreenClass (com.twinsoft.convertigo.beans.core.ScreenClass)5 Sequence (com.twinsoft.convertigo.beans.core.Sequence)5 Sheet (com.twinsoft.convertigo.beans.core.Sheet)5 Statement (com.twinsoft.convertigo.beans.core.Statement)5 TestCase (com.twinsoft.convertigo.beans.core.TestCase)5 TreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject)5 RequestableStep (com.twinsoft.convertigo.beans.core.RequestableStep)4