Search in sources :

Example 16 with Header

use of com.dexels.navajo.document.Header 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 17 with Header

use of com.dexels.navajo.document.Header in project navajo by Dexels.

the class Dispatcher method dispatch.

/*
     * Process a webservice using a special handler class.
     *
     * @param handler the class the will process the webservice.
     *
     * @param in the request Navajo document.
     *
     * @param access
     *
     * @param parms
     *
     * @return
     *
     * @throws Exception
     */
private final Navajo dispatch(Access access) throws Exception {
    WorkerInterface integ = null;
    Navajo out = null;
    if (access == null) {
        logger.warn("Null access!!!");
        return null;
    }
    Navajo in = access.getInDoc();
    if (in != null) {
        Header h = in.getHeader();
        if (h != null) {
            // Process client token:
            String clientToken = h.getHeaderAttribute("clientToken");
            if (clientToken != null) {
                access.setClientToken(access.getClientToken() + " -- " + clientToken);
            }
            // Process client info:
            String clientInfo = h.getHeaderAttribute("clientInfo");
            if (clientInfo != null) {
                access.setClientInfo(clientInfo);
            }
            // Process piggyback data:
            Set<Map<String, String>> s = h.getPiggybackData();
            if (s != null) {
                for (Iterator<Map<String, String>> iter = s.iterator(); iter.hasNext(); ) {
                    Map<String, String> element = iter.next();
                    access.addPiggybackData(element);
                }
            }
        }
    } else {
        throw NavajoFactory.getInstance().createNavajoException("Null input message in dispatch");
    }
    // Check for webservice transaction integrity.
    boolean integrityViolation = false;
    integ = navajoConfig.getIntegrityWorker();
    if (integ != null) {
        // Check for stored response or webservice that is still running.
        out = integ.getResponse(access, in);
        if (out != null) {
            integrityViolation = true;
            return out;
        }
    }
    try {
        ServiceHandler sh = handlerFactory.createHandler(navajoConfig, access, simulationMode);
        out = sh.doService(access);
        access.setOutputDoc(out);
        // Store response for integrity checking.
        if (integ != null && out != null && !integrityViolation) {
            integ.setResponse(in, out);
        }
        return out;
    } finally {
        // Remove stored access from worker request list.
        if (integ != null) {
            integ.removeFromRunningRequestsList(in);
        }
    }
}
Also used : WorkerInterface(com.dexels.navajo.server.enterprise.integrity.WorkerInterface) Header(com.dexels.navajo.document.Header) Navajo(com.dexels.navajo.document.Navajo) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 18 with Header

use of com.dexels.navajo.document.Header in project navajo by Dexels.

the class Dispatcher method finalizeService.

@Override
public void finalizeService(Navajo inMessage, Access access, String rpcName, String rpcUser, Throwable myException, String origThreadName, boolean scheduledWebservice, boolean afterWebServiceActivated, AfterWebServiceEmitter emit) {
    if (access != null && !scheduledWebservice) {
        Navajo outMessage = access.getOutputDoc();
        try {
            // Always make sure header contains original rpcName and rpcUser
            // (BUT NOT PASSWORD!).
            Header h = outMessage.getHeader();
            if (h == null) {
                h = NavajoFactory.getInstance().createHeader(outMessage, rpcName, rpcUser, "", -1);
                outMessage.addHeader(h);
            } else {
                h.setRPCName(rpcName);
                h.setRPCUser(rpcUser);
            }
            // Set accessId to make sure it can be used as reference by
            // triggered tasks.
            h.setHeaderAttribute("accessId", access.getAccessID());
            // If emitter is specified, first fire emitter.
            if (emit != null) {
                emit.emit(access.getOutputDoc());
            }
            // Call after web service event...
            access.setAfterServiceTime(0);
            if (access.getExitCode() != Access.EXIT_AUTH_EXECPTION) {
                long astart = System.currentTimeMillis();
                if (WebserviceListenerFactory.getInstance() != null) {
                    WebserviceListenerFactory.getInstance().afterWebservice(rpcName, access);
                }
                access.setAfterServiceTime((int) (System.currentTimeMillis() - astart));
            }
            // Set access to finished state.
            access.setFinished();
            // Translate property descriptions.
            updatePropertyDescriptions(inMessage, outMessage, access);
            access.storeStatistics(h);
            // Call Navajoresponse event.
            access.setException(myException);
            NavajoEventRegistry.getInstance().publishEvent(new NavajoResponseEvent(access));
            // Publish exception event if exception occurred.
            if (myException != null) {
                NavajoEventRegistry.getInstance().publishEvent(new NavajoExceptionEvent(rpcName, access.getAccessID(), rpcUser, myException));
            }
        } finally {
            // Remove access object from set of active webservices first.
            accessSet.remove(access);
        }
    }
    generateNavajoRequestEvent(myException != null);
    if (origThreadName != null) {
        Thread.currentThread().setName(origThreadName);
    }
}
Also used : NavajoExceptionEvent(com.dexels.navajo.events.types.NavajoExceptionEvent) Header(com.dexels.navajo.document.Header) Navajo(com.dexels.navajo.document.Navajo) NavajoResponseEvent(com.dexels.navajo.events.types.NavajoResponseEvent)

Example 19 with Header

use of com.dexels.navajo.document.Header in project navajo by Dexels.

the class GenericHandler method doService.

/**
 * doService() is called by Dispatcher to perform web service.
 *
 * @return
 * @throws NavajoException
 * @throws UserException
 * @throws SystemException
 * @throws AuthorizationException
 */
@Override
public final Navajo doService(Access a) throws UserException, SystemException, AuthorizationException {
    if (a.isBreakWasSet()) {
        if (a.getOutputDoc() == null) {
            Navajo outDoc = NavajoFactory.getInstance().createNavajo();
            a.setOutputDoc(outDoc);
        }
        return a.getOutputDoc();
    }
    Navajo outDoc = null;
    StringBuilder compilerErrors = new StringBuilder();
    outDoc = NavajoFactory.getInstance().createNavajo();
    CompiledScriptInterface cso = null;
    try {
        cso = loadOnDemand(a, a.rpcName);
    } catch (Throwable e) {
        logger.error("Exception on getting compiledscript", e);
        if (e instanceof FileNotFoundException) {
            a.setExitCode(Access.EXIT_SCRIPT_NOT_FOUND);
        }
        throw new SystemException(-1, e.getMessage(), e);
    }
    try {
        if (cso == null) {
            if (Version.osgiActive()) {
                logger.warn("Script not found from OSGi registry while OSGi is active");
            }
            logger.error("No compiled script found, proceeding further is useless.");
            throw new RuntimeException("Can not resolve script: " + a.rpcName);
        }
        a.setOutputDoc(outDoc);
        a.setCompiledScript(cso);
        if (cso.getClassLoader() == null) {
            logger.error("No classloader present!");
        }
        cso.run(a);
        return a.getOutputDoc();
    } catch (Throwable e) {
        if (e instanceof com.dexels.navajo.mapping.BreakEvent) {
            // Outdoc might have been changed by running script
            outDoc = a.getOutputDoc();
            // Create dummy header to set breakwasset attribute.
            Header h = NavajoFactory.getInstance().createHeader(outDoc, "", "", "", -1);
            outDoc.addHeader(h);
            outDoc.getHeader().setHeaderAttribute("breakwasset", "true");
            return outDoc;
        } else if (e instanceof com.dexels.navajo.server.ConditionErrorException) {
            return ((com.dexels.navajo.server.ConditionErrorException) e).getNavajo();
        } else if (e instanceof UserException) {
            throw (UserException) e;
        }
        throw new SystemException(-1, e.getMessage(), e);
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) Navajo(com.dexels.navajo.document.Navajo) CompiledScriptInterface(com.dexels.navajo.script.api.CompiledScriptInterface) SystemException(com.dexels.navajo.script.api.SystemException) Header(com.dexels.navajo.document.Header) UserException(com.dexels.navajo.script.api.UserException)

Example 20 with Header

use of com.dexels.navajo.document.Header in project navajo by Dexels.

the class BaseDescriptionProvider method updatePropertyDescriptions.

@Override
public void updatePropertyDescriptions(Navajo in, Navajo out, Access access) throws NavajoException {
    String locale = in.getHeader().getHeaderAttribute("locale");
    if (locale == null) {
        return;
    // locale = "NL";
    }
    Header outHeader = out.getHeader();
    Header inHeader = in.getHeader();
    if (inHeader == null) {
        logger.warn("No IN header found. Thats is weird");
        return;
    } else {
        outHeader.setHeaderAttribute("locale", locale);
    }
    List<Message> a = out.getAllMessages();
    for (Iterator<Message> iter = a.iterator(); iter.hasNext(); ) {
        Message element = iter.next();
        updateMessage(in, element, locale, access.getTenant());
    }
}
Also used : Header(com.dexels.navajo.document.Header) Message(com.dexels.navajo.document.Message)

Aggregations

Header (com.dexels.navajo.document.Header)29 Navajo (com.dexels.navajo.document.Navajo)19 NavajoException (com.dexels.navajo.document.NavajoException)9 IOException (java.io.IOException)9 FatalException (com.dexels.navajo.script.api.FatalException)7 UserException (com.dexels.navajo.script.api.UserException)7 Message (com.dexels.navajo.document.Message)6 SystemException (com.dexels.navajo.script.api.SystemException)6 AuthorizationException (com.dexels.navajo.script.api.AuthorizationException)5 Property (com.dexels.navajo.document.Property)4 TriggerException (com.dexels.navajo.server.enterprise.scheduler.TriggerException)4 ClientException (com.dexels.navajo.client.ClientException)3 Access (com.dexels.navajo.script.api.Access)3 NavajoResponseHandler (com.dexels.navajo.client.NavajoResponseHandler)2 MappableException (com.dexels.navajo.script.api.MappableException)2 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2