Search in sources :

Example 1 with ConnectionException

use of com.twinsoft.convertigo.beans.connectors.ConnectionException in project convertigo by convertigo.

the class JavelinTransaction method applyUserRequest.

public void applyUserRequest(iJavelin javelin) throws EngineException {
    boolean fieldIsAutoEnter = false;
    String currentField = "null";
    sessionMustBeDestroyed = false;
    String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
    try {
        Engine.logContext.debug("(JavelinTransaction) Applying user request");
        // We apply the XML command to the Javelin object.
        if (context.inputDocument == null) {
            // Nothing to do: the user request is not relevant for this screen.
            Engine.logContext.debug("(JavelinTransaction) Request handling aborted: no user request");
            return;
        }
        NodeList nodeList;
        Node node, nodeAttribute;
        NamedNodeMap nodeAttributes;
        long documentSignature = 0;
        nodeList = context.inputDocument.getElementsByTagName("document-signature");
        if (nodeList.getLength() > 0) {
            node = nodeList.item(0);
            String value = ((Element) node).getAttribute("value");
            try {
                documentSignature = Long.parseLong(value);
            } catch (NumberFormatException e) {
                Engine.logContext.debug("(JavelinTransaction) Wrong document signature: " + value);
            }
        }
        Engine.logContext.debug("(JavelinTransaction) Received document signature:      " + documentSignature);
        Engine.logContext.debug("(JavelinTransaction) Last received document signature: " + context.documentSignatureReceived);
        Engine.logContext.debug("(JavelinTransaction) Last sent document signature:     " + context.documentSignatureSent);
        if (documentSignature < context.documentSignatureReceived) {
            // The user is trying to replay a previous request (probably by using the back
            // functionality from the browser...): this is forbidden.
            Engine.logContext.warn("(JavelinTransaction) Request handling aborted: \"back\" protection");
            context.outputDocument.getDocumentElement().setAttribute("back-attempt", "true");
            return;
        }
        // Json string of modified fields
        String modifiedFields = "";
        nodeList = context.inputDocument.getElementsByTagName("modified-fields");
        if (nodeList.getLength() > 0) {
            node = nodeList.item(0);
            nodeAttributes = node.getAttributes();
            nodeAttribute = nodeAttributes.getNamedItem("value");
            modifiedFields = nodeAttribute.getNodeValue();
        }
        nodeList = context.inputDocument.getElementsByTagName("current-field");
        if (nodeList.getLength() > 0) {
            node = nodeList.item(0);
            nodeAttributes = node.getAttributes();
            nodeAttribute = nodeAttributes.getNamedItem("name");
            currentField = nodeAttribute.getNodeValue();
        }
        nodeList = context.inputDocument.getElementsByTagName("action");
        if (nodeList.getLength() == 1) {
            Block block;
            String action, blockName;
            node = nodeList.item(0);
            nodeAttributes = node.getAttributes();
            nodeAttribute = nodeAttributes.getNamedItem("name");
            action = nodeAttribute.getNodeValue();
            action = action.trim();
            // Refreshing current XML document
            if (action.equalsIgnoreCase("convertigo_refresh")) {
                Engine.logContext.debug("(JavelinTransaction) Refresh required");
            } else if (action.startsWith("convertigo_bench")) {
                long sleepTime = 1000;
                if (action.length() > "convertigo_bench".length()) {
                    String s = action.substring(16);
                    try {
                        sleepTime = Long.parseLong(s);
                    } catch (NumberFormatException e) {
                    // Ignore
                    }
                }
                Engine.logContext.debug("(JavelinTransaction) Bench option: sleep during " + sleepTime + " second(s)");
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                }
            } else // Destroy the current session
            if (action.equalsIgnoreCase("convertigo_destroy_session")) {
                Engine.logContext.debug("(JavelinTransaction) Requiring destroy of the current session");
                sessionMustBeDestroyed = true;
            } else // Reconnecting
            if (action.equalsIgnoreCase("convertigo_reconnect")) {
                Engine.logContext.debug("(JavelinTransaction) Reconnection required");
                javelin.disconnect();
                if (javelin.isConnected()) {
                    throw new ConnectionException("Unable to disconnect the session! See the emulator logs for more details...");
                }
                javelin.connect(timeoutForConnect);
                if (!javelin.isConnected()) {
                    throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
                }
                javelin.waitForDataStable(timeoutForDataStable, dataStableThreshold);
            } else {
                if (javelin.getTerminalClass().equals(iJavelin.SNA) || javelin.getTerminalClass().equals(iJavelin.AS400)) {
                    // Special case for IBM emulators: before applying an action,
                    // do a RESET action on the emulator to clear a possible
                    // previous X System Status.
                    javelin.doAction("KEY_RESET");
                    Engine.logContext.debug("(JavelinTransaction) Action performed on the Javelin object: 'KEY_RESET'");
                }
                // previously sent document signature
                if ((documentSignature == 0) || (documentSignature == context.documentSignatureSent)) {
                    // Searching for fields to push into the Javelin object.
                    nodeList = context.inputDocument.getElementsByTagName("field");
                    int len = nodeList.getLength();
                    String value;
                    // sort fields by line and column in the screen
                    Element elem;
                    ArrayList<ComparableFieldElement> liste = new ArrayList<ComparableFieldElement>();
                    for (int i = 0; i < len; i++) {
                        elem = (Element) nodeList.item(i);
                        liste.add(new ComparableFieldElement(elem));
                    }
                    Engine.logContext.debug("(JavelinTransaction) Fields from inputDocument set in a list.");
                    Collections.sort(liste);
                    Engine.logContext.debug("(JavelinTransaction) Fields from inputDocument sorted.");
                    Iterator<ComparableFieldElement> it = liste.iterator();
                    while (it.hasNext()) {
                        ComparableFieldElement cfElem = it.next();
                        elem = cfElem.getFieldElement();
                        value = elem.getAttribute("value");
                        if (javelin.getTerminalClass().equals(iJavelin.VDX)) {
                            javelin.send(value);
                            Engine.logContext.debug("(JavelinTransaction) Characters sent to the Javelin object: '" + value + "'");
                        } else if (javelin.getTerminalClass().equals(iJavelin.VT)) {
                            javelin.send(value);
                            Engine.logContext.debug("(JavelinTransaction) VT Characters sent to the Javelin object: '" + value + "'");
                        } else {
                            // Trying to find the requested block
                            blockName = elem.getAttribute("name");
                            Engine.logContext.debug("(JavelinTransaction) Analyzing field \"" + blockName + "\"");
                            block = context.previousFields.get(blockName);
                            int column = 0;
                            int line = 0;
                            try {
                                int index1 = blockName.indexOf("_c");
                                int index2 = blockName.indexOf("_l");
                                column = Integer.parseInt(blockName.substring(index1 + 2, index2));
                                line = Integer.parseInt(blockName.substring(index2 + 2));
                                Engine.logContext.debug("(JavelinTransaction) Cursor position retrieved from the field name \"" + blockName + "\"column: =" + column + " line=" + line);
                            } catch (Exception e) {
                                Engine.logContext.error("Unable to retrieve the cursor position from the field name \"" + blockName + "\"! Skipping it.", e);
                                continue;
                            }
                            if (isFieldValueDifferent(blockName, value, modifiedFields)) {
                                javelin.moveCursor(column, line);
                                Engine.logContext.debug("(JavelinTransaction) Cursor moved to column:" + column + ", line: " + line);
                                // Delete the previous field value
                                if (javelin.getTerminalClass().equals(iJavelin.SNA) || javelin.getTerminalClass().equals(iJavelin.AS400)) {
                                    javelin.doAction("KEY_ERASEEOF");
                                } else if (javelin.getTerminalClass().equals(iJavelin.DKU)) {
                                    javelin.doAction("ERAEOL");
                                }
                                if (value.length() != 0) {
                                    // Test if the field is numeric only
                                    if ((block != null) && (block.attribute & iJavelin.AT_FIELD_NUMERIC) > 0) {
                                        value = removeAllNonNumericChars(value);
                                        Engine.logContext.warn("(JavelinTransaction) Numeric field. Non numeric chars may have been discarded [" + value + "]");
                                    }
                                    // Test if the field is autoenter and that its size equals to the field size
                                    try {
                                        if ((block != null) && (block.attribute & iJavelin.AT_AUTO_ENTER) > 0) {
                                            if (value.length() == Integer.parseInt(block.getOptionalAttribute("size"))) {
                                                fieldIsAutoEnter = true;
                                                Engine.logContext.debug("(JavelinTransaction) Field is auto enter, doAction will not be executed [" + value + "]");
                                            }
                                        }
                                    } catch (Exception e) {
                                        Engine.logContext.warn("(JavelinTransaction) Field is auto enter, but no size attribute present! [" + value + "]");
                                    }
                                    javelin.send(value);
                                    Engine.logContext.debug("(JavelinTransaction) Characters sent to the emulator on (" + column + ", " + line + "): '" + value + "'");
                                }
                                // Update the block history if it is a non empty field
                                if ((block != null) && (value.length() != 0)) {
                                    String historyBlock = block.getOptionalAttribute("history");
                                    if ((block.type.equals("field")) && (historyBlock != null) && (historyBlock.equals("true")) && (value.length() > 0)) {
                                        // TODO: set the tagname list to remember
                                        List<String> values = GenericUtils.cast(context.httpSession.getAttribute(block.tagName));
                                        if (values == null) {
                                            values = new ArrayList<String>(10);
                                        }
                                        if (!values.contains(value)) {
                                            values.add(value);
                                            context.httpSession.setAttribute(block.tagName, values);
                                            Engine.logContext.debug("(JavelinTransaction) History: block '" + block.tagName + "' += '" + value + "'");
                                        }
                                    }
                                }
                                if (action.equalsIgnoreCase("KEY_FIELDPLUS")) {
                                    Engine.logContext.debug("(JavelinTransaction) Action is KEY_FIELDPLUS while sending " + blockName + " field");
                                    if (blockName.equalsIgnoreCase(currentField)) {
                                        // The field we are handling is the current field.
                                        // Do now the FIELD_PLUS action.
                                        Engine.logContext.debug("(JavelinTransaction) We just sent the current field, and action is KEY_FIELDPLUS");
                                        javelin.doAction("KEY_FIELDPLUS");
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    if (currentField != null) {
                        block = (Block) context.previousFields.get(currentField);
                        // we did not find the field in the previous fields : assume the current field is set on a static position. This is
                        // legal as some applications rely on the cursor position event on static fields
                        int index1 = currentField.indexOf("_c");
                        int index2 = currentField.indexOf("_l");
                        if ((index1 != -1) && (index2 != -1)) {
                            int column = Integer.parseInt(currentField.substring(index1 + 2, index2));
                            int line = Integer.parseInt(currentField.substring(index2 + 2));
                            Engine.logContext.debug("(JavelinTransaction) Move cursor on Current field : Cursor position retrieved from the field name \"" + currentField + "\"column=" + column + " line=" + line);
                            boolean moveDone = false;
                            // if current field is numeric, put the cursor at the end of the field
                            // searching field index
                            int nbFields = javelin.getNumberOfFields();
                            int i = 0;
                            boolean found = false;
                            while (i < nbFields && !found) {
                                if (javelin.getFieldColumn(i) == column && javelin.getFieldLine(i) == line)
                                    found = true;
                                else
                                    i++;
                            }
                            if (found) {
                                // field index found
                                if ((javelin.getFieldAttribute(i) & iJavelin.AT_FIELD_NUMERIC) > 0) {
                                    // numeric field
                                    // put the cursor at the end of the field
                                    column = column + javelin.getFieldLength(i) - 1;
                                    Engine.logContext.debug("(JavelinTransaction) Cursor is in a numeric field '" + currentField + "' ; moving cursor to the end of the field '" + currentField + "' at (" + column + ", " + line + ")");
                                    javelin.moveCursor(column, line);
                                    Engine.logContext.debug("(JavelinTransaction) Moved cursor to (" + javelin.getCurrentColumn() + ", " + javelin.getCurrentLine() + ")");
                                    moveDone = true;
                                }
                            }
                            if (!moveDone) {
                                // and if the action is KEY_NPTUI or not
                                if (javelin.getCurrentColumn() == column && javelin.getCurrentLine() == line && !action.equals("KEY_NPTUI")) {
                                    Engine.logContext.debug("(JavelinTransaction) Cursor has not moved from field '" + currentField + "' at (" + column + ", " + line + ") and action is not \"KEY_NPTUI\" ; don't move cursor");
                                } else {
                                    Engine.logContext.debug("(JavelinTransaction) Cursor has moved from field '" + currentField + "' or action is \"KEY_NPTUI\" ; moving cursor to field '" + currentField + "' at (" + column + ", " + line + ")");
                                    javelin.moveCursor(column, line);
                                    Engine.logContext.debug("(JavelinTransaction) Moved cursor to (" + javelin.getCurrentColumn() + ", " + javelin.getCurrentLine() + ")");
                                }
                            }
                        }
                    }
                } else {
                    Engine.logContext.warn("(JavelinTransaction) Cancel applying fields because of document signature check");
                }
                // Storing last document signature received
                context.documentSignatureReceived = documentSignature;
                // Executing action
                if (!fieldIsAutoEnter) {
                    // Execute the action only if there were no AutoEnter fields...
                    if (action.equalsIgnoreCase("KEY_NPTUI")) {
                        // NPTUI action just wait as the moveCursor already triggered the HOST COMM. we only have
                        // to wait here
                        boolean bTimedOut = javelin.waitForDataStable(timeoutForDataStable, dataStableThreshold);
                        Engine.logContext.debug("(JavelinTransaction) Action performed on the Javelin object: '" + action + "'waitForDataStable returned :" + bTimedOut);
                    } else if (action.length() != 0) {
                        javelin.doAction(action);
                        Engine.logContext.debug("(JavelinTransaction) Action performed on the Javelin object: '" + action + "'");
                        if (!(action.equalsIgnoreCase("KEY_FIELDPLUS") || action.equalsIgnoreCase("KEY_FIELDMINUS"))) {
                            boolean bTimedOut = javelin.waitForDataStable(timeoutForDataStable, dataStableThreshold);
                            Engine.logContext.debug("(JavelinTransaction) WaitForDataStable() returned " + bTimedOut);
                        } else
                            Engine.logContext.debug("(JavelinTransaction) Action was KEY_FIELDPLUS or KEY_FIELDMINUS, do not perform waitForDataStable");
                    } else {
                        Engine.logContext.debug("(JavelinTransaction) Empty action string => action aborted");
                    }
                } else {
                    boolean bTimedOut = javelin.waitForDataStable(timeoutForDataStable, dataStableThreshold);
                    Engine.logContext.debug("(JavelinTransaction) WaitForDataStable() returned " + bTimedOut);
                }
            }
        }
    } catch (Exception e) {
        Engine.logContext.error("Request handling aborted because of internal error.", e);
    } finally {
        context.statistics.stop(t);
    }
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) NoSuchElementException(java.util.NoSuchElementException) ConnectionException(com.twinsoft.convertigo.beans.connectors.ConnectionException) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) EngineException(com.twinsoft.convertigo.engine.EngineException) Iterator(java.util.Iterator) Block(com.twinsoft.convertigo.beans.core.Block) ConnectionException(com.twinsoft.convertigo.beans.connectors.ConnectionException)

Example 2 with ConnectionException

use of com.twinsoft.convertigo.beans.connectors.ConnectionException in project convertigo by convertigo.

the class HttpClient method doExecuteMethod.

private int doExecuteMethod(HttpMethod method, HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle) throws ConnectionException, URIException, MalformedURLException {
    int statuscode = -1;
    HostConfiguration hostConfiguration = connector.hostConfiguration;
    // Tells the method to automatically handle authentication.
    method.setDoAuthentication(true);
    // Tells the method to automatically handle redirection.
    method.setFollowRedirects(false);
    try {
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logEngine.isTraceEnabled())
                Engine.logEngine.trace("(HttpClient) request cookies:" + Arrays.asList(cookies).toString());
        }
        Engine.logEngine.debug("(HttpClient) executing method...");
        statuscode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        Engine.logEngine.debug("(HttpClient) end of method successfull");
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logEngine.isTraceEnabled())
                Engine.logEngine.trace("(HttpClient) response cookies:" + Arrays.asList(cookies).toString());
        }
    } catch (IOException e) {
        try {
            Engine.logEngine.warn("(HttpClient) connection error to " + resourceUrl + ": " + e.getMessage() + "; retrying method");
            statuscode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
            Engine.logEngine.debug("(HttpClient) end of method successfull");
        } catch (IOException ee) {
            throw new ConnectionException("Connection error to " + resourceUrl, ee);
        }
    }
    return statuscode;
}
Also used : Cookie(org.apache.commons.httpclient.Cookie) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) IOException(java.io.IOException) ConnectionException(com.twinsoft.convertigo.beans.connectors.ConnectionException)

Aggregations

ConnectionException (com.twinsoft.convertigo.beans.connectors.ConnectionException)2 Block (com.twinsoft.convertigo.beans.core.Block)1 EngineException (com.twinsoft.convertigo.engine.EngineException)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 NoSuchElementException (java.util.NoSuchElementException)1 Cookie (org.apache.commons.httpclient.Cookie)1 HostConfiguration (org.apache.commons.httpclient.HostConfiguration)1 EvaluatorException (org.mozilla.javascript.EvaluatorException)1 JavaScriptException (org.mozilla.javascript.JavaScriptException)1 Element (org.w3c.dom.Element)1 NamedNodeMap (org.w3c.dom.NamedNodeMap)1 Node (org.w3c.dom.Node)1 NodeList (org.w3c.dom.NodeList)1