Search in sources :

Example 6 with SystemException

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

the class SumExpressions method evaluate.

/* (non-Javadoc)
	 * @see com.dexels.navajo.parser.FunctionInterface#evaluate()
	 */
@Override
public Object evaluate() throws TMLExpressionException {
    if (getOperands().size() < 2) {
        for (int i = 0; i < getOperands().size(); i++) {
            Object o = getOperands().get(i);
            System.err.println("Operand # " + i + " is: " + o.toString() + " - " + o.getClass());
        }
        throw new TMLExpressionException(this, "Wrong number of arguments: " + getOperands().size());
    }
    if (!(getOperand(0) instanceof String && getOperand(1) instanceof String)) {
        throw new TMLExpressionException(this, "Wrong argument types: " + getOperand(0).getClass() + " and " + getOperand(1).getClass());
    }
    String messageName = (String) getOperand(0);
    String expression = (String) getOperand(1);
    String filter = null;
    if (getOperands().size() > 2) {
        filter = (String) getOperand(2);
    }
    Message parent = getCurrentMessage();
    Navajo doc = getNavajo();
    try {
        List<Message> arrayMsg = (parent != null ? parent.getMessages(messageName) : doc.getMessages(messageName));
        if (arrayMsg == null) {
            throw new TMLExpressionException(this, "Empty or non existing array message: " + messageName);
        }
        String sumType = "int";
        double sum = 0;
        for (int i = 0; i < arrayMsg.size(); i++) {
            Message m = arrayMsg.get(i);
            boolean evaluate = (filter != null ? Condition.evaluate(filter, doc, null, m, getAccess()) : true);
            if (evaluate) {
                Operand o = Expression.evaluate(expression, m.getRootDoc(), null, m);
                if (o.value == null) {
                    throw new TMLExpressionException(this, "Null value encountered");
                }
                if (o.value instanceof Integer) {
                    sum += ((Integer) o.value).doubleValue();
                } else if (o.value instanceof Double) {
                    sum += ((Double) o.value).doubleValue();
                } else {
                    throw new TMLExpressionException(this, "Incompatible type while summing: " + o.value.getClass().getName());
                }
            }
        }
        if (sumType.equals("int")) {
            return Integer.valueOf((int) sum);
        } else if (sumType.equals("money")) {
            return new Money(sum);
        } else if (sumType.equals("percentage")) {
            return new Percentage(sum);
        } else {
            return Double.valueOf(sum);
        }
    } catch (NavajoException ne) {
        throw new TMLExpressionException(this, ne.getMessage());
    } catch (SystemException se) {
        throw new TMLExpressionException(this, se.getMessage());
    }
}
Also used : Message(com.dexels.navajo.document.Message) Percentage(com.dexels.navajo.document.types.Percentage) Operand(com.dexels.navajo.document.Operand) NavajoException(com.dexels.navajo.document.NavajoException) Navajo(com.dexels.navajo.document.Navajo) TMLExpressionException(com.dexels.navajo.expression.api.TMLExpressionException) Money(com.dexels.navajo.document.types.Money) SystemException(com.dexels.navajo.script.api.SystemException)

Example 7 with SystemException

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

the class SumProperties method evaluate.

@Override
public Object evaluate() throws com.dexels.navajo.expression.api.TMLExpressionException {
    if (getOperands().size() < 2) {
        for (int i = 0; i < getOperands().size(); i++) {
            Object o = getOperands().get(i);
            logger.info("Operand # " + i + " is: " + o.toString() + " - " + o.getClass());
        }
        throw new TMLExpressionException(this, "Wrong number of arguments: " + getOperands().size());
    }
    if (!(getOperand(0) instanceof String && getOperand(1) instanceof String)) {
        throw new TMLExpressionException(this, "Wrong argument types: " + getOperand(0).getClass() + " and " + getOperand(1).getClass());
    }
    String messageName = (String) getOperand(0);
    String propertyName = (String) getOperand(1);
    String filter = null;
    if (getOperands().size() > 2) {
        filter = (String) getOperand(2);
    }
    Message parent = getCurrentMessage();
    Navajo doc = getNavajo();
    try {
        List<Message> arrayMsg = (parent != null ? parent.getMessages(messageName) : doc.getMessages(messageName));
        if (arrayMsg == null) {
            throw new TMLExpressionException(this, "Empty or non existing array message: " + messageName);
        }
        String sumType = "int";
        double sum = 0;
        for (int i = 0; i < arrayMsg.size(); i++) {
            Message m = arrayMsg.get(i);
            Property p = m.getProperty(propertyName);
            boolean evaluate = (filter != null ? Condition.evaluate(filter, doc, null, m, getAccess()) : true);
            if (evaluate) {
                if (p != null) {
                    Object o = p.getTypedValue();
                    if (o == null) {
                        continue;
                    }
                    if (!(o instanceof Integer || o instanceof Double || o instanceof Float || o instanceof Money || o instanceof Percentage || o instanceof Boolean || o instanceof String)) {
                        throw new TMLExpressionException(this, "Only numbers are supported a sum. Not: " + (o.getClass().toString()) + " value: " + o);
                    }
                    if (o instanceof String) {
                        if ("".equals(o)) {
                        // ignore
                        } else {
                            logger.error("Only numbers are supported a sum. Not strings. Value:  " + o);
                            throw new TMLExpressionException(this, "Only numbers are supported a sum. Not strings. Value:  " + o + (o.getClass().toString()));
                        }
                    }
                    if (o instanceof Integer) {
                        sumType = "int";
                        sum += ((Integer) o).doubleValue();
                    } else if (o instanceof Double) {
                        // if (!((Double)o).equals(Double.valueOf(Double.NaN))) {
                        sumType = "float";
                        sum += ((Double) o).doubleValue();
                    // }
                    } else if (o instanceof Float) {
                        // if (!((Float)o).equals(new Float(Float.NaN))) {
                        sumType = "float";
                        sum += ((Float) o).doubleValue();
                    // }
                    } else if (o instanceof Money) {
                        // if (!Double.valueOf(((Money)o).doubleValue()).equals(Double.valueOf(Float.NaN))) {
                        sumType = "money";
                        sum += ((Money) o).doubleValue();
                    // }
                    } else if (o instanceof Percentage) {
                        // if (!Double.valueOf(((Money)o).doubleValue()).equals(Double.valueOf(Float.NaN))) {
                        sumType = "percentage";
                        sum += ((Percentage) o).doubleValue();
                    // }
                    } else if (o instanceof Boolean) {
                        sumType = "int";
                        sum += ((Boolean) o).booleanValue() ? 1 : 0;
                    }
                } else {
                    throw new TMLExpressionException(this, "Property does not exist: " + propertyName);
                }
            }
        }
        if (sumType.equals("int")) {
            return Integer.valueOf((int) sum);
        } else if (sumType.equals("money")) {
            return new Money(sum);
        } else if (sumType.equals("percentage")) {
            return new Percentage(sum);
        } else {
            return Double.valueOf(sum);
        }
    } catch (NavajoException ne) {
        throw new TMLExpressionException(this, ne.getMessage());
    } catch (SystemException se) {
        throw new TMLExpressionException(this, se.getMessage());
    }
}
Also used : Message(com.dexels.navajo.document.Message) Percentage(com.dexels.navajo.document.types.Percentage) NavajoException(com.dexels.navajo.document.NavajoException) Navajo(com.dexels.navajo.document.Navajo) TMLExpressionException(com.dexels.navajo.expression.api.TMLExpressionException) Money(com.dexels.navajo.document.types.Money) SystemException(com.dexels.navajo.script.api.SystemException) Property(com.dexels.navajo.document.Property)

Example 8 with SystemException

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

the class TslCompiler method compileScript.

private final void compileScript(InputStream is, String packagePath, String script, String scriptPath, Writer fo, List<Dependency> deps, String tenant, boolean forceTenant) throws SystemException, SkipCompilationException {
    boolean broadcast = false;
    this.scriptPath = scriptPath;
    try {
        Document tslDoc = null;
        StringBuilder result = new StringBuilder();
        tslDoc = XMLDocumentUtils.createDocument(is, false);
        NodeList tsl = tslDoc.getElementsByTagName("tsl");
        // Invesitigate if it's a direct tml script:
        NodeList nodes = tslDoc.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n instanceof Element) {
                Element e = (Element) n;
                if (e.getTagName().equals("tml") || e.getTagName().equals("message")) {
                    throw new SkipCompilationException("Direct tml needs no compilation");
                }
            }
        }
        if (tsl == null || tsl.getLength() != 1 || !(tsl.item(0) instanceof Element)) {
            throw new SkipCompilationException("Ignoring file: " + scriptPath);
        }
        Element tslElt = (Element) tsl.item(0);
        boolean includeOnly = "true".equals(tslElt.getAttribute("includeOnly"));
        if (includeOnly) {
            throw new SkipCompilationException("Include only for: " + scriptPath);
        }
        String debugLevel = tslElt.getAttribute("debug");
        String description = tslElt.getAttribute("notes");
        String author = tslElt.getAttribute("author");
        broadcast = (tslElt.getAttribute("broadcast").indexOf("true") != -1);
        String actualPackagePath = packagePath;
        if (packagePath.equals("")) {
            if (Version.osgiActive()) {
                actualPackagePath = "defaultPackage";
            }
        }
        String className = script;
        if (forceTenant) {
            className += "_" + tenant;
        }
        String importDef = (actualPackagePath.equals("") ? "" : "package " + MappingUtils.createPackageName(actualPackagePath) + ";\n\n") + "import com.dexels.navajo.server.*;\n" + "import com.dexels.navajo.mapping.*;\n" + "import com.dexels.navajo.document.*;\n" + "import com.dexels.navajo.parser.*;\n" + "import com.dexels.navajo.script.api.*;\n" + "import com.dexels.navajo.expression.api.*;\n" + "import java.util.ArrayList;\n" + "import java.util.List;\n" + "import java.util.HashMap;\n" + "import com.dexels.navajo.server.enterprise.tribe.TribeManagerFactory;\n" + "import com.dexels.navajo.mapping.compiler.meta.IncludeDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.ExtendDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.ExpressionValueDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.SQLFieldDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.InheritDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.JavaDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.NavajoDependency;\n" + "import com.dexels.navajo.mapping.compiler.meta.AdapterFieldDependency;\n" + "import java.util.concurrent.locks.Lock;\n" + "import java.util.concurrent.TimeUnit;\n" + "import java.util.Stack;\n" + "import java.util.Date;\n\n\n";
        result.append(importDef);
        result.append("/**\n");
        result.append(" * Generated Java code by TSL compiler.\n");
        result.append(" * \n");
        result.append(" *\n");
        result.append(" * Java version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.runtime.version") + ")\n");
        result.append(" * OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + "\n");
        result.append(" *\n");
        result.append(" * WARNING NOTICE: DO NOT EDIT THIS FILE UNLESS YOU ARE COMPLETELY AWARE OF WHAT YOU ARE DOING\n");
        result.append(" *\n");
        result.append(" */\n\n");
        String classDef = "public final class " + className + " extends CompiledScript {\n\n\n";
        result.append(classDef);
        result.append("private volatile ArrayList<Dependency> dependentObjects = null;\n\n");
        // Add constructor.
        String constructorDef = "  public " + className + "() {\n " + "        if ( dependentObjects == null ) {\n" + "             dependentObjects = new ArrayList<Dependency>();\n" + "             setDependencies();\n" + "        }\n" + "  }\n\n";
        result.append(constructorDef);
        // First resolve includes.
        NodeList includes = tslDoc.getElementsByTagName("include");
        Node[] includeArray = new Node[includes.getLength()];
        for (int i = 0; i < includes.getLength(); i++) {
            includeArray[i] = includes.item(i);
        }
        for (int i = 0; i < includeArray.length; i++) {
            includeNode(scriptPath, includeArray[i], tslDoc, tenant, deps);
        }
        generateSetScriptDebug(debugLevel, result);
        // Generate validation code.
        generateValidations(tslDoc, result);
        // Generate final block code.
        generateFinalBlock(tslDoc, result, deps, tenant);
        String methodDef = "public final void execute(Access access) throws Exception { \n\n";
        result.append(methodDef);
        result.append("try {\n");
        result.append("inDoc = access.getInDoc();\n");
        // File Rules HashMap
        generateRules(tslDoc, result);
        NodeList children = tslDoc.getElementsByTagName("tsl").item(0).getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            String str = compile(0, children.item(i), "", "", deps, tenant);
            result.append(str);
        }
        result.append("} finally {\n");
        if (broadcast) {
            result.append("try { \n");
            result.append("   TribeManagerFactory.getInstance().broadcast(inDoc, access.getTenant());\n");
            result.append("} catch (Exception e) { \n");
            result.append("   e.printStackTrace(System.err);\n");
            result.append("}\n");
        }
        result.append("}\n");
        result.append("}// EOM\n");
        // Add generated methods.
        for (int i = 0; i < methodClipboard.size(); i++) {
            result.append(methodClipboard.get(i).toString() + "\n\n");
        }
        // Add generated variables.
        for (int i = 0; i < variableClipboard.size(); i++) {
            result.append(variableClipboard.get(i));
        }
        // Add public void setDependencies
        if (!dependencies.toString().equals("")) {
            result.append("public void setDependencies() {\n");
            result.append(dependencies.toString());
            result.append("}\n\n");
            result.append("public ArrayList<Dependency> getDependentObjects() {\n");
            result.append("   return dependentObjects;\n");
            result.append("}\n\n");
        }
        // Add getDescription() and getAuthor()
        if (author != null) {
            String flatAuthor = description.replace("\n", "").replace("\r", "");
            result.append("public String getAuthor() {\n");
            result.append("   return \"" + flatAuthor + "\";\n");
            result.append("}\n\n");
        }
        if (description != null) {
            String flatDescription = description.replace("\n", "").replace("\r", "");
            result.append("public String getDescription() {\n");
            result.append("   return \"" + flatDescription + "\";\n");
            result.append("}\n\n");
        }
        result.append("public String getScriptType() {\n");
        result.append("   return \"" + scriptType + "\";\n");
        result.append("}\n\n");
        result.append("}//EOF");
        fo.write(result.toString());
        fo.close();
    } catch (SkipCompilationException e) {
        throw (e);
    } catch (Exception e) {
        throw new SystemException(-1, "Error while generating Java code for script: " + script + ": " + e.getMessage(), e);
    }
}
Also used : SystemException(com.dexels.navajo.script.api.SystemException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) 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)

Example 9 with SystemException

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

the class TslCompiler method compileScript.

public void compileScript(String script, String scriptPath, String workingPath, String packagePath, Writer outputWriter, List<Dependency> deps, String tenant, boolean hasTenantSpecificScript, boolean forceTenant) throws SystemException, SkipCompilationException {
    final String extension = ".xml";
    String fullScriptPath = scriptPath + "/" + packagePath + "/" + script + extension;
    String ns3ScriptPath = scriptPath + "/" + packagePath + "/" + script + ".ns";
    List<String> inheritedScripts = new ArrayList<>();
    List<String> extendEntities = new ArrayList<>();
    InputStream is = null;
    boolean isNavascript = false;
    try {
        if (new File(ns3ScriptPath).exists()) {
            NS3ToNSXML ns3toxml = new NS3ToNSXML();
            ns3toxml.initialize();
            scriptType = "navascript";
            String content = ns3toxml.read(ns3ScriptPath);
            InputStream metais = ns3toxml.parseNavascript(content);
            MapMetaData mmd = MapMetaData.getInstance();
            String intermed = mmd.parse(fullScriptPath, metais);
            metais.close();
            is = new ByteArrayInputStream(intermed.getBytes());
            isNavascript = true;
        } else if (MapMetaData.isMetaScript(fullScriptPath)) {
            // Check for metascript.
            scriptType = "navascript";
            MapMetaData mmd = MapMetaData.getInstance();
            InputStream metais = navajoIOConfig.getScript(packagePath + "/" + script, tenant, extension);
            String intermed = mmd.parse(fullScriptPath, metais);
            metais.close();
            is = new ByteArrayInputStream(intermed.getBytes());
        } else {
            is = navajoIOConfig.getScript(packagePath + "/" + script, tenant, extension);
        }
        if (!isNavascript) {
            // NS3 does NOT support inheritance at this moment.
            InputStream sis = navajoIOConfig.getScript(packagePath + "/" + script, tenant, extension);
            logger.debug("Getting script: {}/{}", packagePath, script);
            if (ScriptInheritance.containsInject(sis)) {
                // Inheritance preprocessor before compiling.
                InputStream ais = null;
                ais = ScriptInheritance.inherit(is, scriptPath, inheritedScripts);
                is.close();
                is = ais;
            }
            sis.close();
        }
        for (int i = 0; i < inheritedScripts.size(); i++) {
            File inheritedFile = new File(fetchScriptFileName(scriptPath + "/" + inheritedScripts.get(i)));
            addDependency("dependentObjects.add( new InheritDependency( Long.valueOf(\"" + IncludeDependency.getFileTimeStamp(inheritedFile) + "\"), \"" + inheritedScripts.get(i) + "\"));\n", "INHERIT" + inheritedScripts.get(i));
        }
        compileScript(is, packagePath, script, scriptPath, outputWriter, deps, tenant, forceTenant);
    } catch (SkipCompilationException e) {
        throw e;
    } catch (Exception e) {
        throw new SystemException(-1, "Error while generating Java code for script: " + script, e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) MapMetaData(com.dexels.navajo.mapping.compiler.meta.MapMetaData) 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) SystemException(com.dexels.navajo.script.api.SystemException) ByteArrayInputStream(java.io.ByteArrayInputStream) NS3ToNSXML(com.dexels.navajo.mapping.compiler.navascript.NS3ToNSXML) File(java.io.File)

Example 10 with SystemException

use of com.dexels.navajo.script.api.SystemException 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

SystemException (com.dexels.navajo.script.api.SystemException)18 TMLExpressionException (com.dexels.navajo.expression.api.TMLExpressionException)10 Message (com.dexels.navajo.document.Message)9 Navajo (com.dexels.navajo.document.Navajo)9 NavajoException (com.dexels.navajo.document.NavajoException)9 UserException (com.dexels.navajo.script.api.UserException)8 Operand (com.dexels.navajo.document.Operand)7 IOException (java.io.IOException)7 Property (com.dexels.navajo.document.Property)5 CompilationException (com.dexels.navajo.script.api.CompilationException)4 KeywordException (com.dexels.navajo.mapping.compiler.meta.KeywordException)3 MetaCompileException (com.dexels.navajo.mapping.compiler.meta.MetaCompileException)3 ParseException (com.dexels.navajo.parser.compiled.ParseException)3 MappableException (com.dexels.navajo.script.api.MappableException)3 MappingException (com.dexels.navajo.script.api.MappingException)3 ConditionErrorException (com.dexels.navajo.server.ConditionErrorException)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3 TransformerException (javax.xml.transform.TransformerException)3 Header (com.dexels.navajo.document.Header)2