Search in sources :

Example 61 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class RESTAdapter method setupHttpMap.

private void setupHttpMap(HTTPMap http, Binary content) throws UserException {
    // vg
    HashMap<String, String> headers_tr = new HashMap<String, String>();
    try {
        http.load(access);
    } catch (MappableException e) {
        throw new UserException(e.getMessage(), e);
    }
    StringBuilder fullUrl = new StringBuilder(url);
    for (int i = 0; i < parameters.size(); i++) {
        if (i == 0) {
            fullUrl.append("?");
        } else {
            fullUrl.append("&");
        }
        fullUrl.append("&");
        fullUrl.append(parameters.get(i));
    }
    for (Entry<String, String> e : headers.entrySet()) {
        http.setHeaderKey(e.getKey());
        http.setHeaderValue(e.getValue());
        headers_tr.put(e.getKey(), e.getValue());
    }
    http.setUrl(fullUrl.toString());
    http.setHeaderKey("Accept");
    http.setHeaderValue("application/json");
    http.setMethod(method);
    headers_tr.put("Accept", "application/json");
    // if (method.equals("POST") || method.equals("PUT")) { //here it sets the content if the method is only POST or PUT, should I change that?
    // http.setContent(content);
    // http.setContentType("application/json");
    // http.setContentLength(content.getLength());
    // }
    http.setContent(content);
    http.setContentType("application/json");
    http.setContentLength(content.getLength());
    http.trustAll();
    if (username != null && password != null) {
        // Use HTTP Basic auth - should only be used over HTTPS!
        String authString = username + ":" + password;
        byte[] bytes = authString.getBytes(StandardCharsets.UTF_8);
        String encoded = Base64.encode(bytes, 0, bytes.length, 0, "");
        http.setHeaderKey("Authorization");
        http.setHeaderValue("Basic " + encoded);
    }
    http.setReadTimeOut(readTimeOut);
    http.setConnectTimeOut(connectTimeOut);
    if (debug) {
        StringWriter buffer = new StringWriter();
        byte[] em = http.getContent().getData();
        String s_content = new String(em);
        // output all headers, request body and the curl command.
        buffer.append("=======================DEBUG MODE HTTP REQUEST===========================").append("\n");
        buffer.append(">>>>Method: " + http.getMethod()).append("\n");
        buffer.append(">>>>Request body: " + s_content).append("\n");
        buffer.append(">>>>Headers: ").append("\n");
        // curl builder
        String c_url = "curl -X";
        c_url += http.getMethod();
        c_url += " -H \'Content-type:application/json\' ";
        // accessing all headers
        for (Entry<String, String> e : headers_tr.entrySet()) {
            buffer.append(e.getKey() + " : " + e.getValue()).append("\n");
            c_url += "-H \'" + e.getKey() + ": " + e.getValue() + "\' ";
        }
        String no_enter_content = s_content.replace("\n", "").replace("\r", "");
        // http content is a binary
        c_url += "-d \'" + no_enter_content + "\' ";
        c_url += "\'" + http.getUrl() + "\' ";
        buffer.append(">>>>cURL command: " + c_url).append("\n");
        buffer.append("==========================================================================").append("\n");
        logger.info(buffer.toString());
    }
}
Also used : MappableException(com.dexels.navajo.script.api.MappableException) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) UserException(com.dexels.navajo.script.api.UserException)

Example 62 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SequencedInsertMap method setIdentityPlaceholder.

/**
 * Use the identity setter in correct position while setting parameters
 * for the insert statement.  This will put the identity column in the correct
 * place amongst the prepared statement parameteers
 * @param whatever (boolean value doesn't matter)
 * @throws UserException
 */
public void setIdentityPlaceholder(final boolean whatever) throws UserException {
    if ((this.databaseProduct == null || this.databaseProduct.equals(ORACLEPRODUCTNAME)) && this.sequenceName != null) {
        final MessageFormat formatter = new MessageFormat(SequencedInsertMap.SELSEQUENCESQL);
        final Object[] args = { this.sequenceName };
        final String qStr = formatter.format(args);
        try {
            this.createConnection();
            final PreparedStatement prepared = this.getConnection().prepareStatement(qStr);
            final ResultSet rs = prepared.executeQuery();
            if (rs.next()) {
                this.identity = Integer.valueOf(rs.getInt(1));
            }
            rs.close();
            prepared.close();
        } catch (SQLException sqle) {
            throw new UserException(-1, sqle.getMessage());
        }
        if (this.getDebug() && (this.identity != null)) {
            logger.debug(this.getClass() + ": " + this.databaseProduct + ": generated new identifier '" + this.identity + "' from sequence '" + this.sequenceName + "'");
        }
    } else {
        this.identity = null;
    }
    this.setParameter(this.identity);
}
Also used : MessageFormat(java.text.MessageFormat) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) UserException(com.dexels.navajo.script.api.UserException)

Example 63 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SequencedInsertMap method getIdentity.

// ------------------------------------------------------------ public getters
/**
 * @return the identity primary key value that was generated as an integer using
 * the appropriate technique based on the database vendor
 * @throws UserException
 */
public Integer getIdentity() throws UserException {
    if (this.identity == null && this.databaseProduct != null && this.databaseProduct.equals(SequencedInsertMap.HSQLPRODUCTNAME)) {
        try {
            this.createConnection();
            final PreparedStatement prepared = this.getConnection().prepareStatement(SequencedInsertMap.SELIDENTITYSQL);
            final ResultSet rs = prepared.executeQuery();
            if (rs.next()) {
                this.identity = Integer.valueOf(rs.getInt(1));
            }
            rs.close();
            prepared.close();
        } catch (SQLException sqle) {
            throw new UserException(-1, sqle.getMessage());
        }
        if (this.getDebug() && (this.identity != null)) {
            logger.debug(this.getClass() + ": " + this.databaseProduct + ": has generated new identifier '" + this.identity + "'");
        }
    }
    return (this.identity);
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) UserException(com.dexels.navajo.script.api.UserException)

Example 64 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class TslCompiler method messageNode.

@SuppressWarnings("unchecked")
public String messageNode(int ident, Element n, String className, String objectName, List<Dependency> deps, String tenant) throws MappingException, ClassNotFoundException, UserException, IOException, MetaCompileException, ParseException {
    StringBuilder result = new StringBuilder();
    String messageName = n.getAttribute("name");
    String condition = n.getAttribute("condition");
    String type = n.getAttribute("type");
    String mode = n.getAttribute("mode");
    String count = n.getAttribute("count");
    String startindex = n.getAttribute("start_index");
    String orderby = n.getAttribute("orderby");
    String extendsMsg = n.getAttribute("extends");
    String scopeMsg = n.getAttribute("scope");
    String method = n.getAttribute("method");
    String subType = n.getAttribute("subtype");
    type = (type == null) ? "" : type;
    mode = (mode == null) ? "" : mode;
    condition = (condition == null) ? "" : condition;
    count = (count == null || count.equals("")) ? "1" : count;
    method = (method == null) ? "" : method;
    subType = (subType == null) ? "" : subType;
    int startIndex = (startindex == null || startindex.equals("")) ? -1 : Integer.parseInt(startindex);
    boolean conditionClause = false;
    // If <message> node is conditional:
    if (!condition.equals("")) {
        conditionClause = true;
        result.append(printIdent(ident) + "if (Condition.evaluate(" + replaceQuotes(condition) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,access)) { \n");
        ident += 2;
    }
    Element nextElt = getNextElement(n);
    String ref = "";
    String filter = "";
    String startElement = "";
    String elementOffset = "";
    boolean isArrayAttr = false;
    boolean isSubMapped = false;
    boolean forceArray = false;
    boolean isIterator = false;
    boolean isMappedMessage = false;
    String mapPath = null;
    // Check if <message> is mapped to an object attribute:
    if (nextElt != null && nextElt.getNodeName().equals("map") && nextElt.getAttribute("ref") != null && !nextElt.getAttribute("ref").equals("")) {
        String refOriginal = null;
        isSubMapped = true;
        isMappedMessage = false;
        refOriginal = nextElt.getAttribute("ref");
        // Check if ref contains [ char, if it does, an array message of a selection property is mapped.
        if (refOriginal.length() > 0 && refOriginal.charAt(0) == '[') {
            refOriginal = refOriginal.replaceAll("\\[", "");
            refOriginal = refOriginal.replaceAll("\\]", "");
            isMappedMessage = true;
            isArrayAttr = true;
            type = Message.MSG_TYPE_ARRAY;
        } else if (refOriginal.indexOf('$') != -1) {
            // Remove leading $ (if present).
            refOriginal = refOriginal.replaceAll("\\$", "");
        }
        if (!isMappedMessage && refOriginal.indexOf('/') != -1) {
            ref = refOriginal.substring(refOriginal.lastIndexOf('/') + 1, refOriginal.length());
            mapPath = refOriginal.substring(0, refOriginal.lastIndexOf('/'));
        } else {
            ref = refOriginal;
        }
        forceArray = type.equals(Message.MSG_TYPE_ARRAY);
        filter = nextElt.getAttribute("filter");
        if (filter != null) {
            filter = filter.replace('\r', ' ');
            filter = filter.replace('\n', ' ');
        }
        startElement = nextElt.getAttribute("start_element");
        elementOffset = nextElt.getAttribute("element_offset");
        startElement = ((startElement == null || startElement.equals("")) ? "" : startElement);
        elementOffset = ((elementOffset == null || elementOffset.equals("")) ? "" : elementOffset);
        if (!isMappedMessage) {
            try {
                if (mapPath != null) {
                    contextClass = locateContextClass(mapPath, 0);
                    className = contextClass.getName();
                } else {
                    contextClass = Class.forName(className, false, loader);
                }
            } catch (Exception e) {
                throw new MappingException("Error line " + nextElt.getAttribute("linenr") + ": Could not find field: " + className + "/" + mapPath, e);
            }
            addDependency("dependentObjects.add( new JavaDependency( -1, \"" + className + "\"));\n", "JAVA" + className);
            if (DomainObjectMapper.class.isAssignableFrom(contextClass)) {
                isArrayAttr = forceArray;
                type = Message.MSG_TYPE_ARRAY;
            } else {
                try {
                    isArrayAttr = MappingUtils.isArrayAttribute(contextClass, ref);
                } catch (Exception e) {
                    throw new MappingException("Error line " + nextElt.getAttribute("linenr") + ": " + e.getMessage());
                }
                isIterator = MappingUtils.isIteratorAttribute(contextClass, ref);
                if (isIterator) {
                    isArrayAttr = true;
                }
                if (isArrayAttr) {
                    type = Message.MSG_TYPE_ARRAY;
                }
            }
        }
    }
    // Create the message(s). Multiple messages are created if count > 1.
    result.append(printIdent(ident) + "count = " + (count.equals("1") ? "1" : "((Integer) Expression.evaluate(\"" + count + "\", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,null,null,getEvaluationParams()).value).intValue()") + ";\n");
    String messageList = "messageList" + (messageListCounter++);
    result.append(printIdent(ident) + "Message [] " + messageList + " = null;\n");
    String orderbyExpression = ("".equals(orderby) ? "\"\"" : "(String) Expression.evaluate(" + replaceQuotes(orderby) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,null,null,getEvaluationParams()).value");
    if (n.getNodeName().equals("message")) {
        result.append(printIdent(ident) + messageList + " = MappingUtils.addMessage(access.getOutputDoc(), currentOutMsg, \"" + messageName + "\", \"\", count, \"" + type + "\", \"" + mode + "\", " + orderbyExpression + ");\n");
        result.append("");
    } else if (n.getNodeName().equals("loop")) {
        // create a message array of size 1 as placeholder.
        result.append(printIdent(ident) + messageList + " = new Message[1];\n");
        result.append("");
    } else {
        // must be parammessage.
        result.append(printIdent(ident) + messageList + " = MappingUtils.addMessage(access.getInDoc(), currentParamMsg, \"" + messageName + "\", \"\", count, \"" + type + "\", \"" + mode + "\");\n");
    }
    result.append(printIdent(ident) + "for (int messageCount" + (ident) + " = 0; messageCount" + (ident) + " < " + messageList + ".length; messageCount" + (ident) + "++) {\n if (!kill) {\n");
    if (n.getNodeName().equals("message")) {
        result.append(printIdent(ident + 2) + "outMsgStack.push(currentOutMsg);\n");
        result.append(printIdent(ident + 2) + "currentOutMsg = " + messageList + "[messageCount" + (ident) + "];\n");
        if (subType != null && !subType.equals("")) {
            result.append(printIdent(ident + 2) + "currentOutMsg.setSubType(\"" + subType + "\");\n");
            String[] subTypeElements = subType.split(",");
            for (String subTypeElement : subTypeElements) {
                if (subTypeElement.startsWith("interface=")) {
                    for (String iface : subTypeElement.replace("interface=", "").split(";")) {
                        String version = "0";
                        if (iface.indexOf(".") != -1) {
                            version = iface.substring(iface.indexOf(".") + 1, iface.indexOf("?") == -1 ? iface.length() : iface.indexOf("?"));
                        }
                        String replace = "." + version;
                        iface = iface.replace(replace, "");
                        String options = null;
                        if (iface.indexOf('?') > 0) {
                            options = iface.split("\\?")[1];
                            iface = iface.split("\\?")[0];
                        }
                        addDependency("dependentObjects.add( new ExtendDependency( Long.valueOf(\"" + ExtendDependency.getScriptTimeStamp(iface) + "\"), \"" + iface + "\"));\n", "EXTEND" + iface);
                        deps.add(new ExtendDependency(ExtendDependency.getScriptTimeStamp(iface), iface));
                    }
                }
            }
        }
        if (extendsMsg != null && !extendsMsg.equals("")) {
            result.append(printIdent(ident + 2) + "currentOutMsg.setExtends(\"" + extendsMsg + "\");\n");
            if (extendsMsg.startsWith("navajo://")) {
                String ext = extendsMsg.substring(9);
                String version = "0";
                if (ext.indexOf('.') != -1) {
                    version = ext.substring(ext.indexOf('.') + 1, ext.indexOf('?') == -1 ? ext.length() : ext.indexOf('?'));
                }
                String rep = "." + version;
                ext = ext.replace(rep, "");
                String[] superEntities = ext.split(",");
                for (String superEntity : superEntities) {
                    if (superEntity.indexOf('?') > 0) {
                        superEntity = superEntity.split("\\?")[0];
                    }
                    addDependency("dependentObjects.add( new ExtendDependency( Long.valueOf(\"" + ExtendDependency.getScriptTimeStamp(superEntity) + "\"), \"" + superEntity + "\"));\n", "EXTEND" + superEntity);
                    deps.add(new ExtendDependency(ExtendDependency.getScriptTimeStamp(superEntity), superEntity));
                }
            }
        }
        if (scopeMsg != null) {
            result.append(printIdent(ident + 2) + "currentOutMsg.setScope(\"" + scopeMsg + "\");\n");
        }
        result.append(printIdent(ident + 2) + "currentOutMsg.setMethod(\"" + method + "\");\n");
    } else if (n.getNodeName().equals("loop")) {
    // do nothing.
    } else {
        // must be parammessage.
        result.append(printIdent(ident + 2) + "paramMsgStack.push(currentParamMsg);\n");
        result.append(printIdent(ident + 2) + "currentParamMsg = " + messageList + "[messageCount" + (ident) + "];\n");
    }
    result.append(printIdent(ident + 2) + "access.setCurrentOutMessage(currentOutMsg);\n");
    if (isSubMapped && isMappedMessage) {
        boolean isParam = false;
        result.append(printIdent(ident + 2) + "// Map message(s) to message\n");
        String messageListName = "messages" + ident;
        result.append(printIdent(ident + 2) + "List " + messageListName + " = null;\n");
        result.append(printIdent(ident + 2) + "inSelectionRef = MappingUtils.isSelection(currentInMsg, access.getInDoc(), \"" + ref + "\");\n");
        result.append(printIdent(ident + 2) + "if (!inSelectionRef)\n");
        result.append(printIdent(ident + 4) + messageListName + " = MappingUtils.getMessageList(currentInMsg, access.getInDoc(), \"" + ref + "\", \"" + "" + "\", currentMap, currentParamMsg,access);\n");
        result.append(printIdent(ident + 2) + "else\n");
        result.append(printIdent(ident + 4) + messageListName + " = MappingUtils.getSelectedItems(currentInMsg, access.getInDoc(), \"" + ref + "\");\n");
        String loopCounterName = "j" + subObjectCounter++;
        variableClipboard.add("int " + loopCounterName + ";\n");
        result.append(printIdent(ident + 2) + "for (" + loopCounterName + " = 0; " + loopCounterName + " < " + messageListName + ".size(); " + loopCounterName + "++) {\n if (!kill){\n");
        // currentInMsg, inMsgStack
        ident += 4;
        result.append(printIdent(ident) + "inMsgStack.push(currentInMsg);\n");
        if (isParam) {
            result.append(printIdent(ident) + "paramMsgStack.push(currentParamMsg);\n");
        }
        result.append(printIdent(ident) + "inSelectionRefStack.push(new Boolean(inSelectionRef));\n");
        if (isParam) {
            result.append(printIdent(ident) + "if (!inSelectionRef)\n");
            result.append(printIdent(ident + 2) + "currentParamMsg = (Message) " + messageListName + ".get(" + loopCounterName + ");\n");
        }
        result.append(printIdent(ident) + "if (!inSelectionRef)\n");
        result.append(printIdent(ident + 2) + "currentInMsg = (Message) " + messageListName + ".get(" + loopCounterName + ");\n");
        result.append(printIdent(ident) + "else \n");
        // currentSelection.
        result.append(printIdent(ident + 2) + "currentSelection = (Selection) " + messageListName + ".get(" + loopCounterName + ");\n");
        // If filter is specified, evaluate filter first:
        if (!filter.equals("")) {
            result.append(printIdent(ident + 4) + "if (inSelectionRef || Condition.evaluate(" + replaceQuotes(filter) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,access)) {\n");
            ident += 2;
        }
        if (n.getNodeName().equals("message")) {
            result.append(printIdent(ident + 4) + "outMsgStack.push(currentOutMsg);\n");
            result.append(printIdent(ident + 4) + "currentOutMsg = MappingUtils.getMessageObject(\"" + MappingUtils.getBaseMessageName(messageName) + "\", currentOutMsg, true, access.getOutputDoc(), false, \"\", " + "-1" + ");\n");
            result.append(printIdent(ident + 4) + "access.setCurrentOutMessage(currentOutMsg);\n");
        } else if (n.getNodeName().equals("loop")) {
        // do nothing.
        } else {
            // parammessage.
            result.append(printIdent(ident + 4) + "paramMsgStack.push(currentParamMsg);\n");
            result.append(printIdent(ident + 4) + "currentParamMsg = MappingUtils.getMessageObject(\"" + MappingUtils.getBaseMessageName(messageName) + "\", currentParamMsg, true, access.getInDoc(), false, \"\", " + "-1" + ");\n");
        }
        result.append(printIdent(ident) + "try {\n");
        ident = ident + 2;
        NodeList children = nextElt.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                result.append(compile(ident + 4, children.item(i), className, objectName, deps, tenant));
            }
        }
        ident = ident - 2;
        result.append(printIdent(ident) + "} catch (Exception e" + ident + ") {\n");
        result.append(printIdent(ident) + "}\n");
        if (n.getNodeName().equals("message")) {
            result.append(printIdent(ident + 2) + "currentOutMsg = (Message) outMsgStack.pop();\n");
            result.append(printIdent(ident + 2) + "access.setCurrentOutMessage(currentOutMsg);\n");
        } else if (n.getNodeName().equals("loop")) {
        // do  nothing.
        } else {
            result.append(printIdent(ident) + "currentParamMsg = (Message) paramMsgStack.pop();\n");
        }
        if (filter != null && !filter.equals("")) {
            ident -= 2;
            result.append(printIdent(ident + 4) + "}\n");
        }
        result.append(printIdent(ident) + "currentInMsg = (Message) inMsgStack.pop();\n");
        if (isParam) {
            result.append(printIdent(ident) + "currentParamMsg = (Message) paramMsgStack.pop();\n");
        }
        result.append(printIdent(ident) + "inSelectionRef = ((Boolean) inSelectionRefStack.pop()).booleanValue();\n");
        result.append(printIdent(ident) + "currentSelection = null;\n");
        ident -= 4;
        result.append(printIdent(ident + 2) + "}\n} // FOR loop for " + loopCounterName + "\n");
    } else if (isSubMapped && isArrayAttr) {
        type = Message.MSG_TYPE_ARRAY_ELEMENT;
        String lengthName = "length" + (lengthCounter++);
        String mappableArrayName = "mappableObject" + (objectCounter++);
        boolean isDomainObjectMapper = false;
        contextClassStack.push(contextClass);
        String subClassName = null;
        NodeList children = nextElt.getChildNodes();
        try {
            subClassName = MappingUtils.getFieldType(contextClass, ref);
            contextClass = Class.forName(subClassName, false, loader);
        } catch (Exception e) {
            isDomainObjectMapper = contextClass.isAssignableFrom(DomainObjectMapper.class);
            subClassName = "com.dexels.navajo.mapping.bean.DomainObjectMapper";
            contextClass = com.dexels.navajo.mapping.bean.DomainObjectMapper.class;
            if (isDomainObjectMapper) {
                type = "java.lang.Object";
            } else {
                throw new MappingException("Could not find adapter: " + subClassName);
            }
        }
        addDependency("dependentObjects.add( new JavaDependency( -1, \"" + subClassName + "\"));\n", "JAVA" + subClassName);
        // Extract ref....
        if (mapPath == null) {
            if (isDomainObjectMapper) {
                result.append(printIdent(ident + 2) + "try {\n");
                result.append(printIdent(ident + 2) + mappableArrayName + " = com.dexels.navajo.mapping.bean.DomainObjectMapper.createArray( (Object []) ((" + className + ") currentMap.myObject).getDomainObjectAttribute(\"" + ref + "\", null) ) ;\n");
                result.append(printIdent(ident + 2) + "} catch (Exception e) {\n");
                result.append(printIdent(ident + 2) + "  String subtype = ((" + className + ") currentMap.myObject).getDomainObjectAttribute(\"" + ref + "\", null).getClass().getName();\n");
                result.append(printIdent(ident + 2) + "  throw new Exception(\" Could not cast " + ref + "(type = \" + subtype + \") to an array\");\n");
                result.append(printIdent(ident + 2) + "}\n");
            } else {
                result.append(printIdent(ident + 2) + mappableArrayName + " = ((" + className + ") currentMap.myObject).get" + ((ref.charAt(0) + "").toUpperCase() + ref.substring(1)) + "();\n");
            }
        } else {
            if (isDomainObjectMapper) {
                result.append(printIdent(ident + 2) + "try {\n");
                result.append(printIdent(ident + 2) + mappableArrayName + " = com.dexels.navajo.mapping.bean.DomainObjectMapper.createArray( (Object []) ((" + className + ") findMapByPath( \"" + mapPath + "\")).getDomainObjectAttribute(\"" + ref + "\", null) ) ;\n");
                result.append(printIdent(ident + 2) + "} catch (Exception e) {\n");
                result.append(printIdent(ident + 2) + "  String subtype = ((" + className + ") findMapByPath( \"" + mapPath + "\")).getDomainObjectAttribute(\"" + ref + "\", null).getClass().getName();\n");
                result.append(printIdent(ident + 2) + "  throw new Exception(\" Could not cast " + ref + "(type = \" + subtype + \") to an array\");\n");
                result.append(printIdent(ident + 2) + "}\n");
            } else {
                result.append(printIdent(ident + 2) + mappableArrayName + " = ((" + className + ") findMapByPath( \"" + mapPath + "\")).get" + ((ref.charAt(0) + "").toUpperCase() + ref.substring(1)) + "();\n");
            }
        }
        String mappableArrayDefinition = (isIterator ? "java.util.Iterator<" + subClassName + "> " + mappableArrayName + " = null;\n" : "Object [] " + mappableArrayName + " = null;\n");
        variableClipboard.add(mappableArrayDefinition);
        if (!isIterator) {
            result.append(printIdent(ident + 2) + "int " + lengthName + " = " + "(" + mappableArrayName + " == null ? 0 : " + mappableArrayName + ".length);\n");
        }
        String startIndexVar = "startIndex" + (startIndexCounter++);
        result.append(printIdent(ident + 2) + "int " + startIndexVar + " = " + startIndex + ";\n");
        String startElementVar = "startWith" + (startElementCounter);
        String offsetElementVar = "offset" + (startElementCounter++);
        // Use a different than 0 as start for for loop.
        // result.append(printIdent(ident) + "count = " +
        result.append(printIdent(ident + 2) + "int " + startElementVar + " = " + (startElement.equals("") ? "0" : "((Integer) Expression.evaluate(\"" + startElement + "\", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,null,null,getEvaluationParams()).value).intValue()") + ";\n");
        result.append(printIdent(ident + 2) + "int " + offsetElementVar + " = " + (elementOffset.equals("") ? "1" : "((Integer) Expression.evaluate(\"" + elementOffset + "\", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,null,null,getEvaluationParams()).value).intValue()") + ";\n");
        if (!isIterator) {
            result.append(printIdent(ident + 2) + "for (int i" + (ident + 2) + " = " + startElementVar + "; i" + (ident + 2) + " < " + lengthName + "; i" + (ident + 2) + " = i" + (ident + 2) + "+" + offsetElementVar + ") {\n if (!kill) {\n");
        } else {
            result.append(printIdent(ident + 2) + "while (" + mappableArrayName + ".hasNext() ) {\n if (!kill) {\n");
        }
        result.append(printIdent(ident + 4) + "treeNodeStack.push(currentMap);\n");
        if (!isIterator) {
            result.append(printIdent(ident + 4) + "currentMap = new MappableTreeNode(access, currentMap, " + mappableArrayName + "[i" + (ident + 2) + "], true);\n");
        } else {
            result.append(printIdent(ident + 4) + "currentMap = new MappableTreeNode(access, currentMap, " + mappableArrayName + ".next(), true);\n");
        }
        result.append(printIdent(ident + 4) + "currentMap.setNavajoLineNr(" + n.getAttribute("linenr") + ");\n");
        // If filter is specified, evaluate filter first:
        if (filter != null && !filter.equals("")) {
            result.append(printIdent(ident + 4) + "if (Condition.evaluate(" + replaceQuotes(filter) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,access)) {\n");
            ident += 2;
        }
        if (n.getNodeName().equals("message")) {
            result.append(printIdent(ident + 4) + "outMsgStack.push(currentOutMsg);\n");
            result.append(printIdent(ident + 4) + "currentOutMsg = MappingUtils.getMessageObject(\"" + MappingUtils.getBaseMessageName(messageName) + "\", currentOutMsg, true, access.getOutputDoc(), false, \"\", " + ((startIndex == -1) ? "-1" : startIndexVar + "++") + ");\n");
            result.append(printIdent(ident + 4) + "access.setCurrentOutMessage(currentOutMsg);\n");
        } else if (n.getNodeName().equals("loop")) {
        // do nothing.
        } else {
            // parammessage.
            result.append(printIdent(ident + 4) + "paramMsgStack.push(currentParamMsg);\n");
            result.append(printIdent(ident + 4) + "currentParamMsg = MappingUtils.getMessageObject(\"" + MappingUtils.getBaseMessageName(messageName) + "\", currentParamMsg, true, access.getInDoc(), false, \"\", " + ((startIndex == -1) ? "-1" : startIndexVar + "++") + ");\n");
        }
        result.append(printIdent(ident) + "if ( currentMap.myObject instanceof Mappable ) {  ((Mappable) currentMap.myObject).load(access);}\n");
        String subObjectName = "mappableObject" + (objectCounter++);
        result.append(printIdent(ident + 4) + subObjectName + " = (" + subClassName + ") currentMap.myObject;\n");
        String objectDefinition = subClassName + " " + subObjectName + " = null;\n";
        variableClipboard.add(objectDefinition);
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                result.append(compile(ident + 4, children.item(i), subClassName, subObjectName, deps, tenant));
            }
        }
        contextClass = contextClassStack.pop();
        result.append(printIdent(ident + 2) + "MappingUtils.callStoreMethod(currentMap.myObject);\n");
        if (n.getNodeName().equals("message")) {
            result.append(printIdent(ident + 2) + "currentOutMsg = (Message) outMsgStack.pop();\n");
            result.append(printIdent(ident + 2) + "access.setCurrentOutMessage(currentOutMsg);\n");
        } else if (n.getNodeName().equals("loop")) {
        // do nothing.
        } else {
            result.append(printIdent(ident) + "currentParamMsg = (Message) paramMsgStack.pop();\n");
        }
        if (filter != null && !filter.equals("")) {
            ident -= 2;
            result.append(printIdent(ident + 4) + "}\n");
        }
        result.append(printIdent(ident + 2) + "currentMap.setEndtime();\n" + "currentMap = (MappableTreeNode) treeNodeStack.pop();\n");
        result.append(printIdent(ident + 2) + "}\n} // EOF Array map result from contextMap \n");
    } else if (isSubMapped) {
        if (n.getNodeName().equals("loop")) {
            throw new MappingException("Can only loop over arrays");
        }
        if (mapPath == null) {
            result.append(printIdent(ident + 2) + "treeNodeStack.push(currentMap);\n");
            if (className.equals("com.dexels.navajo.mapping.bean.DomainObjectMapper")) {
                result.append(printIdent(ident + 2) + "currentMap = new MappableTreeNode(access, currentMap, new com.dexels.navajo.mapping.bean.DomainObjectMapper( ((" + className + ") currentMap.myObject).getDomainObjectAttribute(\"" + ref + "\", null) ), false);\n");
            } else {
                result.append(printIdent(ident + 2) + "currentMap = new MappableTreeNode(access, currentMap, ((" + className + ") currentMap.myObject).get" + ((ref.charAt(0) + "").toUpperCase() + ref.substring(1)) + "(), false);\n");
            }
            result.append(printIdent(ident + 4) + "currentMap.setNavajoLineNr(" + n.getAttribute("linenr") + ");\n");
        } else {
            String localObjectName = "mappableObject" + (objectCounter++);
            result.append(printIdent(ident + 2) + "Object " + localObjectName + " = findMapByPath( \"" + mapPath + "\");\n");
            result.append(printIdent(ident + 2) + "treeNodeStack.push(currentMap);\n");
            if (className.equals("com.dexels.navajo.mapping.bean.DomainObjectMapper")) {
                result.append(printIdent(ident + 2) + "currentMap = new MappableTreeNode(access, currentMap,new com.dexels.navajo.mapping.bean.DomainObjectMapper( ((" + className + ")" + localObjectName + ").getDomainObjectAttribute(\"" + ref + "\", null) ), false);\n");
            } else {
                result.append(printIdent(ident + 2) + "currentMap = new MappableTreeNode(access, currentMap, ((" + className + ")" + localObjectName + ").get" + ((ref.charAt(0) + "").toUpperCase() + ref.substring(1)) + "(), false);\n");
            }
            result.append(printIdent(ident + 4) + "currentMap.setNavajoLineNr(" + n.getAttribute("linenr") + ");\n");
        }
        result.append(printIdent(ident + 2) + "if (currentMap.myObject != null) {\n");
        result.append(printIdent(ident) + "if ( currentMap.myObject instanceof Mappable ) {  ((Mappable) currentMap.myObject).load(access);}\n");
        contextClassStack.push(contextClass);
        String subClassName = null;
        if (DomainObjectMapper.class.isAssignableFrom(contextClass)) {
            subClassName = "com.dexels.navajo.mapping.bean.DomainObjectMapper";
            contextClass = DomainObjectMapper.class;
        } else {
            subClassName = MappingUtils.getFieldType(contextClass, ref);
            contextClass = null;
            try {
                contextClass = Class.forName(subClassName, false, loader);
            } catch (Exception e) {
                throw new MappingException("Could not find adapter " + subClassName);
            }
        }
        addDependency("dependentObjects.add( new JavaDependency( -1, \"" + subClassName + "\"));\n", "JAVA" + subClassName);
        String subObjectName = "mappableObject" + (objectCounter++);
        result.append(printIdent(ident + 4) + subObjectName + " = (" + subClassName + ") currentMap.myObject;\n");
        String objectDefinition = subClassName + " " + subObjectName + " = null;\n";
        variableClipboard.add(objectDefinition);
        NodeList children = nextElt.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            result.append(compile(ident + 4, children.item(i), subClassName, subObjectName, deps, tenant));
        }
        contextClass = contextClassStack.pop();
        result.append(printIdent(ident + 2) + "}\n");
        result.append(printIdent(ident + 2) + "currentMap.setEndtime();\n" + "MappingUtils.callStoreMethod(currentMap.myObject);\n" + "currentMap = (MappableTreeNode) treeNodeStack.pop();\n");
    } else {
        if (n.getNodeName().equals("loop")) {
            throw new MappingException("Can only loop over arrays");
        }
        NodeList children = n.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            result.append(compile(ident + 2, children.item(i), className, objectName, deps, tenant));
        }
    }
    if (n.getNodeName().equals("message")) {
        result.append(printIdent(ident) + "currentOutMsg = (Message) outMsgStack.pop();\n");
        result.append(printIdent(ident) + "access.setCurrentOutMessage(currentOutMsg);\n");
    } else if (n.getNodeName().equals("loop")) {
    // do nothing.
    } else {
        result.append(printIdent(ident) + "currentParamMsg = (Message) paramMsgStack.pop();\n");
    }
    result.append(printIdent(ident) + "}\n } // EOF messageList for \n");
    if (conditionClause) {
        ident -= 2;
        result.append(printIdent(ident) + "} // EOF message condition \n");
    }
    return result.toString();
}
Also used : ExtendDependency(com.dexels.navajo.mapping.compiler.meta.ExtendDependency) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) DomainObjectMapper(com.dexels.navajo.mapping.bean.DomainObjectMapper) UserException(com.dexels.navajo.script.api.UserException) TransformerException(javax.xml.transform.TransformerException) MappingException(com.dexels.navajo.script.api.MappingException) TMLExpressionException(com.dexels.navajo.expression.api.TMLExpressionException) ParseException(com.dexels.navajo.parser.compiled.ParseException) KeywordException(com.dexels.navajo.mapping.compiler.meta.KeywordException) MetaCompileException(com.dexels.navajo.mapping.compiler.meta.MetaCompileException) IOException(java.io.IOException) SystemException(com.dexels.navajo.script.api.SystemException) CompilationException(com.dexels.navajo.script.api.CompilationException) MappingException(com.dexels.navajo.script.api.MappingException)

Example 65 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class TslCompiler method getExpressionValue.

/**
 * Extract the value from an expression node.
 *
 * @param exprElmnt
 * @return
 * @throws Exception
 */
private Object[] getExpressionValue(Element exprElmnt, Boolean isStringOperand) throws UserException {
    String value = null;
    isStringOperand = Boolean.FALSE;
    Element valueElt = (Element) XMLutils.findNode(exprElmnt, "value");
    if (valueElt == null) {
        value = XMLutils.XMLUnescape(exprElmnt.getAttribute("value"));
    } else {
        value = getCDATAContent(valueElt);
        if (value == null) {
            Node child = valueElt.getFirstChild();
            if (child == null) {
                logger.error("Could not child in element: {}", valueElt.getNodeName());
                throw new UserException("Invalid script: " + valueElt.getNodeName());
            }
            value = child.getNodeValue();
        }
    }
    // Check if operand is given as text node between <expression> tags.
    if (value == null || value.equals("")) {
        Node child = exprElmnt.getFirstChild();
        String cdata = getCDATAContent(exprElmnt);
        if (cdata != null) {
            isStringOperand = Boolean.TRUE;
            value = cdata;
        } else if (child != null) {
            isStringOperand = Boolean.TRUE;
            value = child.getNodeValue();
        } else {
            throw new UserException("Error line " + exprElmnt.getAttribute("linenr") + ":" + exprElmnt.getAttribute("startoffset") + " @" + (exprElmnt.getParentNode() + "/" + exprElmnt) + ": <expression> node should either contain a value attribute or a text child node: >" + value + "<");
        }
    } else {
        value = value.trim();
        value = value.replaceAll("\n", " ");
        value = value.replaceAll("\r", " ");
        value = XMLutils.XMLUnescape(value);
    }
    return new Object[] { removeNewLines(value), isStringOperand };
}
Also used : Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) UserException(com.dexels.navajo.script.api.UserException)

Aggregations

UserException (com.dexels.navajo.script.api.UserException)113 MappableException (com.dexels.navajo.script.api.MappableException)54 IOException (java.io.IOException)33 NavajoException (com.dexels.navajo.document.NavajoException)25 Message (com.dexels.navajo.document.Message)22 SQLException (java.sql.SQLException)19 SystemException (com.dexels.navajo.script.api.SystemException)18 Binary (com.dexels.navajo.document.types.Binary)14 ConditionErrorException (com.dexels.navajo.server.ConditionErrorException)13 Property (com.dexels.navajo.document.Property)12 ArrayList (java.util.ArrayList)12 Navajo (com.dexels.navajo.document.Navajo)11 AuthorizationException (com.dexels.navajo.script.api.AuthorizationException)11 ResultSet (java.sql.ResultSet)11 MappingException (com.dexels.navajo.script.api.MappingException)10 ResultSetMetaData (java.sql.ResultSetMetaData)9 Element (org.w3c.dom.Element)8 CompilationException (com.dexels.navajo.script.api.CompilationException)7 File (java.io.File)7 NodeList (org.w3c.dom.NodeList)7