Search in sources :

Example 21 with Access

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

the class SFTPResourceTest method testSFTPResourceMap.

@Test
@Ignore
public void testSFTPResourceMap() throws MappableException, UserException {
    SFTPResourceMap sf = new SFTPResourceMap();
    sf.load(new Access());
    sf.setResource("test");
    sf.setPath("/share");
    sf.setFilename("monkey.gif");
    Binary b = new Binary(getClass().getResourceAsStream("logo.gif"));
    sf.setContent(b);
    sf.store();
}
Also used : SFTPResourceMap(com.dexels.navajo.resource.sftp.SFTPResourceMap) Access(com.dexels.navajo.script.api.Access) Binary(com.dexels.navajo.document.types.Binary) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 22 with Access

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

the class AsyncClientImpl method callService.

// Only used from Rhino
@Override
public void callService(Access inputAccess, Navajo input, String service, TmlRunnable onSuccess, TmlRunnable onFail, NavajoResponseCallback navajoResponseCallback) throws IOException {
    final Access currentAccess = inputAccess.cloneWithoutNavajos();
    if (input == null) {
        input = NavajoFactory.getInstance().createNavajo();
    }
    currentAccess.setInDoc(input);
    Header header = input.getHeader();
    if (header == null) {
        header = NavajoFactory.getInstance().createHeader(input, service, currentAccess.rpcUser, currentAccess.rpcUser, -1);
        input.addHeader(header);
    }
    header.setRPCName(service);
    header.setRPCUser(currentAccess.rpcUser);
    header.setRPCPassword(currentAccess.rpcPwd);
    NavajoResponseHandler nrh = new NavajoResponseHandler() {

        Throwable caughtException = null;

        @Override
        public void onResponse(Navajo n) {
            setActualCalls(getActualCalls() - 1);
            currentAccess.setOutputDoc(n);
            if (onSuccess != null) {
                onSuccess.setResponseNavajo(n);
                if (navajoResponseCallback != null) {
                    navajoResponseCallback.responseReceived(n);
                }
                setActualCalls(getActualCalls() - 1);
                SchedulerRegistry.submit(onSuccess, false);
            }
        }

        @Override
        public synchronized void onFail(Throwable t) throws IOException {
            caughtException = t;
            logger.warn("Error: ", caughtException);
            setActualCalls(getActualCalls() - 1);
            try {
                if (onFail != null) {
                    SchedulerRegistry.submit(onFail, false);
                }
            } finally {
                setActualCalls(getActualCalls() - 1);
            }
        }

        @Override
        public synchronized Throwable getCaughtException() {
            return caughtException;
        }
    };
    setActualCalls(getActualCalls() + 1);
    callService(currentAccess.getRequestUrl(), input, nrh, null);
}
Also used : Header(com.dexels.navajo.document.Header) Access(com.dexels.navajo.script.api.Access) NavajoResponseHandler(com.dexels.navajo.client.NavajoResponseHandler) Navajo(com.dexels.navajo.document.Navajo)

Example 23 with Access

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

Example 24 with Access

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

the class ASTMappableNode method interpretToLambda.

@Override
public ContextExpression interpretToLambda(List<String> problems, String expression, Function<String, FunctionClassification> functionClassifier, Function<String, Optional<Node>> mapResolver) {
    Optional<Node> resolved = mapResolver.apply(val);
    if (resolved.isPresent()) {
        return resolved.get().interpretToLambda(problems, expression, functionClassifier, mapResolver);
    }
    return new ContextExpression() {

        @Override
        public boolean isLiteral() {
            return false;
        }

        @Override
        public Operand apply(Navajo doc, Message parentMsg, Message parentParamMsg, Selection parentSel, MappableTreeNode mapNode, TipiLink tipiLink, Access access, Optional<ImmutableMessage> immutableMessage, Optional<ImmutableMessage> paramMessage) {
            if (mapNode == null) {
                throw new TMLExpressionException("No known mapobject resolver");
            }
            // MappableTreeNode mapNode = mapNodeResolver.apply(val);
            // if(mapNode==null) {
            // throw new TMLExpressionException("No known mapobject");
            // 
            // }
            // if(mapNode==null) {
            // Node resolvedItem = mapResolver.get().apply(val);
            // System.err.println(">> "+resolvedItem.getClass());
            // resolvedItem.interpretToLambda(problems, expression, functionClassifier, mapResolver);
            // 
            // }
            List objects = null;
            // Parameter array may contain parameters that are used when calling the get method.
            Object[] parameterArray = null;
            if (args > 0) {
                objects = new ArrayList();
            }
            for (int i = 0; i < args; i++) {
                List<String> problems = new ArrayList<>();
                Operand a = jjtGetChild(i).interpretToLambda(problems, expression, functionClassifier, mapResolver).apply(doc, parentMsg, parentParamMsg, parentSel, mapNode, tipiLink, access, immutableMessage, paramMessage);
                if (!problems.isEmpty()) {
                    throw new TMLExpressionException(problems, expression);
                }
                if (objects != null) {
                    objects.add(a.value);
                }
            }
            // List<String> problems
            if (objects != null) {
                parameterArray = new Object[objects.size()];
                parameterArray = objects.toArray(parameterArray);
            }
            try {
                Object oValue = maybeGetMapAttribute(val, mapNode, parameterArray);
                if (oValue == null)
                    return Operand.NULL;
                else if (oValue instanceof Float) {
                    return Operand.ofFloat(((Float) oValue).doubleValue());
                } else if (oValue instanceof Long) {
                    return Operand.ofLong(((Long) oValue).longValue());
                } else {
                    return Operand.ofDynamic(oValue);
                }
            } catch (Exception me) {
                throw new TMLExpressionException(me.getMessage(), me);
            }
        }

        @Override
        public Optional<String> returnType() {
            return Optional.empty();
        }

        @Override
        public String expression() {
            return expression;
        }
    };
}
Also used : MappableTreeNode(com.dexels.navajo.script.api.MappableTreeNode) Message(com.dexels.navajo.document.Message) ImmutableMessage(com.dexels.immutable.api.ImmutableMessage) Optional(java.util.Optional) Selection(com.dexels.navajo.document.Selection) Operand(com.dexels.navajo.document.Operand) MappableTreeNode(com.dexels.navajo.script.api.MappableTreeNode) ContextExpression(com.dexels.navajo.expression.api.ContextExpression) Access(com.dexels.navajo.script.api.Access) ArrayList(java.util.ArrayList) Navajo(com.dexels.navajo.document.Navajo) TMLExpressionException(com.dexels.navajo.expression.api.TMLExpressionException) TMLExpressionException(com.dexels.navajo.expression.api.TMLExpressionException) TipiLink(com.dexels.navajo.expression.api.TipiLink) ArrayList(java.util.ArrayList) List(java.util.List)

Example 25 with Access

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

the class ASTOrNode method interpretToLambda.

@Override
public ContextExpression interpretToLambda(List<String> problems, String expression, Function<String, FunctionClassification> functionClassifier, Function<String, Optional<Node>> mapResolver) {
    ContextExpression expA = jjtGetChild(0).interpretToLambda(problems, expression, functionClassifier, mapResolver);
    checkOrAdd("Or expression failed, first expression is not a boolean but a " + expA.returnType().orElse("<unknown>"), problems, expA.returnType(), Property.BOOLEAN_PROPERTY);
    ContextExpression expB = jjtGetChild(1).interpretToLambda(problems, expression, functionClassifier, mapResolver);
    checkOrAdd("Or expression failed, second expression is not a boolean but a " + expB.returnType().orElse("<unknown>"), problems, expB.returnType(), Property.BOOLEAN_PROPERTY);
    return new ContextExpression() {

        @Override
        public boolean isLiteral() {
            return expA.isLiteral() && expB.isLiteral();
        }

        @Override
        public Operand apply(Navajo doc, Message parentMsg, Message parentParamMsg, Selection parentSel, MappableTreeNode mapNode, TipiLink tipiLink, Access access, Optional<ImmutableMessage> immutableMessage, Optional<ImmutableMessage> paramMessage) {
            Object a = expA.apply(doc, parentMsg, parentParamMsg, parentSel, mapNode, tipiLink, access, immutableMessage, paramMessage).value;
            Boolean ba = (Boolean) a;
            if (a == null) {
                ba = Boolean.FALSE;
            }
            if (ba.booleanValue())
                return Operand.ofBoolean(true);
            Object b = expB.apply(doc, parentMsg, parentParamMsg, parentSel, mapNode, tipiLink, access, immutableMessage, paramMessage).value;
            Boolean bb = (Boolean) b;
            if (b == null) {
                bb = Boolean.FALSE;
            }
            return Operand.ofBoolean(ba.booleanValue() || bb.booleanValue());
        }

        @Override
        public Optional<String> returnType() {
            return Optional.of(Property.BOOLEAN_PROPERTY);
        }

        @Override
        public String expression() {
            return expression;
        }
    };
}
Also used : MappableTreeNode(com.dexels.navajo.script.api.MappableTreeNode) TipiLink(com.dexels.navajo.expression.api.TipiLink) Message(com.dexels.navajo.document.Message) ImmutableMessage(com.dexels.immutable.api.ImmutableMessage) Optional(java.util.Optional) Selection(com.dexels.navajo.document.Selection) ContextExpression(com.dexels.navajo.expression.api.ContextExpression) Access(com.dexels.navajo.script.api.Access) Navajo(com.dexels.navajo.document.Navajo)

Aggregations

Access (com.dexels.navajo.script.api.Access)45 Navajo (com.dexels.navajo.document.Navajo)29 Message (com.dexels.navajo.document.Message)27 Test (org.junit.Test)18 Property (com.dexels.navajo.document.Property)15 Selection (com.dexels.navajo.document.Selection)14 ImmutableMessage (com.dexels.immutable.api.ImmutableMessage)12 ContextExpression (com.dexels.navajo.expression.api.ContextExpression)12 TipiLink (com.dexels.navajo.expression.api.TipiLink)12 MappableTreeNode (com.dexels.navajo.script.api.MappableTreeNode)12 Optional (java.util.Optional)12 Operand (com.dexels.navajo.document.Operand)10 TMLExpressionException (com.dexels.navajo.expression.api.TMLExpressionException)10 ArrayList (java.util.ArrayList)8 UserException (com.dexels.navajo.script.api.UserException)6 ResultMessage (com.dexels.navajo.adapter.messagemap.ResultMessage)5 Binary (com.dexels.navajo.document.types.Binary)4 HttpResource (com.dexels.navajo.resource.http.HttpResource)4 HttpResourceFactory (com.dexels.navajo.resource.http.HttpResourceFactory)4 Dispatcher (com.dexels.navajo.server.Dispatcher)4