Search in sources :

Example 1 with ApplicationListener

use of lucee.runtime.listener.ApplicationListener in project Lucee by lucee.

the class Admin method doGetApplicationListener.

private void doGetApplicationListener() throws PageException {
    Struct sct = new StructImpl();
    pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
    ApplicationListener appListener = config.getApplicationListener();
    sct.set("type", AppListenerUtil.toStringType(appListener));
    sct.set("mode", AppListenerUtil.toStringMode(appListener.getMode()));
// replaced with encoding outputsct.set("defaultencoding", config.get DefaultEncoding());
}
Also used : StructImpl(lucee.runtime.type.StructImpl) ApplicationListener(lucee.runtime.listener.ApplicationListener) Struct(lucee.runtime.type.Struct)

Example 2 with ApplicationListener

use of lucee.runtime.listener.ApplicationListener in project Lucee by lucee.

the class XMLConfigWebFactory method loadApplication.

/**
 * @param configServer
 * @param config
 * @param doc
 * @throws IOException
 * @throws PageException
 */
private static void loadApplication(ConfigServerImpl configServer, ConfigImpl config, Document doc, int mode) throws IOException, PageException {
    boolean hasCS = configServer != null;
    boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_SETTING);
    Element application = getChildByName(doc.getDocumentElement(), "application");
    Element scope = getChildByName(doc.getDocumentElement(), "scope");
    // Listener type
    ApplicationListener listener;
    if (mode == ConfigImpl.MODE_STRICT) {
        listener = new ModernAppListener();
    } else {
        listener = ConfigWebUtil.loadListener(getAttr(application, "listener-type"), null);
        if (listener == null) {
            if (hasCS && configServer.getApplicationListener() != null)
                listener = ConfigWebUtil.loadListener(configServer.getApplicationListener().getType(), null);
            if (listener == null)
                listener = new MixedAppListener();
        }
    }
    String[] strTypes = new String[] { "function", "include", "query", "resource", "http", "file", "webservice" };
    int[] types = new int[] { Config.CACHEDWITHIN_FUNCTION, Config.CACHEDWITHIN_INCLUDE, Config.CACHEDWITHIN_QUERY, Config.CACHEDWITHIN_RESOURCE, Config.CACHEDWITHIN_HTTP, Config.CACHEDWITHIN_FILE, Config.CACHEDWITHIN_WEBSERVICE };
    // cachedwithin
    for (int i = 0; i < types.length; i++) {
        String cw = getAttr(application, "cached-within-" + strTypes[i]);
        if (!StringUtil.isEmpty(cw, true))
            config.setCachedWithin(types[i], cw);
        else if (hasCS)
            config.setCachedWithin(types[i], configServer.getCachedWithin(types[i]));
    }
    // Type Checking
    Boolean typeChecking = Caster.toBoolean(getAttr(application, "type-checking"), null);
    if (typeChecking != null)
        config.setTypeChecking(typeChecking.booleanValue());
    else if (hasCS)
        config.setTypeChecking(configServer.getTypeChecking());
    // Listener Mode
    int listenerMode = ConfigWebUtil.toListenerMode(getAttr(application, "listener-mode"), -1);
    if (listenerMode == -1) {
        if (hasCS)
            listenerMode = configServer.getApplicationListener() == null ? ApplicationListener.MODE_CURRENT2ROOT : configServer.getApplicationListener().getMode();
        else
            listenerMode = ApplicationListener.MODE_CURRENT2ROOT;
    }
    listener.setMode(listenerMode);
    config.setApplicationListener(listener);
    // Req Timeout URL
    if (mode == ConfigImpl.MODE_STRICT) {
        config.setAllowURLRequestTimeout(false);
    } else {
        String allowURLReqTimeout = getAttr(application, "allow-url-requesttimeout");
        if (hasAccess && !StringUtil.isEmpty(allowURLReqTimeout)) {
            config.setAllowURLRequestTimeout(Caster.toBooleanValue(allowURLReqTimeout, false));
        } else if (hasCS)
            config.setAllowURLRequestTimeout(configServer.isAllowURLRequestTimeout());
    }
    // Req Timeout
    TimeSpan ts = null;
    if (hasAccess) {
        String reqTimeoutApplication = getAttr(application, "requesttimeout");
        // deprecated
        String reqTimeoutScope = getAttr(scope, "requesttimeout");
        if (!StringUtil.isEmpty(reqTimeoutApplication))
            ts = Caster.toTimespan(reqTimeoutApplication);
        if (ts == null && !StringUtil.isEmpty(reqTimeoutScope))
            ts = Caster.toTimespan(reqTimeoutScope);
    }
    if (ts != null && ts.getMillis() > 0)
        config.setRequestTimeout(ts);
    else if (hasCS)
        config.setRequestTimeout(configServer.getRequestTimeout());
    // script-protect
    String strScriptProtect = getAttr(application, "script-protect");
    if (hasAccess && !StringUtil.isEmpty(strScriptProtect)) {
        // print.err("sp:"+strScriptProtect);
        config.setScriptProtect(AppListenerUtil.translateScriptProtect(strScriptProtect));
    } else if (hasCS)
        config.setScriptProtect(configServer.getScriptProtect());
    // classic-date-parsing
    if (config instanceof ConfigServer) {
        if (mode == ConfigImpl.MODE_STRICT) {
            DateCaster.classicStyle = true;
        } else {
            String strClassicDateParsing = getAttr(application, "classic-date-parsing");
            if (!StringUtil.isEmpty(strClassicDateParsing)) {
                DateCaster.classicStyle = Caster.toBooleanValue(strClassicDateParsing, false);
            }
        }
    }
    // Cache
    Resource configDir = config.getConfigDir();
    String strCacheDirectory = application.getAttribute("cache-directory");
    if (hasAccess && !StringUtil.isEmpty(strCacheDirectory)) {
        strCacheDirectory = ConfigWebUtil.translateOldPath(strCacheDirectory);
        Resource res = ConfigWebUtil.getFile(configDir, strCacheDirectory, "cache", configDir, FileUtil.TYPE_DIR, config);
        config.setCacheDir(res);
    } else {
        config.setCacheDir(configDir.getRealResource("cache"));
    }
    String strMax = getAttr(application, "cache-directory-max-size");
    if (hasAccess && !StringUtil.isEmpty(strMax)) {
        config.setCacheDirSize(ByteSizeParser.parseByteSizeDefinition(strMax, config.getCacheDirSize()));
    } else if (hasCS)
        config.setCacheDirSize(configServer.getCacheDirSize());
    // admin sync
    ClassDefinition asc = getClassDefinition(application, "admin-sync-", config.getIdentification());
    if (!asc.hasClass())
        asc = getClassDefinition(application, "admin-synchronisation-", config.getIdentification());
    if (hasAccess && asc.hasClass()) {
        try {
            Class clazz = asc.getClazz();
            if (!Reflector.isInstaneOf(clazz, AdminSync.class))
                throw new ApplicationException("class [" + clazz.getName() + "] does not implement interface [" + AdminSync.class.getName() + "]");
            config.setAdminSyncClass(clazz);
        } catch (Exception e) {
            SystemOut.printDate(e);
        }
    } else if (hasCS)
        config.setAdminSyncClass(configServer.getAdminSyncClass());
}
Also used : ModernAppListener(lucee.runtime.listener.ModernAppListener) Element(org.w3c.dom.Element) Resource(lucee.commons.io.res.Resource) ClassDefinition(lucee.runtime.db.ClassDefinition) lucee.aprint(lucee.aprint) FunctionLibException(lucee.transformer.library.function.FunctionLibException) PageException(lucee.runtime.exp.PageException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityException(lucee.runtime.exp.SecurityException) TagLibException(lucee.transformer.library.tag.TagLibException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SQLException(java.sql.SQLException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) SAXException(org.xml.sax.SAXException) ClassException(lucee.commons.lang.ClassException) MalformedURLException(java.net.MalformedURLException) ExpressionException(lucee.runtime.exp.ExpressionException) ApplicationException(lucee.runtime.exp.ApplicationException) TimeSpan(lucee.runtime.type.dt.TimeSpan) ApplicationException(lucee.runtime.exp.ApplicationException) ApplicationListener(lucee.runtime.listener.ApplicationListener) CFXTagClass(lucee.runtime.cfx.customtag.CFXTagClass) CPPCFXTagClass(lucee.runtime.cfx.customtag.CPPCFXTagClass) JavaCFXTagClass(lucee.runtime.cfx.customtag.JavaCFXTagClass) MixedAppListener(lucee.runtime.listener.MixedAppListener)

Example 3 with ApplicationListener

use of lucee.runtime.listener.ApplicationListener in project Lucee by lucee.

the class PageContextImpl method executeRest.

@Override
public void executeRest(String realPath, boolean throwExcpetion) throws PageException {
    initallog();
    // config.get ApplicationListener();
    ApplicationListener listener = null;
    try {
        String pathInfo = req.getPathInfo();
        // charset
        try {
            String charset = HTTPUtil.splitMimeTypeAndCharset(req.getContentType(), new String[] { "", "" })[1];
            if (StringUtil.isEmpty(charset))
                charset = getWebCharset().name();
            java.net.URL reqURL = new java.net.URL(req.getRequestURL().toString());
            String path = ReqRspUtil.decode(reqURL.getPath(), charset, true);
            String srvPath = req.getServletPath();
            if (path.startsWith(srvPath)) {
                pathInfo = path.substring(srvPath.length());
            }
        } catch (Exception e) {
        }
        // Service mapping
        if (StringUtil.isEmpty(pathInfo) || pathInfo.equals("/")) {
            // list available services (if enabled in admin)
            if (config.getRestList()) {
                try {
                    HttpServletRequest _req = getHttpServletRequest();
                    write("Available sevice mappings are:<ul>");
                    lucee.runtime.rest.Mapping[] mappings = config.getRestMappings();
                    lucee.runtime.rest.Mapping _mapping;
                    String path;
                    for (int i = 0; i < mappings.length; i++) {
                        _mapping = mappings[i];
                        Resource p = _mapping.getPhysical();
                        path = _req.getContextPath() + ReqRspUtil.getScriptName(this, _req) + _mapping.getVirtual();
                        write("<li " + (p == null || !p.isDirectory() ? " style=\"color:red\"" : "") + ">" + path + "</li>");
                    }
                    write("</ul>");
                } catch (IOException e) {
                    throw Caster.toPageException(e);
                }
            } else
                RestUtil.setStatus(this, 404, null);
            return;
        }
        // check for matrix
        int index;
        String entry;
        Struct matrix = new StructImpl();
        while ((index = pathInfo.lastIndexOf(';')) != -1) {
            entry = pathInfo.substring(index + 1);
            pathInfo = pathInfo.substring(0, index);
            if (StringUtil.isEmpty(entry, true))
                continue;
            index = entry.indexOf('=');
            if (index != -1)
                matrix.setEL(KeyImpl.init(entry.substring(0, index).trim()), entry.substring(index + 1).trim());
            else
                matrix.setEL(KeyImpl.init(entry.trim()), "");
        }
        // get accept
        List<MimeType> accept = ReqRspUtil.getAccept(this);
        MimeType contentType = ReqRspUtil.getContentType(this);
        // check for format extension
        // int format = getApplicationContext().getRestSettings().getReturnFormat();
        int format;
        boolean hasFormatExtension = false;
        if (StringUtil.endsWithIgnoreCase(pathInfo, ".json")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_JSON;
            accept.clear();
            accept.add(MimeType.APPLICATION_JSON);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".wddx")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_WDDX;
            accept.clear();
            accept.add(MimeType.APPLICATION_WDDX);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".cfml")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_SERIALIZE;
            accept.clear();
            accept.add(MimeType.APPLICATION_CFML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".serialize")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 10);
            format = UDF.RETURN_FORMAT_SERIALIZE;
            accept.clear();
            accept.add(MimeType.APPLICATION_CFML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".xml")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 4);
            format = UDF.RETURN_FORMAT_XML;
            accept.clear();
            accept.add(MimeType.APPLICATION_XML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".java")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDFPlus.RETURN_FORMAT_JAVA;
            accept.clear();
            accept.add(MimeType.APPLICATION_JAVA);
            hasFormatExtension = true;
        } else {
            format = getApplicationContext() == null ? null : getApplicationContext().getRestSettings().getReturnFormat();
        // MimeType mt=MimeType.toMimetype(format);
        // if(mt!=null)accept.add(mt);
        }
        if (accept.size() == 0)
            accept.add(MimeType.ALL);
        // loop all mappings
        // lucee.runtime.rest.Result result = null;//config.getRestSource(pathInfo, null);
        RestRequestListener rl = null;
        lucee.runtime.rest.Mapping[] restMappings = config.getRestMappings();
        lucee.runtime.rest.Mapping m, mapping = null, defaultMapping = null;
        // String callerPath=null;
        if (restMappings != null)
            for (int i = 0; i < restMappings.length; i++) {
                m = restMappings[i];
                if (m.isDefault())
                    defaultMapping = m;
                if (pathInfo.startsWith(m.getVirtualWithSlash(), 0) && m.getPhysical() != null) {
                    mapping = m;
                    // result = m.getResult(this,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null);
                    rl = new RestRequestListener(m, pathInfo.substring(m.getVirtual().length()), matrix, format, hasFormatExtension, accept, contentType, null);
                    break;
                }
            }
        // default mapping
        if (mapping == null && defaultMapping != null && defaultMapping.getPhysical() != null) {
            mapping = defaultMapping;
            // result = mapping.getResult(this,callerPath=pathInfo,format,matrix,null);
            rl = new RestRequestListener(mapping, pathInfo, matrix, format, hasFormatExtension, accept, contentType, null);
        }
        if (mapping == null || mapping.getPhysical() == null) {
            RestUtil.setStatus(this, 404, "no rest service for [" + pathInfo + "] found");
            getConfig().getLog("rest").error("REST", "no rest service for [" + pathInfo + "] found");
        } else {
            base = config.toPageSource(null, mapping.getPhysical(), null);
            listener = ((MappingImpl) base.getMapping()).getApplicationListener();
            listener.onRequest(this, base, rl);
        }
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
        PageException pe = Caster.toPageException(t);
        if (!Abort.isSilentAbort(pe)) {
            log(true);
            if (fdEnabled) {
                FDSignal.signal(pe, false);
            }
            if (listener == null) {
                if (base == null)
                    listener = config.getApplicationListener();
                else
                    listener = ((MappingImpl) base.getMapping()).getApplicationListener();
            }
            listener.onError(this, pe);
        } else
            log(false);
        if (throwExcpetion)
            throw pe;
    } finally {
        if (enablecfoutputonly > 0) {
            setCFOutputOnly((short) 0);
        }
        base = null;
    }
}
Also used : URL(lucee.runtime.type.scope.URL) MimeType(lucee.commons.lang.mimetype.MimeType) Struct(lucee.runtime.type.Struct) HttpServletRequest(javax.servlet.http.HttpServletRequest) PageException(lucee.runtime.exp.PageException) RestRequestListener(lucee.runtime.rest.RestRequestListener) Resource(lucee.commons.io.res.Resource) IOException(java.io.IOException) PageException(lucee.runtime.exp.PageException) CasterException(lucee.runtime.exp.CasterException) MissingIncludeException(lucee.runtime.exp.MissingIncludeException) JspException(javax.servlet.jsp.JspException) IOException(java.io.IOException) CacheException(lucee.commons.io.cache.exp.CacheException) DatabaseException(lucee.runtime.exp.DatabaseException) ServletException(javax.servlet.ServletException) ModernAppListenerException(lucee.runtime.listener.ModernAppListenerException) RequestTimeoutException(lucee.runtime.exp.RequestTimeoutException) ExpressionException(lucee.runtime.exp.ExpressionException) ApplicationException(lucee.runtime.exp.ApplicationException) StructImpl(lucee.runtime.type.StructImpl) ApplicationListener(lucee.runtime.listener.ApplicationListener)

Example 4 with ApplicationListener

use of lucee.runtime.listener.ApplicationListener in project Lucee by lucee.

the class ScopeContext method clearUnusedApplications.

private void clearUnusedApplications(CFMLFactoryImpl jspFactory) {
    if (applicationContexts.size() == 0)
        return;
    long now = System.currentTimeMillis();
    Object[] arrContexts = applicationContexts.keySet().toArray();
    ApplicationListener listener = jspFactory.getConfig().getApplicationListener();
    for (int i = 0; i < arrContexts.length; i++) {
        Application application = applicationContexts.get(arrContexts[i]);
        if (application.getLastAccess() + application.getTimeSpan() < now) {
            // SystemOut .printDate(jspFactory.getConfigWebImpl().getOut(),"Clear application
            // scope:"+arrContexts[i]+"-"+this);
            application.touch();
            try {
                listener.onApplicationEnd(jspFactory, (String) arrContexts[i]);
            } catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
                ExceptionHandler.log(jspFactory.getConfig(), Caster.toPageException(t));
            } finally {
                applicationContexts.remove(arrContexts[i]);
                application.release(ThreadLocalPageContext.get());
            }
        }
    }
}
Also used : ApplicationListener(lucee.runtime.listener.ApplicationListener)

Example 5 with ApplicationListener

use of lucee.runtime.listener.ApplicationListener in project Lucee by lucee.

the class ScopeContext method clearUnusedMemoryScope.

/**
 * @param cfmlFactory
 */
private void clearUnusedMemoryScope(CFMLFactoryImpl cfmlFactory, int type) {
    Map<String, Map<String, Scope>> contexts = type == Scope.SCOPE_CLIENT ? cfClientContexts : cfSessionContexts;
    if (contexts.size() == 0)
        return;
    Object[] arrContexts = contexts.keySet().toArray();
    ApplicationListener listener = cfmlFactory.getConfig().getApplicationListener();
    Object applicationName, cfid, o;
    Map<String, Scope> fhm;
    for (int i = 0; i < arrContexts.length; i++) {
        applicationName = arrContexts[i];
        fhm = contexts.get(applicationName);
        if (fhm.size() > 0) {
            Object[] cfids = fhm.keySet().toArray();
            int count = cfids.length;
            for (int y = 0; y < cfids.length; y++) {
                cfid = cfids[y];
                o = fhm.get(cfid);
                if (!(o instanceof MemoryScope))
                    continue;
                MemoryScope scope = (MemoryScope) o;
                // close
                if (scope.isExpired()) {
                    // TODO macht das sinn? ist das nicht kopierleiche?
                    ApplicationImpl application = (ApplicationImpl) applicationContexts.get(applicationName);
                    long appLastAccess = 0;
                    if (application != null) {
                        appLastAccess = application.getLastAccess();
                        application.touch();
                    }
                    scope.touch();
                    try {
                        if (type == Scope.SCOPE_SESSION)
                            listener.onSessionEnd(cfmlFactory, (String) applicationName, (String) cfid);
                    } catch (Throwable t) {
                        ExceptionUtil.rethrowIfNecessary(t);
                        ExceptionHandler.log(cfmlFactory.getConfig(), Caster.toPageException(t));
                    } finally {
                        if (application != null)
                            application.setLastAccess(appLastAccess);
                        fhm.remove(cfids[y]);
                        scope.release(ThreadLocalPageContext.get());
                        getLog().log(Log.LEVEL_INFO, "scope-context", "remove memory based " + VariableInterpreter.scopeInt2String(type) + " scope for " + applicationName + "/" + cfid);
                        count--;
                    }
                }
            }
            if (count == 0)
                contexts.remove(arrContexts[i]);
        }
    }
}
Also used : StorageScope(lucee.runtime.type.scope.storage.StorageScope) MemoryScope(lucee.runtime.type.scope.storage.MemoryScope) ApplicationListener(lucee.runtime.listener.ApplicationListener) MemoryScope(lucee.runtime.type.scope.storage.MemoryScope) Map(java.util.Map)

Aggregations

ApplicationListener (lucee.runtime.listener.ApplicationListener)10 ApplicationException (lucee.runtime.exp.ApplicationException)4 IOException (java.io.IOException)3 ExpressionException (lucee.runtime.exp.ExpressionException)3 PageException (lucee.runtime.exp.PageException)3 ServletException (javax.servlet.ServletException)2 JspException (javax.servlet.jsp.JspException)2 lucee.aprint (lucee.aprint)2 CacheException (lucee.commons.io.cache.exp.CacheException)2 Resource (lucee.commons.io.res.Resource)2 CFMLFactoryImpl (lucee.runtime.CFMLFactoryImpl)2 CasterException (lucee.runtime.exp.CasterException)2 DatabaseException (lucee.runtime.exp.DatabaseException)2 MissingIncludeException (lucee.runtime.exp.MissingIncludeException)2 RequestTimeoutException (lucee.runtime.exp.RequestTimeoutException)2 ModernAppListener (lucee.runtime.listener.ModernAppListener)2 ModernAppListenerException (lucee.runtime.listener.ModernAppListenerException)2 Struct (lucee.runtime.type.Struct)2 StructImpl (lucee.runtime.type.StructImpl)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1