Search in sources :

Example 11 with TwsCachedXPathAPI

use of com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI in project convertigo by convertigo.

the class StepWithExpressions method getStepCopyToInvoke.

private Step getStepCopyToInvoke(Step step) throws EngineException {
    Step stepToInvoke = getStepCopy(step);
    if (stepToInvoke != null) {
        stepToInvoke.parent = this;
        stepToInvoke.transactionContextMaintainer = ((sequence.useSameJSessionForSteps()) ? this : null);
        stepToInvoke.xpathApi = new TwsCachedXPathAPI(getProject());
        // require new HttpState!
        stepToInvoke.httpState = sequence.getNewHttpState();
        stepToInvoke.executedSteps.putAll(executedSteps);
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans.trace("(StepWithExpression) " + step + " [" + step.hashCode() + "] has been copied into " + stepToInvoke + " [" + stepToInvoke.hashCode() + "]");
    }
    return stepToInvoke;
}
Also used : ParallelStep(com.twinsoft.convertigo.beans.steps.ParallelStep) BranchStep(com.twinsoft.convertigo.beans.steps.BranchStep) TwsCachedXPathAPI(com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)

Example 12 with TwsCachedXPathAPI

use of com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI in project convertigo by convertigo.

the class Sequence method prepareForRequestable.

@Override
public void prepareForRequestable(Context context, org.mozilla.javascript.Context javascriptContext, Scriptable scope) throws EngineException {
    currentChildStep = 0;
    xpathApi = new TwsCachedXPathAPI(getProject());
    copies = new HashMap<String, Step>(100);
    childrenSteps = new HashMap<String, Long>(100);
    executedSteps = new HashMap<Long, String>(1000);
    workerElementMap = new HashMap<String, Node>(1000);
    insertObjectsInScope();
}
Also used : Node(org.w3c.dom.Node) BranchStep(com.twinsoft.convertigo.beans.steps.BranchStep) XMLCopyStep(com.twinsoft.convertigo.beans.steps.XMLCopyStep) TwsCachedXPathAPI(com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)

Example 13 with TwsCachedXPathAPI

use of com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI in project convertigo by convertigo.

the class OperationResponse method isMatching.

public boolean isMatching(Document xmlDocument) {
    if (xmlDocument != null && !xpath.isEmpty()) {
        try {
            TwsCachedXPathAPI xpathApi = new TwsCachedXPathAPI(getProject());
            NodeList nodeList = xpathApi.selectNodeList(xmlDocument, xpath);
            int length = nodeList.getLength();
            return (length > 0) ? true : false;
        } catch (Exception e) {
        }
    }
    return false;
}
Also used : NodeList(org.w3c.dom.NodeList) TwsCachedXPathAPI(com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)

Example 14 with TwsCachedXPathAPI

use of com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI in project convertigo by convertigo.

the class SqlTransaction method runCore.

@Override
public void runCore() throws EngineException {
    try {
        // Create an empty list for hidden variable values
        List<String> logHiddenValues = new ArrayList<String>();
        connector = ((SqlConnector) parent);
        rollbackDone = false;
        if (!runningThread.bContinue)
            return;
        // We check variables and initialize queries if we have a change
        if (!checkVariables(preparedSqlQueries)) {
            preparedSqlQueries = initializeQueries(true);
        }
        if (preparedSqlQueries.size() > 0) {
            if (!preparedSqlQueries.get(0).getParametersMap().isEmpty()) {
                preparedSqlQueries.get(0).getParametersMap().get(preparedSqlQueries.get(0).getOrderedParametersList().get(0));
            }
        }
        // Start generating the response schema
        Element xsd_parent = getSchemaContainerElement();
        boolean inError = false;
        for (SqlQueryInfos sqlQueryInfos : preparedSqlQueries) {
            // Prepare the query and retrieve its type
            String query = prepareQuery(logHiddenValues, sqlQueryInfos);
            if (!runningThread.bContinue)
                return;
            // Execute the SELECT query
            SqlKeywords queryType = sqlQueryInfos.getType();
            switch(queryType) {
                case commit:
                    {
                        inError = doCommit();
                    }
                    break;
                case rollback:
                    {
                        inError = doRollback(true);
                    }
                    break;
                case call:
                case select:
                case replace:
                case create_table:
                case drop_table:
                case truncate_table:
                case update:
                case insert:
                case delete:
                case unknown:
                    {
                        // execute query
                        inError = doExecute(query, logHiddenValues, sqlQueryInfos);
                        // retrieve and append results/outputs, build inner xsd
                        if (!inError) {
                            try {
                                boolean bContinue = true;
                                ResultSet rs = null;
                                Integer nb = -1;
                                // append query results (resulset or update count)
                                do {
                                    if (!runningThread.bContinue)
                                        return;
                                    rs = preparedStatement.getResultSet();
                                    if (rs == null) {
                                        nb = preparedStatement.getUpdateCount();
                                    }
                                    if (rs != null || nb != -1) {
                                        getQueryResults(rs, nb, xsd_parent, query, logHiddenValues, sqlQueryInfos);
                                        if (!preparedStatement.getMoreResults()) {
                                            bContinue = preparedStatement.getUpdateCount() != -1;
                                        }
                                        rs = null;
                                        nb = -1;
                                    } else {
                                        bContinue = false;
                                    }
                                } while (bContinue);
                                // append procedure/function outputs (callable statement only)
                                getQueryOuts(xsd_parent, sqlQueryInfos);
                            } catch (SQLException e) {
                                inError = true;
                                Element sql_output = parseResults(e.getMessage());
                                if (sql_output != null) {
                                    Element outputDocumentRootElement = context.outputDocument.getDocumentElement();
                                    outputDocumentRootElement.appendChild(sql_output);
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
            score += 1;
            // Close statement and current resulset if exist
            if (preparedStatement != null)
                preparedStatement.close();
            if (!runningThread.bContinue)
                return;
            if (inError)
                break;
        }
        // We commit if auto-commit parameter is false
        if (!rollbackDone && (autoCommit == AutoCommitMode.autocommit_end.ordinal())) {
            try {
                connector.connection.commit();
            } catch (SQLException excep) {
                Element sql_output = parseResults(excep.getMessage());
                if (sql_output != null) {
                    Element outputDocumentRootElement = context.outputDocument.getDocumentElement();
                    outputDocumentRootElement.appendChild(sql_output);
                }
            }
        }
        if (generateJsonTypes) {
            TwsCachedXPathAPI xpathApi = context.getXpathApi();
            Element sql_out = (Element) xpathApi.selectSingleNode(context.outputDocument, "/*/sql_output");
            if (Engine.logBeans.isTraceEnabled()) {
                Engine.logEngine.trace("(SqlTransaction) outputDocument before json: " + XMLUtils.prettyPrintDOM(context.outputDocument));
                Engine.logEngine.trace("(SqlTransaction) tables before json: " + tables);
            }
            if (tables != null) {
                sql_out.setAttribute("type", "array");
                if (xmlMode == XmlMode.flat_element) {
                    Map<Integer, Pair<String, String>> types = new HashMap<Integer, Pair<String, String>>();
                    for (List<List<Object>> columns : tables.values()) {
                        for (List<Object> col : columns) {
                            String cls = ((String) col.get(2)).toLowerCase();
                            String type = "string";
                            if (cls.startsWith("java.lang.")) {
                                type = cls.substring(10);
                            }
                            types.put((Integer) col.get(0), ImmutablePair.of((String) col.get(1), type));
                        }
                    }
                    NodeList rows = xpathApi.selectNodeList(context.outputDocument, "/*/sql_output/*");
                    for (int i = 0; i < rows.getLength(); i++) {
                        Element row = ((Element) rows.item(i));
                        row.setAttribute("type", "object");
                        if (types != null) {
                            NodeList fields = xpathApi.selectNodeList(row, "*");
                            for (int j = 0; j < fields.getLength(); j++) {
                                Pair<String, String> info = types.get(j + 1);
                                Element field = ((Element) fields.item(j));
                                field.setAttribute("type", info.getRight());
                                if (!field.getTagName().equals(info.getLeft())) {
                                    field.setAttribute("originalKeyName", info.getLeft());
                                }
                            }
                        }
                    }
                }
            } else {
                sql_out.setAttribute("type", "string");
            }
        }
        // Store learned schema
        if (Engine.isStudioMode() && xsd_parent != null) {
            Document doc = xsd_parent.getOwnerDocument();
            if (doc != null) {
                String prettyPrintedText = XMLUtils.prettyPrintDOM(doc);
                prettyPrintedText = prettyPrintedText.substring(prettyPrintedText.indexOf("<xsd:"));
                xsdType = prettyPrintedText;
            }
        }
    } catch (Exception e) {
        connector.setData(null, null);
        throw new EngineException("An unexpected error occured while executing transaction. Could not execute the SQL query.", e);
    } finally {
        try {
            if (preparedStatement != null)
                preparedStatement.close();
        } catch (SQLException e) {
            ;
        }
        preparedStatement = null;
    }
}
Also used : SQLException(java.sql.SQLException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) EngineException(com.twinsoft.convertigo.engine.EngineException) SqlConnector(com.twinsoft.convertigo.beans.connectors.SqlConnector) Document(org.w3c.dom.Document) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) NodeList(org.w3c.dom.NodeList) List(java.util.List) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) NodeList(org.w3c.dom.NodeList) SQLException(java.sql.SQLException) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwsCachedXPathAPI(com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)

Example 15 with TwsCachedXPathAPI

use of com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI in project convertigo by convertigo.

the class XPathToCheck method migrate.

public static void migrate(String projectName) {
    try {
        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);
        MobileApplication mobileApplication = project.getMobileApplication();
        if (mobileApplication != null) {
            TwsCachedXPathAPI xpathApi = new TwsCachedXPathAPI();
            // Tags to change for all platforms
            List<XPathToCheck> xPathToCheckDefault = new LinkedList<XPathToCheck>();
            xPathToCheckDefault.add(new XPathToCheck("/widget/preference[@name='phonegap-version']", "", true));
            xPathToCheckDefault.add(new XPathToCheck("/widget/preference[@name='SplashScreen']", "", true));
            xPathToCheckDefault.add(new XPathToCheck("/widget/preference[@name='ShowSplashScreenSpinner']", "", true));
            String[][] pluginList = new String[][] { { "org.apache.cordova.device", "org.apache.cordova.file", "org.apache.cordova.file-transfer", "org.apache.cordova.splashscreen", "cordova-plugin-whitelist", "org.apache.cordova.console" }, { "cordova-plugin-device", "cordova-plugin-file", "cordova-plugin-file-transfer", "cordova-plugin-splashscreen", "cordova-plugin-whitelist", "cordova-plugin-console" } };
            for (int i = 0; i < pluginList[0].length; i++) {
                xPathToCheckDefault.add(new XPathToCheck("/widget/*[local-name()='plugin' and @name='" + pluginList[0][i] + "']", "/widget/plugin[@name='" + pluginList[1][i] + "']", true));
                xPathToCheckDefault.add(new XPathToCheck("/widget/*[local-name()='plugin' and @name='" + pluginList[1][i] + "']", "/widget/plugin[@name='" + pluginList[1][i] + "']", true));
            }
            pluginList = new String[][] { { "com.couchbase.lite.phonegap", "org.apache.cordova.battery-status", "org.apache.cordova.camera", "org.apache.cordova.media-capture", "org.apache.cordova.contacts", "org.apache.cordova.device-motion", "org.apache.cordova.device-orientation", "org.apache.cordova.dialogs", "org.apache.cordova.geolocation", "org.apache.cordova.globalization", "org.apache.cordova.inappbrowser", "org.apache.cordova.media", "org.apache.cordova.network-information", "org.apache.cordova.vibration", "org.apache.cordova.statusbar", "com.phonegap.plugins.pushplugin", "com.phonegap.plugins.barcodescanner" }, { "couchbase-lite-phonegap-plugin", "cordova-plugin-battery-status", "cordova-plugin-camera", "cordova-plugin-media-capture", "cordova-plugin-contacts", "cordova-plugin-device-motion", "cordova-plugin-device-orientation", "cordova-plugin-dialogs", "cordova-plugin-geolocation", "cordova-plugin-globalization", "cordova-plugin-inappbrowser", "cordova-plugin-media", "cordova-plugin-network-information", "cordova-plugin-vibration", "cordova-plugin-statusbar", "phonegap-plugin-push", "phonegap-plugin-barcodescanner" } };
            // Tags to change only for Android
            List<XPathToCheck> xPathToCheckAndroid = new LinkedList<XPathToCheck>();
            xPathToCheckAndroid.addAll(xPathToCheckDefault);
            xPathToCheckAndroid.add(new XPathToCheck("/widget/platform[@name='android' and not(*)]", "/widget/engine[@name='$(CordovaPlatform)$']", true));
            xPathToCheckAndroid.add(new XPathToCheck("/widget/preference[@name='android-minSdkVersion']", "", true));
            xPathToCheckAndroid.add(new XPathToCheck("/widget/preference[@name='android-build-tool']", "", true));
            String[] androidResList = new String[] { "ldpi", "mdpi", "hdpi", "xhdpi" };
            for (String androidRes : androidResList) {
                xPathToCheckAndroid.add(new XPathToCheck("/widget/icon[@gap:platform='android' and @gap:qualifier='" + androidRes + "']", "/widget/platform[@name='android']/icon[@density='" + androidRes + "']", false));
            }
            androidResList = new String[] { "ldpi", "mdpi", "hdpi", "xhdpi", "land-ldpi", "land-mdpi", "land-hdpi", "land-xhdpi" };
            for (String androidRes : androidResList) {
                xPathToCheckAndroid.add(new XPathToCheck("/widget/splash[@gap:platform='android' and @gap:qualifier='" + androidRes + "']", "/widget/platform[@name='android']/splash[@density='" + androidRes + "']", false));
            }
            // Tags to change only for iOS
            List<XPathToCheck> xPathToCheckIOs = new LinkedList<XPathToCheck>();
            xPathToCheckIOs.addAll(xPathToCheckDefault);
            xPathToCheckIOs.add(new XPathToCheck("/widget/platform[@name='ios']", "/widget/engine[@name='$(CordovaPlatform)$']", true));
            xPathToCheckIOs.add(new XPathToCheck("/widget/preference[@name='target-device' and @value='universal']", null, true));
            String[] iosResList = new String[] { "180", "120", "57", "72", "114", "144" };
            for (String iosRes : iosResList) {
                xPathToCheckIOs.add(new XPathToCheck("/widget/icon[@gap:platform='ios' and @width='" + iosRes + "']", "/widget/platform[@name='ios']/icon[@width='" + iosRes + "']", false));
            }
            iosResList = new String[] { "2208", "1334", "1136", "1496", "748", "2008", "1004", "960", "480" };
            for (String iosRes : iosResList) {
                xPathToCheckIOs.add(new XPathToCheck("/widget/splash[@gap:platform='ios' and @height='" + iosRes + "']", "/widget/platform[@name='ios']/splash[@height='" + iosRes + "']", false));
            }
            xPathToCheckIOs.add(new XPathToCheck("/widget/access", "", true));
            // Tags to change only for Windows Phone 8
            List<XPathToCheck> xPathToCheckWinPhone8 = new LinkedList<XPathToCheck>();
            xPathToCheckWinPhone8.addAll(xPathToCheckDefault);
            xPathToCheckWinPhone8.add(new XPathToCheck("/widget/platform[@name='winphone' and not(*)]", "/widget/engine[@name='$(CordovaPlatform)$']", true));
            xPathToCheckWinPhone8.add(new XPathToCheck("/widget/icon[@gap:platform='winphone' and not(@gap:role)]", "/widget/platform[@name='wp8']/icon[not(@role)]", false));
            xPathToCheckWinPhone8.add(new XPathToCheck("/widget/icon[@gap:platform='winphone' and @gap:role='background']", "/widget/platform[@name='wp8']/icon[@role='background']", false));
            xPathToCheckWinPhone8.add(new XPathToCheck("/widget/splash[@gap:platform='winphone']", "/widget/platform[@name='wp8']/splash[@src]", false));
            // Iterates on each platforms
            List<MobilePlatform> mobilePlatformList = mobileApplication.getMobilePlatformList();
            for (MobilePlatform mobilePlatform : mobilePlatformList) {
                // Get the config.xml file and load the xml
                File configFile = new File(mobilePlatform.getResourceFolder(), "config.xml");
                if (configFile.exists()) {
                    Document oldDoc = XMLUtils.loadXml(configFile);
                    // Gets the tags to change depending to the platform
                    List<XPathToCheck> xPathToCheckList = null;
                    String platformName = null;
                    if (mobilePlatform instanceof Android) {
                        xPathToCheckList = xPathToCheckAndroid;
                        platformName = "Android";
                    } else if (mobilePlatform instanceof IOs) {
                        xPathToCheckList = xPathToCheckIOs;
                        platformName = "IOs";
                    } else if (mobilePlatform instanceof WindowsPhone8) {
                        xPathToCheckList = xPathToCheckWinPhone8;
                        platformName = "WindowsPhone8";
                    } else {
                        continue;
                    }
                    // Gets the template config.xml file and load the xml
                    String configTemplatePath = Engine.TEMPLATES_PATH + "/base/DisplayObjects/platforms/" + platformName + "/config.xml";
                    File configTemplateFile = new File(configTemplatePath);
                    if (!configTemplateFile.exists()) {
                        throw new Exception("Can't find template config.xml at " + configTemplatePath);
                    }
                    Document templateDoc = XMLUtils.loadXml(configTemplateFile);
                    for (XPathToCheck xPathToCheck : xPathToCheckList) {
                        Element oldElement = (Element) xpathApi.selectSingleNode(oldDoc, xPathToCheck.oldXpath);
                        // If the goal is to remove the old node
                        if (xPathToCheck.templateXpath == null) {
                            if (oldElement != null) {
                                oldElement.getParentNode().removeChild(oldElement);
                            }
                            continue;
                        }
                        Element templateElement = (Element) xpathApi.selectSingleNode(templateDoc, xPathToCheck.templateXpath);
                        // Can't do anything if the element is not found in the template file
                        if (templateElement == null) {
                            continue;
                        }
                        // Replace the old element by the template
                        if (oldElement != null || xPathToCheck.required) {
                            // If the template is already in the old config.xml
                            Element templateOldElement = (Element) xpathApi.selectSingleNode(oldDoc, xPathToCheck.templateXpath);
                            if (templateOldElement != null && templateElement.isEqualNode(templateOldElement)) {
                                continue;
                            }
                            String xPathTemplateParent = xPathToCheck.templateXpath.substring(0, xPathToCheck.templateXpath.lastIndexOf('/'));
                            Node parentNode = createSameTree(oldDoc, templateElement.getParentNode(), xPathTemplateParent, xpathApi);
                            Node newNode = oldDoc.adoptNode(templateElement.cloneNode(true));
                            if (oldElement != null) {
                                if (parentNode.isSameNode(oldElement.getParentNode())) {
                                    parentNode.replaceChild(newNode, oldElement);
                                } else {
                                    parentNode.appendChild(newNode);
                                    oldElement.getParentNode().removeChild(oldElement);
                                }
                            } else {
                                parentNode.appendChild(newNode);
                            }
                        }
                    }
                    for (int i = 0; i < pluginList[0].length; i++) {
                        Node comment = xpathApi.selectNode(oldDoc, "//comment()[contains(.,\"" + pluginList[1][i] + "\")]");
                        if (comment == null) {
                            comment = xpathApi.selectNode(oldDoc, "//comment()[contains(.,\"" + pluginList[0][i] + "\")]");
                        }
                        if (comment != null) {
                            Node newComment = xpathApi.selectNode(templateDoc, "//comment()[contains(.,\"" + pluginList[1][i] + "\")]");
                            comment.getParentNode().replaceChild(oldDoc.adoptNode(newComment), comment);
                        }
                    }
                    File oldConfigFile = new File(configFile.getParent(), "config.xml.old");
                    if (!oldConfigFile.exists()) {
                        oldConfigFile.createNewFile();
                    }
                    FileUtils.copyFile(configFile, oldConfigFile);
                    File newConfigFile = new File(mobilePlatform.getResourceFolder(), "config.xml");
                    if (!newConfigFile.exists()) {
                        newConfigFile.createNewFile();
                    }
                    XMLUtils.saveXml(oldDoc, newConfigFile.getAbsolutePath());
                }
            }
        }
    } catch (Exception e) {
        Engine.logDatabaseObjectManager.error("[Migration 7.4.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}
Also used : WindowsPhone8(com.twinsoft.convertigo.beans.mobileplatforms.WindowsPhone8) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) IOs(com.twinsoft.convertigo.beans.mobileplatforms.IOs) LinkedList(java.util.LinkedList) Android(com.twinsoft.convertigo.beans.mobileplatforms.Android) Project(com.twinsoft.convertigo.beans.core.Project) MobilePlatform(com.twinsoft.convertigo.beans.core.MobilePlatform) MobileApplication(com.twinsoft.convertigo.beans.core.MobileApplication) File(java.io.File) TwsCachedXPathAPI(com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)

Aggregations

TwsCachedXPathAPI (com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI)18 Document (org.w3c.dom.Document)13 NodeList (org.w3c.dom.NodeList)11 Element (org.w3c.dom.Element)10 Node (org.w3c.dom.Node)8 TransformerException (javax.xml.transform.TransformerException)7 LinkedList (java.util.LinkedList)5 HtmlConnector (com.twinsoft.convertigo.beans.connectors.HtmlConnector)4 Android (com.twinsoft.convertigo.beans.mobileplatforms.Android)4 WindowsPhone8 (com.twinsoft.convertigo.beans.mobileplatforms.WindowsPhone8)4 EngineException (com.twinsoft.convertigo.engine.EngineException)4 File (java.io.File)4 IOException (java.io.IOException)4 List (java.util.List)4 MobileApplication (com.twinsoft.convertigo.beans.core.MobileApplication)3 MobilePlatform (com.twinsoft.convertigo.beans.core.MobilePlatform)3 IOs (com.twinsoft.convertigo.beans.mobileplatforms.IOs)3 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)2 Project (com.twinsoft.convertigo.beans.core.Project)2 Windows (com.twinsoft.convertigo.beans.mobileplatforms.Windows)2