Search in sources :

Example 16 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class JavelinConnector method prepareForTransaction.

@Override
public void prepareForTransaction(Context context) throws EngineException {
    String t = context.statistics.start(EngineStatistics.GET_JAVELIN_OBJECT);
    try {
        // Quick and dirty workaround for ticket #1280
        if (!checkKeys())
            throw new EngineException("No more key available; check your license keys!");
        // if something append during transaction execution
        com.twinsoft.api.Session session = Engine.theApp.sessionManager.getSession(context.contextID);
        if (session != null)
            session.resetSomethingChange();
        if (Engine.isStudioMode()) {
            if (javelin != null) {
                Engine.logBeans.debug("(JavelinConnector) Using the studio Javelin object");
                return;
            }
            throw new EngineException("Studio mode: the Legacy connector must be open in order to execute transactions");
        }
        Engine.logBeans.debug("(JavelinConnector) Retrieving the Javelin object");
        JavelinTransaction javelinTransaction = null;
        try {
            javelinTransaction = (JavelinTransaction) context.requestedObject;
        } catch (ClassCastException e) {
            throw new EngineException("Requested object is not a transaction", e);
        }
        int timeout = javelinTransaction.getTimeoutForDataStable();
        int threshold = javelinTransaction.getDataStableThreshold();
        Authentication auth = null;
        if (context.isRequestFromVic) {
            // instance, from a web service call).
            if (!context.isTrustedRequest) {
                try {
                    VicApi vicApi = new VicApi();
                    if (!vicApi.isServiceAuthorized(context.tasUserName, context.tasVirtualServerName, context.tasServiceCode)) {
                        throw new EngineException("The service '" + context.tasServiceCode + "' is not authorized for the user '" + context.tasUserName);
                    }
                } catch (IOException e) {
                    throw new EngineException("Unable to retrieve authorization from the VIC database.", e);
                }
            }
        } else {
            // Check the Carioca authorizations only if this is a non trusted request
            if (context.isTrustedRequest) {
            // Nothing to do: all the tas* variables from the context must have been set
            // by the caller.
            // Means we must not execute the TAS API.
            } else {
                // Getting Authentication object
                context.tasVirtualServerName = getVirtualServer();
                try {
                    String authName = (context.tasSessionKey == null ? context.tasUserName : context.tasSessionKey);
                    auth = Engine.theApp.getAuthenticationObject(context.tasVirtualServerName, authName);
                    // Logging to Carioca only if needed
                    User user = auth.getCurrentUser();
                    if (user == null) {
                        // Request from Carioca
                        if (context.tasSessionKey != null) {
                            auth.login(context.tasSessionKey);
                            User currentUser = auth.getCurrentUser();
                            context.tasUserName = currentUser.getName();
                            context.tasUserPassword = currentUser.getPassword();
                            context.tasVirtualServerName = "(SV #" + currentUser.getServerID() + ")";
                            String message = "Authentication to Carioca with sesskey = '" + context.tasSessionKey + "' => user: \"" + context.tasUserName + "\"";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        } else // Specific user
                        if ((context.tasUserName != null) && (context.tasUserPassword != null)) {
                            auth.login(context.tasUserName, context.tasUserPassword);
                            String message = "Authentication to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        } else {
                            context.tasUserName = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
                            context.tasUserPassword = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
                            auth.login(context.tasUserName, context.tasUserPassword);
                            String message = "Default authentication to Carioca";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        }
                    } else {
                        context.tasUserName = user.getName();
                        context.tasUserPassword = user.getPassword();
                        context.tasUserGroup = user.getMainGroupName();
                        context.tasVirtualServerName = "(#" + Long.toString(user.getServerID()) + ")";
                        String message = "Already authenticated to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
                        Engine.logBeans.debug("(JavelinConnector) " + message);
                    }
                } catch (Exception e) {
                    auth = null;
                    String message = "Unable to authenticate to Carioca.\n" + "Carioca virtual server: " + context.tasVirtualServerName + "\n" + "SessKey: \"" + context.tasSessionKey + "\"\n" + "User: \"" + context.tasUserName + "\"\n" + "Password: \"" + context.tasUserPassword + "\"";
                    EngineException ee = new EngineException(message, e);
                    throw ee;
                }
            }
        }
        // We retrieve the current project
        String javelinServiceCode = context.tasServiceCode;
        if (javelinServiceCode == null) {
            javelinServiceCode = getServiceCode();
            Engine.logBeans.debug("(JavelinConnector)  No service code provided; getting the connector service code.");
        }
        // Analyzes/overrrides service code for device number pooling
        javelinServiceCode = analyzeServiceCode(javelinServiceCode);
        Engine.logBeans.debug("(JavelinConnector) Service code: " + javelinServiceCode);
        session = Engine.theApp.sessionManager.getSession(context.contextID);
        if (session == null) {
            Engine.logBeans.debug("(JavelinConnector) No session has been found; creation of a new one and ignoring the user request.");
            context.inputDocument = null;
            try {
                if (context.isRequestFromVic) {
                    session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup + "@" + context.tasVirtualServerName, context.tasDteAddress, context.tasCommDevice, context.contextID);
                } else if (context.isTrustedRequest) {
                    String connectionParameters = getServiceCode();
                    try {
                        StringTokenizer st = new StringTokenizer(connectionParameters, ",");
                        String appType = st.nextToken();
                        if (appType.equals("vic")) {
                            javelinServiceCode = st.nextToken();
                            context.tasDteAddress = st.nextToken();
                            context.tasCommDevice = st.nextToken();
                            Engine.logBeans.debug("(JavelinConnector) Trusted request => the connector handles connection parameters : " + connectionParameters);
                            Engine.logBeans.debug("(JavelinConnector) serviceCode: " + javelinServiceCode);
                            Engine.logBeans.debug("(JavelinConnector) dteAddress: " + context.tasDteAddress);
                            Engine.logBeans.debug("(JavelinConnector) commDevice: " + context.tasCommDevice);
                            Engine.logBeans.debug("(JavelinConnector) user: " + context.tasUserName);
                            String group = context.tasUserGroup + "@" + context.tasVirtualServerName;
                            Engine.logBeans.debug("(JavelinConnector) group: " + group);
                            session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, group, context.tasDteAddress, context.tasCommDevice, context.contextID);
                        }
                    } catch (NoSuchElementException e) {
                        Engine.logBeans.error("(JavelinConnector) Invalid connector connection parameters: " + connectionParameters);
                    }
                } else {
                    session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
                }
            } catch (Exception e) {
                String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
                EngineException ee = new EngineException(message, e);
                throw ee;
            }
            if (session == null) {
                String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
                EngineException ee = new EngineException(message);
                throw ee;
            }
            javelin = session.getJavelinObject();
            javelin.setLog(new LogWrapper(Engine.logEmulators));
            javelin.setDataStableOnCursorOn(false);
            javelin.connect(javelinTransaction.getTimeoutForConnect());
            boolean isConnected = javelin.isConnected();
            Engine.logBeans.debug("(JavelinConnector) isConnected=" + isConnected);
            if (!isConnected) {
                throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
            }
            executeConnectionSyncCode(javelin, timeout, threshold);
        } else {
            Engine.logBeans.debug("(JavelinConnector) Using the existing session");
            if (context.isNewSession) {
                Engine.logBeans.debug("(JavelinConnector) New session required and ignoring the user request");
                context.inputDocument = null;
                // First, we remove the previous session
                Engine.theApp.sessionManager.removeSession(context.contextID);
                try {
                    if (context.isRequestFromVic) {
                        session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup, context.tasDteAddress, context.tasCommDevice, context.contextID);
                    } else {
                        session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
                    }
                } catch (Exception e) {
                    String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
                    Engine.logBeans.warn("(JavelinConnector) " + message);
                    EngineException ee = new EngineException(message, e);
                    throw ee;
                }
                if (session == null) {
                    String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
                    Engine.logBeans.warn("(JavelinConnector) " + message);
                    EngineException ee = new EngineException(message);
                    throw ee;
                }
                javelin = session.getJavelinObject();
                javelin.setLog(new LogWrapper(Engine.logEmulators));
                javelin.setDataStableOnCursorOn(false);
                javelin.connect(javelinTransaction.getTimeoutForConnect());
                if (!javelin.isConnected()) {
                    throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
                }
                executeConnectionSyncCode(javelin, timeout, threshold);
            } else {
                javelin = session.getJavelinObject();
                // Reconnect only if the requested transaction is not the end transaction
                if ((!context.isDestroying) && (!session.isConnected())) {
                    javelin.setDataStableOnCursorOn(false);
                    javelin.connect(javelinTransaction.getTimeoutForConnect());
                    if (!javelin.isConnected()) {
                        throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
                    }
                    executeConnectionSyncCode(javelin, timeout, threshold);
                }
            }
        }
        context.isNewSession = false;
    } finally {
        context.statistics.stop(t);
    }
}
Also used : User(com.twinsoft.tas.User) EngineException(com.twinsoft.convertigo.engine.EngineException) FindString(com.twinsoft.convertigo.beans.common.FindString) IOException(java.io.IOException) LogWrapper(com.twinsoft.convertigo.engine.util.LogWrapper) RESyntaxException(org.apache.regexp.RESyntaxException) NoSuchElementException(java.util.NoSuchElementException) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException) JavelinTransaction(com.twinsoft.convertigo.beans.transactions.JavelinTransaction) StringTokenizer(java.util.StringTokenizer) Authentication(com.twinsoft.tas.Authentication) VicApi(com.twinsoft.convertigo.engine.plugins.VicApi) NoSuchElementException(java.util.NoSuchElementException)

Example 17 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class JavelinConnector method waitAtScreenClass.

/**
 * Waits for one of the screens described by the screen classes
 * in the project to arrive. The method waits for all the screen classes
 * except the current one. You can use waitAtScreenClass() method to synchronize
 * your handler before returning "redetect", "accumulate" or "skip".
 *
 * @param context		the Convertigo context.
 * @param timeout		the time (in ms) we have to wait for the screen class.
 * @param hardDelay		a delay (in ms) added after the screen class has arrived.
 *
 * @return				true, if we the screen did arrive, false otherwise.
 */
public boolean waitAtScreenClass(Context context, int timeout, int hardDelay) throws EngineException {
    if (javelin != null) {
        try {
            List<JavelinScreenClass> vScreenClasses = getAllScreenClasses();
            List<Criteria> vCriterias;
            List<Criteria> vAllCriterias = new ArrayList<Criteria>(128);
            RegularExpression regularExpression;
            FindString findString;
            int j = 0;
            ScreenClass lastDetectedScreenClass = (ScreenClass) context.lastDetectedObject;
            for (ScreenClass screenClass : vScreenClasses) {
                // Do not detect the current screen class
                if ((lastDetectedScreenClass != null) && (screenClass.getName().equals(lastDetectedScreenClass.getName()))) {
                    Engine.logBeans.debug("(JavelinConnector) WaitAtScreenClass(): last detected screen class is " + lastDetectedScreenClass.getName());
                    continue;
                }
                vCriterias = screenClass.getLocalCriterias();
                for (Criteria criteria : vCriterias) {
                    if (criteria instanceof FindString) {
                        findString = (FindString) criteria;
                        if ((findString.getX() == -1) || (findString.getX() == -1)) {
                            Engine.logBeans.debug("(JavelinConnector) Ignoring criteria \"" + findString.getString() + "\" at (" + findString.getX() + ", " + findString.getY() + ")");
                        } else {
                            Engine.logBeans.debug("(JavelinConnector) Adding a wait at ID:" + j + " \"" + findString.getString() + "\" at (" + findString.getX() + ", " + findString.getY() + ")");
                            javelin.waitAtId(j, findString.getString(), findString.getX(), findString.getY());
                            vAllCriterias.add(criteria);
                            j++;
                        }
                    } else if (criteria instanceof RegularExpression) {
                        regularExpression = (RegularExpression) criteria;
                        if ((regularExpression.getX() == -1) || (regularExpression.getX() == -1)) {
                            Engine.logBeans.debug("(JavelinConnector) Ignoring criteria \"" + regularExpression.getRegularExpression() + "\" at (" + regularExpression.getX() + ", " + regularExpression.getY() + ")");
                        } else {
                            Engine.logBeans.debug("(JavelinConnector) Adding a wait at ID:" + j + " \"" + regularExpression.getRegularExpression() + "\" at (" + regularExpression.getX() + ", " + regularExpression.getY() + ")");
                            javelin.waitAtId(j, regularExpression.getRegularExpression(), regularExpression.getX(), regularExpression.getY());
                            vAllCriterias.add(criteria);
                            j++;
                        }
                    }
                }
            }
            j = javelin.waitTrigger(timeout);
            javelin.deleteWaitAts();
            Criteria criteria;
            if (j != -1) {
                criteria = (Criteria) vAllCriterias.get(j);
                String string = "?";
                int x = -1;
                int y = -1;
                if (criteria instanceof FindString) {
                    findString = (FindString) criteria;
                    string = findString.getString();
                    x = findString.getX();
                    y = findString.getY();
                } else if (criteria instanceof RegularExpression) {
                    regularExpression = (RegularExpression) criteria;
                    string = regularExpression.getRegularExpression();
                    x = regularExpression.getX();
                    y = regularExpression.getY();
                }
                Engine.logBeans.debug("(JavelinConnector) WaitAtScreenClass(): found criteria ID:" + j + " \"" + string + "\" at (" + x + ", " + y + ")");
                if (hardDelay > 0) {
                    javelin.waitSync(hardDelay);
                }
                return true;
            }
            Engine.logBeans.debug("(JavelinConnector) Automatic data stable event detection aborted because of timeout!");
            return false;
        } catch (Exception e) {
            Engine.logBeans.error("Exception while trying to wait at screen class", e);
            throw new EngineException("Unable to wait at screen class! See the emulator log for more details...", e);
        }
    } else {
        throw new EngineException("Unable to call the waitAtScreenClass() function without a Javelin emulator!");
    }
}
Also used : RegularExpression(com.twinsoft.convertigo.beans.common.RegularExpression) JavelinScreenClass(com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass) ScreenClass(com.twinsoft.convertigo.beans.core.ScreenClass) JavelinScreenClass(com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass) ArrayList(java.util.ArrayList) EngineException(com.twinsoft.convertigo.engine.EngineException) Criteria(com.twinsoft.convertigo.beans.core.Criteria) FindString(com.twinsoft.convertigo.beans.common.FindString) FindString(com.twinsoft.convertigo.beans.common.FindString) RESyntaxException(org.apache.regexp.RESyntaxException) NoSuchElementException(java.util.NoSuchElementException) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 18 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class JavelinConnector method waitNextPage.

/**
 * Waits for a new page for the same screen class or a new screen class.
 *
 * The method wait for one of the screens described by the screen classes in the
 * project to arrive. We wait for all the screen classes except the current one. In the
 * case of a next page on the same screen class, waitNextPage() will monitor the cursor
 * position. the method will return when the cursor position returns to the same position
 * it was before calling waitNextPage().
 *
 * You can use waitNextPage() method to synchronize your handler before returning
 * "redetect", "accumulate" or "skip".
 *
 * @param context 		the Convertigo context.
 * @param timeout		the time (in ms) we have to wait for the screen class.
 * @param hardDelay		a delay (in ms) added after the nextpage has arrived.
 *
 * @return				true, if we the page did arrive, false otherwise.
 */
public boolean waitNextPage(Context context, String action, int timeout, int hardDelay) throws EngineException {
    if (javelin != null) {
        try {
            List<JavelinScreenClass> vScreenClasses = getAllScreenClasses();
            List<Criteria> vCriterias;
            List<Criteria> vAllCriterias = new ArrayList<Criteria>(128);
            RegularExpression regularExpression;
            FindString findString;
            javelin.deleteWaitAts();
            ScreenClass lastDetectedScreenClass = (ScreenClass) context.lastDetectedObject;
            // Set all screen class criterias observations
            int j = 1;
            for (ScreenClass screenClass : vScreenClasses) {
                Engine.logBeans.debug("(JavelinConnector) Analyzing screen class \"" + screenClass.getName() + "\"");
                // Do not detect the current screen class
                if ((lastDetectedScreenClass != null) && (screenClass.getQName().equals(lastDetectedScreenClass.getQName()))) {
                    Engine.logBeans.debug("(JavelinConnector) Ignoring screen class \"" + screenClass.getName() + "\"");
                    continue;
                }
                vCriterias = screenClass.getLocalCriterias();
                for (Criteria criteria : vCriterias) {
                    if (criteria instanceof RegularExpression) {
                        regularExpression = (RegularExpression) criteria;
                        if ((regularExpression.getX() == -1) || (regularExpression.getX() == -1)) {
                            Engine.logBeans.debug("(JavelinConnector) Ignoring criteria \"" + regularExpression.getRegularExpression() + "\" at (" + regularExpression.getX() + ", " + regularExpression.getY() + ")");
                        } else {
                            Engine.logBeans.debug("(JavelinConnector) Adding a wait at ID: " + j + " \"" + regularExpression.getRegularExpression() + "\" at (" + regularExpression.getX() + ", " + regularExpression.getY() + ")");
                            javelin.waitAtId(j, regularExpression.getRegularExpression(), regularExpression.getX(), regularExpression.getY());
                            vAllCriterias.add(criteria);
                            j++;
                        }
                    }
                }
            }
            // Wait for the cursor to move out from the current location
            int line = javelin.getCurrentLine();
            int col = javelin.getCurrentColumn();
            Engine.logBeans.debug("(JavelinConnector) WaitNextPage(): cursor is now in col: " + col + ", line: " + line);
            javelin.waitCursorAtId(1, col, line, false);
            javelin.doAction(action);
            int ret = javelin.waitTrigger(timeout);
            if (ret == -1) {
                Engine.logBeans.debug("(JavelinConnector) WaitNextPage(): cursor did not move out in time");
                return false;
            }
            // Set one more observation ID on the cursor position
            Engine.logBeans.debug("(JavelinConnector) Adding a waitCursorAt at ID: " + 0 + " in col: " + col + ", line: " + line);
            javelin.waitCursorAtId(0, col, line, true);
            j = javelin.waitTrigger(timeout);
            javelin.deleteWaitAts();
            Criteria criteria;
            if (j != -1) {
                if (j < vAllCriterias.size()) {
                    criteria = (Criteria) vAllCriterias.get(j);
                    String string = "?";
                    int x = -1;
                    int y = -1;
                    if (criteria instanceof FindString) {
                        findString = (FindString) criteria;
                        string = findString.getString();
                        x = findString.getX();
                        y = findString.getY();
                    } else if (criteria instanceof RegularExpression) {
                        regularExpression = (RegularExpression) criteria;
                        string = regularExpression.getRegularExpression();
                        x = regularExpression.getX();
                        y = regularExpression.getY();
                    }
                    Engine.logBeans.debug("(JavelinConnector) WaitNextPage(): found criteria ID:" + j + " \"" + string + "\" at (" + x + ", " + y + ")");
                } else {
                    Engine.logBeans.debug("(JavelinConnector) WaitNextPage(): cursor back in col: " + col + ", line: " + line);
                }
                if (hardDelay > 0) {
                    javelin.waitSync(hardDelay);
                }
                return true;
            }
            Engine.logBeans.debug("(JavelinConnector) WaitNextPage(): automatic data stable event detection aborted because of timeout!");
            return false;
        } catch (Exception e) {
            Engine.logBeans.error("Exception while trying to wait next page", e);
            throw new EngineException("Unable to wait for the next page! See the emulator log for more details...", e);
        }
    } else {
        throw new EngineException("Unable to call the waitNextPage() function without a Javelin emulator!");
    }
}
Also used : RegularExpression(com.twinsoft.convertigo.beans.common.RegularExpression) JavelinScreenClass(com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass) ScreenClass(com.twinsoft.convertigo.beans.core.ScreenClass) JavelinScreenClass(com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass) ArrayList(java.util.ArrayList) EngineException(com.twinsoft.convertigo.engine.EngineException) Criteria(com.twinsoft.convertigo.beans.core.Criteria) FindString(com.twinsoft.convertigo.beans.common.FindString) FindString(com.twinsoft.convertigo.beans.common.FindString) RESyntaxException(org.apache.regexp.RESyntaxException) NoSuchElementException(java.util.NoSuchElementException) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 19 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class DatabaseObject method toXml.

public Element toXml(Document document) throws EngineException {
    Element element = document.createElement(getDatabaseType().toLowerCase());
    element.setAttribute("classname", getClass().getName());
    if (exportOptions.contains(ExportOption.bIncludeVersion)) {
        element.setAttribute("version", com.twinsoft.convertigo.beans.Version.version);
    }
    // Storing the database object priority
    element.setAttribute("priority", Long.toString(priority));
    int len;
    PropertyDescriptor[] propertyDescriptors;
    PropertyDescriptor propertyDescriptor;
    try {
        BeanInfo bi = CachedIntrospector.getBeanInfo(getClass());
        propertyDescriptors = bi.getPropertyDescriptors();
        len = propertyDescriptors.length;
        if (exportOptions.contains(ExportOption.bIncludeDisplayName)) {
            element.setAttribute("displayName", bi.getBeanDescriptor().getDisplayName());
        }
    } catch (IntrospectionException e) {
        throw new EngineException("Couldn't introspect the bean \"" + getName() + "\"", e);
    }
    for (int i = 0; i < len; i++) {
        propertyDescriptor = propertyDescriptors[i];
        String propertyDescriptorName = propertyDescriptor.getName();
        addProperty(document, element, propertyDescriptor, propertyDescriptorName);
    }
    return element;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Element(org.w3c.dom.Element) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 20 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class DatabaseObject method read.

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;
    objectClassName = element.getAttribute("classname");
    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }
    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if ("com.twinsoft.convertigo.beans.core.Project".equals(objectClassName) && VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        VersionException ee = new VersionException(version);
        throw ee;
    }
    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).getConstructor().newInstance();
    } catch (Exception e) {
        // XMLUtils.prettyPrintDOM(node);
        String s = node.getNodeName();
        String message = "Unable to create a new instance of the object from the serialized XML data.\n" + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }
    databaseObject.isImporting = true;
    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n" + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }
    try {
        long priority = Long.valueOf(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;
        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();
        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();
        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            Element childElement = (Element) childNode;
            childNodeName = childNode.getNodeName();
            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");
            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.info("Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils.readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));
                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='" + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");
                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }
                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName, propertyObjectValue);
                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }
                propertyValue = propertyObjectValue.toString();
                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '" + databaseObject.getName() + "' (" + objectClassName + "): [" + targetException.getClass().getName() + "] " + targetException.getMessage());
                }
                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty", new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '" + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n" + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n" + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }
    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n" + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }
    return databaseObject;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) PropertyDescriptor(java.beans.PropertyDescriptor) Element(org.w3c.dom.Element) BeanInfo(java.beans.BeanInfo) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) EngineException(com.twinsoft.convertigo.engine.EngineException) Method(java.lang.reflect.Method) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) EngineException(com.twinsoft.convertigo.engine.EngineException) DatabaseObjectNotFoundException(com.twinsoft.convertigo.engine.DatabaseObjectNotFoundException) VersionException(com.twinsoft.convertigo.engine.VersionException) UndefinedSymbolsException(com.twinsoft.convertigo.engine.UndefinedSymbolsException) ObjectWithSameNameException(com.twinsoft.convertigo.engine.ObjectWithSameNameException) InvocationTargetException(java.lang.reflect.InvocationTargetException) VersionException(com.twinsoft.convertigo.engine.VersionException)

Aggregations

EngineException (com.twinsoft.convertigo.engine.EngineException)426 IOException (java.io.IOException)155 File (java.io.File)117 Element (org.w3c.dom.Element)84 NodeList (org.w3c.dom.NodeList)64 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)62 Document (org.w3c.dom.Document)43 JSONObject (org.codehaus.jettison.json.JSONObject)41 Node (org.w3c.dom.Node)40 Project (com.twinsoft.convertigo.beans.core.Project)35 ArrayList (java.util.ArrayList)35 JSONException (org.codehaus.jettison.json.JSONException)33 Sequence (com.twinsoft.convertigo.beans.core.Sequence)31 RequestableVariable (com.twinsoft.convertigo.beans.variables.RequestableVariable)29 TreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject)27 DatabaseObjectTreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.DatabaseObjectTreeObject)25 Connector (com.twinsoft.convertigo.beans.core.Connector)24 HashMap (java.util.HashMap)23 Transaction (com.twinsoft.convertigo.beans.core.Transaction)21 ObjectWithSameNameException (com.twinsoft.convertigo.engine.ObjectWithSameNameException)20