Search in sources :

Example 66 with UserException

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

the class TslCompiler method fieldNode.

@SuppressWarnings("unchecked")
public String fieldNode(int ident, Element n, String className, String objectName, List<Dependency> dependencies, String tenant) throws UserException, MappingException, ClassNotFoundException, KeywordException, IOException, MetaCompileException, ParseException {
    StringBuilder result = new StringBuilder();
    String attributeOriginal = n.getAttribute("name");
    String condition = n.getAttribute("condition");
    String attribute = null;
    String mapPath = null;
    if (attributeOriginal.indexOf('/') != -1) {
        attribute = attributeOriginal.substring(attributeOriginal.lastIndexOf('/') + 1, attributeOriginal.length());
        mapPath = attributeOriginal.substring(0, attributeOriginal.lastIndexOf('/'));
    } else {
        attribute = attributeOriginal;
    }
    if (attribute == null || attribute.equals(""))
        throw new UserException("Name attribute is required for field tags");
    condition = (condition == null) ? "" : condition;
    String totalMethodName = "set" + (attribute.charAt(0) + "").toUpperCase() + attribute.substring(1, attribute.length());
    String methodName = null;
    if (totalMethodName.indexOf('/') != -1) {
        methodName = totalMethodName.substring(totalMethodName.lastIndexOf('/') + 1, totalMethodName.length());
    } else {
        methodName = totalMethodName;
    }
    NodeList children = n.getChildNodes();
    if (!condition.equals("")) {
        result.append(printIdent(ident) + "if (Condition.evaluate(" + replaceQuotes(condition) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,access)) { \n");
    } else {
        result.append(printIdent(ident) + "if (true) {\n");
    }
    // Expression nodes.
    boolean isMapped = false;
    Element mapNode = null;
    int exprCount = countNodes(children, "expression");
    List<String> exprValues = new ArrayList<>();
    for (int i = 0; i < children.getLength(); i++) {
        // Has condition
        if (children.item(i).getNodeName().equals("expression")) {
            result.append(expressionNode(ident + 2, (Element) children.item(i), --exprCount, className, objectName));
            Boolean b = false;
            exprValues.add((String) getExpressionValue(((Element) children.item(i)), b)[0]);
        } else if (children.item(i).getNodeName().equals("map")) {
            isMapped = true;
            mapNode = (Element) children.item(i);
        }
    }
    if (!isMapped) {
        String castedValue = "";
        boolean isDomainObjectMapper = false;
        try {
            Class localContextClass = null;
            try {
                if (mapPath != null) {
                    localContextClass = locateContextClass(mapPath, 0);
                } else {
                    if (Version.osgiActive()) {
                        localContextClass = resolveClassUsingService(className);
                    } else {
                        localContextClass = Class.forName(className, false, loader);
                    }
                }
            } catch (Exception e) {
                throw new UserException("Could not find adapter: " + className, e);
            }
            addDependency("dependentObjects.add( new JavaDependency( -1, \"" + className + "\"));\n", "JAVA" + className);
            dependencies.add(new JavaDependency(-1, className));
            String type = null;
            try {
                type = MappingUtils.getFieldType(localContextClass, attribute);
                checkDependentFieldResource(localContextClass, attribute, exprValues, dependencies);
            } catch (Exception e) {
                isDomainObjectMapper = localContextClass.isAssignableFrom(DomainObjectMapper.class);
                if (isDomainObjectMapper) {
                    type = "java.lang.Object";
                } else {
                    throw new UserException("Could not find field: " + attribute + " in adapter " + localContextClass.getName(), e);
                }
            }
            if (type.equals("java.lang.String")) {
                castedValue = "(String) sValue";
            } else if (type.equals("com.dexels.navajo.document.types.ClockTime")) {
                castedValue = "(com.dexels.navajo.document.types.ClockTime) sValue";
            } else if (type.equals("int")) {
                castedValue = "((Integer) sValue).intValue()";
            } else if (type.equals("double")) {
                castedValue = "((Double) sValue).doubleValue()";
            } else if (type.equals("java.util.Date")) {
                castedValue = "((java.util.Date) sValue)";
            } else if (type.equals("boolean")) {
                castedValue = "((Boolean) sValue).booleanValue()";
            } else if (type.equals("float")) {
                // sValue is never float,
                // internally always Double!
                castedValue = "(new Float(sValue+\"\")).floatValue()";
            } else if (type.equals("com.dexels.navajo.document.types.Binary")) {
                castedValue = "((com.dexels.navajo.document.types.Binary) sValue)";
            } else if (type.equals("com.dexels.navajo.document.types.Money")) {
                castedValue = "((com.dexels.navajo.document.types.Money) sValue)";
            } else if (type.equals("com.dexels.navajo.document.types.Percentage")) {
                castedValue = "((com.dexels.navajo.document.types.Percentage) sValue)";
            } else if (type.equals("java.lang.Integer")) {
                castedValue = "((Integer) sValue)";
            } else if (type.equals("java.lang.Long")) {
                castedValue = "((Long) sValue)";
            } else if (type.equals("java.lang.Float")) {
                // sValue is never
                // float,
                // internally
                // always
                // Double!
                castedValue = "new Float(sValue+\"\")";
            } else if (type.equals("java.lang.Double")) {
                castedValue = "((Double) sValue)";
            } else if (type.equals("java.lang.Boolean")) {
                castedValue = "((Boolean) sValue)";
            } else if (type.equals("java.util.List")) {
                castedValue = "((List<Object>) sValue)";
            } else {
                castedValue = "sValue";
            }
        } catch (UserException e) {
            throw new UserException(-1, "Error in script: could not find mappable object: " + className, e);
        }
        if (mapPath != null) {
            if (!isDomainObjectMapper) {
                result.append(printIdent(ident + 2) + "((" + locateContextClass(mapPath, 0).getName() + ")findMapByPath(\"" + mapPath + "\"))." + methodName + "(" + castedValue + ");\n");
            } else {
                result.append(printIdent(ident + 2) + "((" + locateContextClass(mapPath, 0).getName() + ")findMapByPath(\"" + mapPath + "\")).setDomainObjectAttribute(\"" + attribute + "\"," + castedValue + ");\n");
            }
        } else {
            if (!isDomainObjectMapper) {
                result.append(printIdent(ident + 2) + objectName + "." + methodName + "(" + castedValue + ");\n");
            } else {
                // set attribute in excluded fields.
                // USE INTROSPECTION METHOD TO CALL METHOD ON PROXIED
                // DOMAIN OBJECT...
                result.append(printIdent(ident + 2) + objectName + ".setDomainObjectAttribute(\"" + attribute + "\"," + castedValue + ");\n");
            }
        }
    } else {
        // Mappable)
        if (mapNode == null) {
            throw new IllegalStateException("Unexpected null mapNode");
        }
        String ref = mapNode.getAttribute("ref");
        boolean isParam = false;
        if (ref.indexOf("[") != -1) {
            // remove square brackets...
            ref = ref.replace('[', ' ');
            ref = ref.replace(']', ' ');
            ref = ref.trim();
        }
        if (ref.startsWith("/@")) {
            // replace @ with __parms__ 'parameter'
            // message indication.
            ref = ref.replaceAll("@", "__parms__/");
            isParam = true;
        }
        String filter = mapNode.getAttribute("filter");
        filter = (filter == null) ? "" : filter;
        result.append(printIdent(ident + 2) + "// And by the way, my filter is " + filter + "\n");
        result.append(printIdent(ident + 2) + "// Map message(s) to field\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");
        contextClassStack.push(contextClass);
        Class localContextClass = null;
        try {
            if (mapPath != null) {
                localContextClass = locateContextClass(mapPath, 1);
            } else {
                localContextClass = contextClass;
            }
        } catch (Exception e) {
            throw new UserException("Could not find adapter: " + className, e);
        }
        String type = null;
        try {
            type = MappingUtils.getFieldType(localContextClass, attribute);
        } catch (Exception e) {
            throw new UserException("Could not find field: " + attribute + " in adapter " + localContextClass.getName() + ", mappath = " + mapPath);
        }
        /**
         * END.
         */
        boolean isArray = MappingUtils.isArrayAttribute(localContextClass, attribute);
        try {
            contextClass = Class.forName(type, false, loader);
        } catch (Exception e) {
            throw new UserException("Could not find adapter: " + type);
        }
        addDependency("dependentObjects.add( new JavaDependency( -1, \"" + type + "\"));\n", "JAVA" + type);
        if (isArray) {
            String subObjectsName = "subObject" + subObjectCounter;
            String loopCounterName = "j" + subObjectCounter;
            subObjectCounter++;
            String objectDefinition = type + " [] " + subObjectsName + " = null;\n";
            variableClipboard.add(objectDefinition);
            variableClipboard.add("int " + loopCounterName + ";\n");
            result.append(printIdent(ident + 2) + subObjectsName + " = new " + type + "[" + messageListName + ".size()];\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.equals("")) {
                result.append(printIdent(ident + 4) + "if (inSelectionRef || Condition.evaluate(" + replaceQuotes(filter) + ", access.getInDoc(), currentMap, currentInMsg, currentParamMsg,access)) {\n");
                ident += 2;
            }
            result.append(printIdent(ident) + "treeNodeStack.push(currentMap);\n");
            result.append(printIdent(ident) + "currentMap = new MappableTreeNode(access, currentMap, classLoader.getClass(\"" + type + "\").newInstance(), false);\n");
            result.append(printIdent(ident + 4) + "currentMap.setNavajoLineNr(" + n.getAttribute("linenr") + ");\n");
            result.append(printIdent(ident) + "if ( currentMap.myObject instanceof Mappable ) {  ((Mappable) currentMap.myObject).load(access);}\n");
            result.append(printIdent(ident) + subObjectsName + "[" + loopCounterName + "] = (" + type + ") currentMap.myObject;\n");
            result.append(printIdent(ident) + "try {\n");
            ident = ident + 2;
            children = mapNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                result.append(compile(ident + 2, children.item(i), type, subObjectsName + "[" + loopCounterName + "]", dependencies, tenant));
            }
            ident = ident - 2;
            result.append(printIdent(ident) + "} catch (Exception e" + ident + ") {\n");
            result.append(printIdent(ident + 2) + "MappingUtils.callKillOrStoreMethod( " + subObjectsName + "[" + loopCounterName + "], e" + ident + ");\n");
            result.append(printIdent(ident + 2) + "throw e" + ident + ";\n");
            result.append(printIdent(ident) + "}\n");
            result.append(printIdent(ident) + "MappingUtils.callStoreMethod(" + subObjectsName + "[" + loopCounterName + "]);\n");
            result.append(printIdent(ident) + "currentMap.setEndtime();\ncurrentMap = (MappableTreeNode) treeNodeStack.pop();\n");
            if (!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");
            if (mapPath == null) {
                result.append(printIdent(ident + 2) + objectName + "." + methodName + "(" + subObjectsName + ");\n");
            } else {
                result.append(printIdent(ident + 2) + "((" + locateContextClass(mapPath, 1).getName() + ") findMapByPath(\"" + mapPath + "\"))." + methodName + "(" + subObjectsName + ");\n");
            }
        } else {
            // Not an array type field, but single Mappable object.
            // Push current mappable object on stack.
            result.append(printIdent(ident) + "treeNodeStack.push(currentMap);\n");
            // Create instance of object.
            result.append(printIdent(ident) + "currentMap = new MappableTreeNode(access, currentMap, classLoader.getClass(\"" + type + "\").newInstance(), false);\n");
            result.append(printIdent(ident + 4) + "currentMap.setNavajoLineNr(" + n.getAttribute("linenr") + ");\n");
            // Create local variable to address new object.
            String subObjectsName = "subObject" + subObjectCounter;
            subObjectCounter++;
            // push currentInMsg, currentParamMsg and inSelectionRef
            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(0);\n");
            }
            result.append(printIdent(ident) + "if (!inSelectionRef)\n");
            result.append(printIdent(ident + 2) + "currentInMsg = (Message) " + messageListName + ".get(0);\n");
            result.append(printIdent(ident) + "else\n");
            // currentSelection.
            result.append(printIdent(ident + 2) + "currentSelection = (Selection) " + messageListName + ".get(0);\n");
            // Call load on object.
            result.append(printIdent(ident) + "if ( currentMap.myObject instanceof Mappable) { ((Mappable) currentMap.myObject).load(access);}\n");
            // Assign local variable reference.
            result.append(printIdent(ident) + type + " " + subObjectsName + " = (" + type + ") currentMap.myObject;\n");
            result.append(printIdent(ident) + "try {\n");
            ident = ident + 2;
            // Recursively dive into children.
            children = mapNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                result.append(compile(ident + 2, children.item(i), type, subObjectsName, dependencies, tenant));
            }
            ident = ident - 2;
            result.append(printIdent(ident) + "} catch (Exception e" + ident + ") {\n");
            result.append(printIdent(ident + 2) + "MappingUtils.callKillOrStoreMethod( " + subObjectsName + ", e" + ident + ");\n");
            result.append(printIdent(ident + 2) + "throw e" + ident + ";\n");
            result.append(printIdent(ident) + "}\n");
            result.append(printIdent(ident) + "MappingUtils.callStoreMethod(" + subObjectsName + ");\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");
            result.append(printIdent(ident) + "currentMap.setEndtime();\ncurrentMap = (MappableTreeNode) treeNodeStack.pop();\n");
            if (mapPath == null) {
                result.append(printIdent(ident + 2) + objectName + "." + methodName + "(" + subObjectsName + ");\n");
            } else {
                result.append(printIdent(ident + 2) + "((" + locateContextClass(mapPath, 1).getName() + ") findMapByPath(\"" + mapPath + "\"))." + methodName + "(" + subObjectsName + ");\n");
            }
        }
        contextClass = contextClassStack.pop();
    }
    result.append(printIdent(ident) + "}\n");
    return result.toString();
}
Also used : JavaDependency(com.dexels.navajo.mapping.compiler.meta.JavaDependency) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) 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) UserException(com.dexels.navajo.script.api.UserException)

Example 67 with UserException

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

the class TslCompiler method locateContextClass.

/**
 * Locate a contextclass in the class stack based upon a mappath. Depending
 * on the way this method is called an additional offset to stack index must
 * be supplied...
 */
private Class locateContextClass(String mapPath, int offset) throws UserException {
    StringTokenizer st = new StringTokenizer(mapPath, "/");
    int count = 0;
    while (st.hasMoreTokens()) {
        String element = st.nextToken();
        if (!"..".equals(element)) {
            logger.debug("Huh? : {}", element);
        }
        count++;
    }
    if (count == 0) {
        return contextClass;
    }
    if (contextClassStack.size() - count - offset < 0) {
        throw new UserException("Could not resolve field: " + mapPath);
    }
    return contextClassStack.get(contextClassStack.size() - count - offset);
}
Also used : StringTokenizer(java.util.StringTokenizer) UserException(com.dexels.navajo.script.api.UserException)

Example 68 with UserException

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

the class TslCompiler method generateValidations.

/**
 * Check condition/validation rules inside the script.
 *
 * @param f
 * @return
 * @throws Exception
 */
private final void generateValidations(Document d, StringBuilder generatedCode) throws Exception {
    boolean hasValidations = false;
    StringBuilder conditionString = new StringBuilder("conditionArray = new String[]{\n");
    StringBuilder ruleString = new StringBuilder("ruleArray = new String[]{\n");
    StringBuilder codeString = new StringBuilder("codeArray = new String[]{\n");
    StringBuilder descriptionString = new StringBuilder("descriptionArray = new String[]{\n");
    NodeList list = d.getElementsByTagName("validations");
    for (int i = 0; i < list.getLength(); i++) {
        NodeList rules = list.item(i).getChildNodes();
        for (int j = 0; j < rules.getLength(); j++) {
            if (rules.item(j).getNodeName().equals("check")) {
                Element rule = (Element) rules.item(j);
                String code = rule.getAttribute("code");
                String description = rule.getAttribute("description");
                String value = rule.getAttribute("value");
                String condition = rule.getAttribute("condition");
                if (value.equals("")) {
                    value = rule.getFirstChild().getNodeValue();
                }
                if (code.equals("")) {
                    throw new UserException(-1, "Validation syntax error: code attribute missing or empty");
                }
                if (value.equals("")) {
                    throw new UserException(-1, "Validation syntax error: value attribute missing or empty");
                }
                value = value.replaceAll("\r", "");
                // Check if condition evaluates to true, for evaluating
                // validation ;)
                hasValidations = true;
                conditionString.append("\"" + condition.replace('\n', ' ').trim() + "\"");
                ruleString.append("\"" + value.replace('\n', ' ').trim() + "\"");
                codeString.append("\"" + code.replace('\n', ' ').trim() + "\"");
                descriptionString.append("\"" + description.replace('\n', ' ').trim() + "\"");
                if (j != (rules.getLength() - 2)) {
                    // Add ","
                    conditionString.append(",\n");
                    ruleString.append(",\n");
                    codeString.append(",\n");
                    descriptionString.append(",\n");
                }
            }
        }
        if (i < list.getLength() - 1) {
            conditionString.append(",\n");
            ruleString.append(",\n");
            codeString.append(",\n");
            descriptionString.append(",\n");
        }
    }
    conditionString.append("};\n");
    ruleString.append("};\n");
    codeString.append("};\n");
    descriptionString.append("};\n");
    generatedCode.append("public final void setValidations() {\n");
    if (hasValidations) {
        generatedCode.append(conditionString.toString());
        generatedCode.append(ruleString.toString());
        generatedCode.append(codeString.toString());
        generatedCode.append(descriptionString.toString());
    }
    generatedCode.append("}\n\n");
}
Also used : NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) UserException(com.dexels.navajo.script.api.UserException)

Example 69 with UserException

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

the class DomainObjectMapper method mapAllPropertiesToObject.

/**
 * Automatically maps all properties to appropriate 'setters'.
 *
 * @throws Exception
 */
private void mapAllPropertiesToObject(Class myClass) throws Exception {
    createObject();
    Message mapMsg = (myAccess.getCompiledScript() != null ? myAccess.getCompiledScript().getCurrentInMsg() : myAccess.getInDoc().getMessage(currentMessageName));
    if (mapMsg == null) {
        throw new UserException(-1, "No mappable message specified.");
    }
    List<Property> allProperties = mapMsg.getAllProperties();
    for (int i = 0; i < allProperties.size(); i++) {
        Property p = allProperties.get(i);
        if (!isAnExcludedProperty(p.getName())) {
            try {
                Class[] parameters = null;
                Object myValue = null;
                if (!p.getType().equals(Property.SELECTION_PROPERTY)) {
                    parameters = new Class[] { p.getTypedValue().getClass() };
                    myValue = p.getTypedValue();
                } else {
                    // Is selection.
                    parameters = new Class[] { String.class };
                    // Guess cardinality '1'.
                    if (p.getCardinality().equals("+")) {
                        throw new Exception("Multiple cardinality selections not yet supported in automatic mapping.");
                    }
                    myValue = p.getSelected().getValue();
                }
                Method m = setMethodReference(myClass, p.getName(), parameters);
                m.invoke(myObject, myValue);
            } catch (Exception e) {
                if (!isIgnoreNonExistingAttributes()) {
                    throw e;
                } else {
                // Ignore non existing attribute.
                }
            }
        }
    }
}
Also used : Message(com.dexels.navajo.document.Message) UserException(com.dexels.navajo.script.api.UserException) Method(java.lang.reflect.Method) Property(com.dexels.navajo.document.Property) MappingException(com.dexels.navajo.script.api.MappingException) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException)

Example 70 with UserException

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

the class Dispatcher method processNavajo.

/**
 * Handle a webservice.
 *
 * @param inMessage
 * @param userCertificate
 * @param clientInfo
 * @param origRunnable
 * @param skipAuth
 *            , always skip authorization part.
 * @return
 * @throws FatalException
 */
private final Navajo processNavajo(Navajo inMessage, String instance, Object userCertificate, ClientInfo clientInfo, boolean skipAuth, TmlRunnable origRunnable, AfterWebServiceEmitter emit) throws FatalException {
    Access access = null;
    Navajo outMessage = null;
    String rpcName = "";
    String rpcUser = "";
    String rpcPassword = "";
    Throwable myException = null;
    String origThreadName = null;
    boolean scheduledWebservice = false;
    boolean afterWebServiceActivated = false;
    int accessSetSize = accessSet.size();
    setRequestRate(clientInfo, accessSetSize);
    Navajo result = handleCallbackPointers(inMessage, instance);
    if (result != null) {
        return result;
    }
    Header header = inMessage.getHeader();
    rpcName = header.getRPCName();
    rpcUser = header.getRPCUser();
    rpcPassword = header.getRPCPassword();
    boolean preventFinalize = false;
    try {
        /**
         * Phase II: Authorisation/Authentication of the user. Is the user
         * known and valid and may it use the specified service? Also log
         * the access.
         */
        long startAuth = System.currentTimeMillis();
        if (rpcName == null) {
            throw new FatalException("No script defined");
        }
        if (rpcName.equals("navajo_ping")) {
            // Ping!
            outMessage = NavajoFactory.getInstance().createNavajo();
            Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
            outMessage.addHeader(h);
            return outMessage;
        }
        access = new Access(1, 1, rpcUser, rpcName, "", "", "", userCertificate, false, null);
        access.setTenant(instance);
        access.rpcPwd = rpcPassword;
        access.setInDoc(inMessage);
        access.setClientDescription(header.getHeaderAttribute("clientdescription"));
        access.setApplication(header.getHeaderAttribute("application"));
        access.setOrganization(header.getHeaderAttribute("organization"));
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
        }
        NavajoEventRegistry.getInstance().publishEvent(new NavajoRequestEvent(access));
        appendGlobals(inMessage, instance);
        if (useAuthorisation && !skipAuth) {
            try {
                if (navajoConfig == null) {
                    throw new FatalException("EMPTY NAVAJOCONFIG, INVALID STATE OF DISPATCHER!");
                }
                // if (instance == null) {
                // throw new SystemException(-1, "No tenant set -cannot authenticate!");
                // }
                // Determine authenticator
                final AuthenticationMethod authenticator;
                if (clientInfo == null) {
                    authenticator = authMethodBuilder.getInstanceForRequest(null);
                } else {
                    authenticator = authMethodBuilder.getInstanceForRequest(clientInfo.getAuthHeader());
                }
                if (authenticator == null) {
                    throw new FatalException("Missing authenticator");
                }
                authenticator.process(access);
            } catch (AuthorizationException ex) {
                outMessage = generateAuthorizationErrorMessage(access, ex, rpcName);
                AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + ex.getMessage(), Level.WARNING);
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                return outMessage;
            }/*catch (SystemException se) { //
                    logger.error("SystemException on authenticateUser  {} for {}: ", rpcUser, rpcName, se);
                    outMessage = generateErrorMessage(access, se.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                    AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + se.getMessage(),
                            Level.WARNING);
                    access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                    return outMessage;
                }*/
             catch (Throwable t) {
                logger.error("Unexpected exception on authenticateUser  {} for {}: ", rpcUser, rpcName, t);
                outMessage = generateErrorMessage(access, t.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                access.setException(t);
                return outMessage;
            }
        }
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
            access.parseTime = clientInfo.getParseTime();
            access.queueTime = clientInfo.getQueueTime();
            access.requestEncoding = clientInfo.getEncoding();
            access.compressedReceive = clientInfo.isCompressedRecv();
            access.compressedSend = clientInfo.isCompressedSend();
            access.contentLength = clientInfo.getContentLength();
            access.created = clientInfo.getCreated();
            access.queueId = clientInfo.getQueueId();
            access.queueSize = clientInfo.getQueueSize();
            // Set the name of this thread.
            origThreadName = Thread.currentThread().getName();
            Thread.currentThread().setName(getThreadName(access));
        }
        final GlobalManager gm;
        if (instance != null) {
            gm = globalManagers.get(instance);
        } else {
            gm = globalManagers.get("default");
        }
        if (gm != null) {
            gm.initGlobals(inMessage);
        }
        if (origRunnable != null) {
            access.setOriginalRunnable(origRunnable);
            // and vice versa, for the endTransaction
            origRunnable.setAttribute("access", access);
        }
        String fullLog = inMessage.getHeader().getHeaderAttribute("fullLog");
        if ("true".equals(fullLog)) {
            logger.info("Full debug detected. Accesshash: {}", access.hashCode());
            access.setDebugAll(true);
        }
        if ((access.userID == -1) || (access.serviceID == -1)) {
            // ACCESS NOTGRANTED.
            String errorMessage = "";
            if (access.userID == -1) {
                errorMessage = "Cannot authenticate user: " + rpcUser;
            } else {
                errorMessage = "Cannot authorise use of: " + rpcName;
            }
            outMessage = generateErrorMessage(access, errorMessage, SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
            return outMessage;
        } else {
            // ACCESS GRANTED.
            access.authorisationTime = (int) (System.currentTimeMillis() - startAuth);
            accessSet.add(access);
            // username might've changed as the username might've been a placeholder while we're authenticating using a bearer token
            rpcUser = access.getRpcUser();
            // Be very defensive not to add null values to the MDC, as they will fail at unexpected moments
            if (access.accessID != null) {
                MDC.put("accessId", access.accessID);
            }
            if (access.getRpcName() != null) {
                MDC.put("rpcName", access.getRpcName());
            }
            if (access.getRpcUser() != null) {
                MDC.put("rpcUser", access.getRpcUser());
            }
            if (access.getTenant() != null) {
                MDC.put("tenant", access.getTenant());
            }
            if (getNavajoConfig().getRootPath() != null) {
                MDC.put("rootPath", getNavajoConfig().getRootPath());
            }
            if (getNavajoConfig().getInstanceName() != null) {
                MDC.put("instanceName", getNavajoConfig().getInstanceName());
            }
            if (getNavajoConfig().getInstanceGroup() != null) {
                MDC.put("instanceGroup", getNavajoConfig().getInstanceGroup());
            }
            if (inMessage.getHeader().getSchedule() != null && !inMessage.getHeader().getSchedule().equals("")) {
                if (validTimeSpecification(inMessage.getHeader().getSchedule())) {
                    scheduledWebservice = true;
                    logger.info("Scheduling webservice: {}  on {} ", inMessage.getHeader().getRPCName(), inMessage.getHeader().getSchedule());
                    TaskRunnerInterface trf = TaskRunnerFactory.getInstance();
                    TaskInterface ti = trf.createTask();
                    try {
                        ti.setTrigger(inMessage.getHeader().getSchedule());
                        ti.setNavajo(inMessage);
                        // Make sure task gets persisted in tasks.xml
                        ti.setPersisted(true);
                        if (inMessage.getHeader().getHeaderAttribute("keeprequestresponse") != null && inMessage.getHeader().getHeaderAttribute("keeprequestresponse").equals("true")) {
                            ti.setKeepRequestResponse(true);
                        }
                        trf.addTask(ti);
                        outMessage = generateScheduledMessage(inMessage.getHeader(), ti.getId(), false);
                    } catch (TriggerException e) {
                        logger.info("WARNING: Invalid trigger specified for task {}: {}", ti.getId(), inMessage.getHeader().getSchedule());
                        trf.removeTask(ti);
                        outMessage = generateErrorMessage(access, "Could not schedule task:" + e.getMessage(), -1, -1, e);
                    }
                } else {
                    // obsolete time specification
                    outMessage = generateScheduledMessage(inMessage.getHeader(), null, true);
                }
            } else {
                /**
                 * Phase VI: Dispatch to proper servlet.
                 */
                // Create beforeWebservice event.
                access.setInDoc(inMessage);
                long bstart = System.currentTimeMillis();
                Navajo useProxy = (WebserviceListenerFactory.getInstance() != null ? WebserviceListenerFactory.getInstance().beforeWebservice(rpcName, access) : null);
                access.setBeforeServiceTime((int) (System.currentTimeMillis() - bstart));
                if (useAuthorisation) {
                    if (useProxy == null) {
                        outMessage = dispatch(access);
                    } else {
                        rpcName = access.rpcName;
                        outMessage = useProxy;
                    }
                } else {
                    throw new UnsupportedOperationException("I've removed this code because I assumed it wasn't used any more");
                }
            }
        }
    } catch (AuthorizationException aee) {
        outMessage = generateAuthorizationErrorMessage(access, aee, rpcName);
        AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + aee.getMessage() + ")", Level.WARNING);
        myException = aee;
        access.setExitCode(Access.EXIT_AUTH_EXECPTION);
        return outMessage;
    } catch (UserException ue) {
        try {
            outMessage = generateErrorMessage(access, ue.getMessage(), ue.code, 1, (ue.getCause() != null ? ue.getCause() : ue));
            myException = ue;
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            myException = ee;
            return errorHandler(access, ee, inMessage);
        }
    } catch (SystemException se) {
        logger.error("Error: ", se);
        myException = se;
        try {
            outMessage = generateErrorMessage(access, se.getMessage(), se.code, 1, (se.getCause() != null ? se.getCause() : se));
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            return errorHandler(access, ee, inMessage);
        }
    } catch (Throwable e) {
        logger.error("Error: ", e);
        myException = e;
        return errorHandler(access, e, inMessage);
    } finally {
        if (!preventFinalize) {
            finalizeService(inMessage, access, rpcName, rpcUser, myException, origThreadName, scheduledWebservice, afterWebServiceActivated, emit);
        }
    }
    return access.getOutputDoc();
}
Also used : FatalException(com.dexels.navajo.script.api.FatalException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) Access(com.dexels.navajo.script.api.Access) Navajo(com.dexels.navajo.document.Navajo) AuthenticationMethod(com.dexels.navajo.authentication.api.AuthenticationMethod) NavajoRequestEvent(com.dexels.navajo.events.types.NavajoRequestEvent) FatalException(com.dexels.navajo.script.api.FatalException) NavajoException(com.dexels.navajo.document.NavajoException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException) IOException(java.io.IOException) SystemException(com.dexels.navajo.script.api.SystemException) Header(com.dexels.navajo.document.Header) GlobalManager(com.dexels.navajo.server.global.GlobalManager) SystemException(com.dexels.navajo.script.api.SystemException) TaskRunnerInterface(com.dexels.navajo.server.enterprise.scheduler.TaskRunnerInterface) TaskInterface(com.dexels.navajo.server.enterprise.scheduler.TaskInterface) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException)

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