Search in sources :

Example 16 with LifecycleListener

use of org.apache.catalina.LifecycleListener in project tomee by apache.

the class LazyValve method instance.

private Valve instance() {
    if (delegate == null) {
        synchronized (this) {
            if (delegate == null) {
                final Object instance;
                ClassLoader cl = loader();
                if (cl == null) {
                    return null;
                }
                final Class<?> clazz;
                try {
                    clazz = cl.loadClass(delegateClassName);
                } catch (final ClassNotFoundException e) {
                    throw new TomEERuntimeException(e);
                }
                try {
                    final ObjectRecipe recipe = new ObjectRecipe(clazz);
                    recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
                    recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
                    recipe.allow(Option.FIELD_INJECTION);
                    recipe.allow(Option.PRIVATE_PROPERTIES);
                    if (properties != null) {
                        final Properties props = new PropertiesAdapter().unmarshal(properties.trim().replaceAll("\\p{Space}*(\\p{Alnum}*)=", "\n$1="));
                        recipe.setAllProperties(props);
                    }
                    instance = recipe.create();
                } catch (final Exception e) {
                    throw new TomEERuntimeException(e);
                }
                delegate = Valve.class.cast(instance);
                delegate.setNext(next);
                if (Contained.class.isInstance(delegate)) {
                    Contained.class.cast(delegate).setContainer(container);
                }
                if (Lifecycle.class.isInstance(delegate)) {
                    if (init) {
                        try {
                            final Lifecycle lifecycle = Lifecycle.class.cast(delegate);
                            for (final LifecycleListener listener : lifecycleListeners) {
                                lifecycle.addLifecycleListener(listener);
                            }
                            lifecycle.init();
                            if (start) {
                                lifecycle.start();
                            }
                        } catch (final LifecycleException e) {
                        // no-op
                        }
                    }
                }
                if (ClusterValve.class.isInstance(delegate)) {
                    ClusterValve.class.cast(delegate).setCluster(cluster);
                }
            }
        }
    }
    return delegate;
}
Also used : Contained(org.apache.catalina.Contained) LifecycleException(org.apache.catalina.LifecycleException) Lifecycle(org.apache.catalina.Lifecycle) LifecycleListener(org.apache.catalina.LifecycleListener) Properties(java.util.Properties) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) LifecycleException(org.apache.catalina.LifecycleException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) ClusterValve(org.apache.catalina.ha.ClusterValve) PropertiesAdapter(org.apache.openejb.config.sys.PropertiesAdapter) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Valve(org.apache.catalina.Valve) ClusterValve(org.apache.catalina.ha.ClusterValve)

Example 17 with LifecycleListener

use of org.apache.catalina.LifecycleListener in project tomcat by apache.

the class StandardEngineSF method storeChildren.

/**
     * Store the specified Engine properties.
     *
     * @param aWriter
     *            PrintWriter to which we are storing
     * @param indent
     *            Number of spaces to indent this element
     * @param aEngine
     *            Object whose properties are being stored
     *
     * @exception Exception
     *                if an exception occurs while storing
     */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aEngine, StoreDescription parentDesc) throws Exception {
    if (aEngine instanceof StandardEngine) {
        StandardEngine engine = (StandardEngine) aEngine;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = ((Lifecycle) engine).findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);
        // Store nested <Realm> element
        Realm realm = engine.getRealm();
        Realm parentRealm = null;
        // TODO is this case possible? (see it a old Server 5.0 impl)
        if (engine.getParent() != null) {
            parentRealm = engine.getParent().getRealm();
        }
        if (realm != parentRealm) {
            storeElement(aWriter, indent, realm);
        }
        // Store nested <Valve> elements
        Valve[] valves = engine.getPipeline().getValves();
        if (valves != null && valves.length > 0) {
            List<Valve> engineValves = new ArrayList<>();
            for (int i = 0; i < valves.length; i++) {
                if (!(valves[i] instanceof ClusterValve))
                    engineValves.add(valves[i]);
            }
            storeElementArray(aWriter, indent, engineValves.toArray());
        }
        // store all <Cluster> elements
        Cluster cluster = engine.getCluster();
        if (cluster != null) {
            storeElement(aWriter, indent, cluster);
        }
        // store all <Host> elements
        Container[] children = engine.findChildren();
        storeElementArray(aWriter, indent, children);
    }
}
Also used : Lifecycle(org.apache.catalina.Lifecycle) ArrayList(java.util.ArrayList) Cluster(org.apache.catalina.Cluster) LifecycleListener(org.apache.catalina.LifecycleListener) ClusterValve(org.apache.catalina.ha.ClusterValve) Container(org.apache.catalina.Container) StandardEngine(org.apache.catalina.core.StandardEngine) ClusterValve(org.apache.catalina.ha.ClusterValve) Valve(org.apache.catalina.Valve) Realm(org.apache.catalina.Realm)

Example 18 with LifecycleListener

use of org.apache.catalina.LifecycleListener in project tomcat by apache.

the class HostConfig method deployWAR.

/**
     * Deploy packed WAR.
     * @param cn The context name
     * @param war The WAR file
     */
protected void deployWAR(ContextName cn, File war) {
    File xml = new File(host.getAppBaseFile(), cn.getBaseName() + "/" + Constants.ApplicationContextXml);
    File warTracker = new File(host.getAppBaseFile(), cn.getBaseName() + "/" + Constants.WarTracker);
    boolean xmlInWar = false;
    try (JarFile jar = new JarFile(war)) {
        JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
        if (entry != null) {
            xmlInWar = true;
        }
    } catch (IOException e) {
    /* Ignore */
    }
    // If there is an expanded directory then any xml in that directory
    // should only be used if the directory is not out of date and
    // unpackWARs is true. Note the code below may apply further limits
    boolean useXml = false;
    // test that here
    if (xml.exists() && unpackWARs && (!warTracker.exists() || warTracker.lastModified() == war.lastModified())) {
        useXml = true;
    }
    Context context = null;
    try {
        if (deployXML && useXml && !copyXML) {
            synchronized (digesterLock) {
                try {
                    context = (Context) digester.parse(xml);
                } catch (Exception e) {
                    log.error(sm.getString("hostConfig.deployDescriptor.error", war.getAbsolutePath()), e);
                } finally {
                    digester.reset();
                    if (context == null) {
                        context = new FailedContext();
                    }
                }
            }
            context.setConfigFile(xml.toURI().toURL());
        } else if (deployXML && xmlInWar) {
            synchronized (digesterLock) {
                try (JarFile jar = new JarFile(war)) {
                    JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
                    try (InputStream istream = jar.getInputStream(entry)) {
                        context = (Context) digester.parse(istream);
                    }
                } catch (Exception e) {
                    log.error(sm.getString("hostConfig.deployDescriptor.error", war.getAbsolutePath()), e);
                } finally {
                    digester.reset();
                    if (context == null) {
                        context = new FailedContext();
                    }
                    context.setConfigFile(UriUtil.buildJarUrl(war, Constants.ApplicationContextXml));
                }
            }
        } else if (!deployXML && xmlInWar) {
            // Block deployment as META-INF/context.xml may contain security
            // configuration necessary for a secure deployment.
            log.error(sm.getString("hostConfig.deployDescriptor.blocked", cn.getPath(), Constants.ApplicationContextXml, new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml")));
        } else {
            context = (Context) Class.forName(contextClass).newInstance();
        }
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t);
    } finally {
        if (context == null) {
            context = new FailedContext();
        }
    }
    boolean copyThisXml = false;
    if (deployXML) {
        if (host instanceof StandardHost) {
            copyThisXml = ((StandardHost) host).isCopyXML();
        }
        // If Host is using default value Context can override it.
        if (!copyThisXml && context instanceof StandardContext) {
            copyThisXml = ((StandardContext) context).getCopyXML();
        }
        if (xmlInWar && copyThisXml) {
            // Change location of XML file to config base
            xml = new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml");
            try (JarFile jar = new JarFile(war)) {
                JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
                try (InputStream istream = jar.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(xml);
                    BufferedOutputStream ostream = new BufferedOutputStream(fos, 1024)) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        int n = istream.read(buffer);
                        if (n < 0) {
                            break;
                        }
                        ostream.write(buffer, 0, n);
                    }
                    ostream.flush();
                }
            } catch (IOException e) {
            /* Ignore */
            }
        }
    }
    DeployedApplication deployedApp = new DeployedApplication(cn.getName(), xml.exists() && deployXML && copyThisXml);
    long startTime = 0;
    // Deploy the application in this WAR file
    if (log.isInfoEnabled()) {
        startTime = System.currentTimeMillis();
        log.info(sm.getString("hostConfig.deployWar", war.getAbsolutePath()));
    }
    try {
        // Populate redeploy resources with the WAR file
        deployedApp.redeployResources.put(war.getAbsolutePath(), Long.valueOf(war.lastModified()));
        if (deployXML && xml.exists() && copyThisXml) {
            deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified()));
        } else {
            // In case an XML file is added to the config base later
            deployedApp.redeployResources.put((new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml")).getAbsolutePath(), Long.valueOf(0));
        }
        Class<?> clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.newInstance();
        context.addLifecycleListener(listener);
        context.setName(cn.getName());
        context.setPath(cn.getPath());
        context.setWebappVersion(cn.getVersion());
        context.setDocBase(cn.getBaseName() + ".war");
        host.addChild(context);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t);
    } finally {
        // If we're unpacking WARs, the docBase will be mutated after
        // starting the context
        boolean unpackWAR = unpackWARs;
        if (unpackWAR && context instanceof StandardContext) {
            unpackWAR = ((StandardContext) context).getUnpackWAR();
        }
        if (unpackWAR && context.getDocBase() != null) {
            File docBase = new File(host.getAppBaseFile(), cn.getBaseName());
            deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified()));
            addWatchedResources(deployedApp, docBase.getAbsolutePath(), context);
            if (deployXML && !copyThisXml && (xmlInWar || xml.exists())) {
                deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified()));
            }
        } else {
            // Passing null for docBase means that no resources will be
            // watched. This will be logged at debug level.
            addWatchedResources(deployedApp, null, context);
        }
        // Add the global redeploy resources (which are never deleted) at
        // the end so they don't interfere with the deletion process
        addGlobalRedeployResources(deployedApp);
    }
    deployed.put(cn.getName(), deployedApp);
    if (log.isInfoEnabled()) {
        log.info(sm.getString("hostConfig.deployWar.finished", war.getAbsolutePath(), Long.valueOf(System.currentTimeMillis() - startTime)));
    }
}
Also used : Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) LifecycleListener(org.apache.catalina.LifecycleListener) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) IOException(java.io.IOException) StandardHost(org.apache.catalina.core.StandardHost) StandardContext(org.apache.catalina.core.StandardContext) FileOutputStream(java.io.FileOutputStream) JarFile(java.util.jar.JarFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 19 with LifecycleListener

use of org.apache.catalina.LifecycleListener in project tomcat by apache.

the class HostConfig method deployDescriptor.

/**
     * Deploy specified context descriptor.
     * @param cn The context name
     * @param contextXml The descriptor
     */
// context is not null
@SuppressWarnings("null")
protected void deployDescriptor(ContextName cn, File contextXml) {
    DeployedApplication deployedApp = new DeployedApplication(cn.getName(), true);
    long startTime = 0;
    // Assume this is a configuration descriptor and deploy it
    if (log.isInfoEnabled()) {
        startTime = System.currentTimeMillis();
        log.info(sm.getString("hostConfig.deployDescriptor", contextXml.getAbsolutePath()));
    }
    Context context = null;
    boolean isExternalWar = false;
    boolean isExternal = false;
    File expandedDocBase = null;
    try (FileInputStream fis = new FileInputStream(contextXml)) {
        synchronized (digesterLock) {
            try {
                context = (Context) digester.parse(fis);
            } catch (Exception e) {
                log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), e);
            } finally {
                digester.reset();
                if (context == null) {
                    context = new FailedContext();
                }
            }
        }
        Class<?> clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.newInstance();
        context.addLifecycleListener(listener);
        context.setConfigFile(contextXml.toURI().toURL());
        context.setName(cn.getName());
        context.setPath(cn.getPath());
        context.setWebappVersion(cn.getVersion());
        // Add the associated docBase to the redeployed list if it's a WAR
        if (context.getDocBase() != null) {
            File docBase = new File(context.getDocBase());
            if (!docBase.isAbsolute()) {
                docBase = new File(host.getAppBaseFile(), context.getDocBase());
            }
            // If external docBase, register .xml as redeploy first
            if (!docBase.getCanonicalPath().startsWith(host.getAppBaseFile().getAbsolutePath() + File.separator)) {
                isExternal = true;
                deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified()));
                deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified()));
                if (docBase.getAbsolutePath().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                    isExternalWar = true;
                }
            } else {
                log.warn(sm.getString("hostConfig.deployDescriptor.localDocBaseSpecified", docBase));
                // Ignore specified docBase
                context.setDocBase(null);
            }
        }
        host.addChild(context);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t);
    } finally {
        // Get paths for WAR and expanded WAR in appBase
        // default to appBase dir + name
        expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName());
        if (context.getDocBase() != null && !context.getDocBase().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
            // first assume docBase is absolute
            expandedDocBase = new File(context.getDocBase());
            if (!expandedDocBase.isAbsolute()) {
                // if docBase specified and relative, it must be relative to appBase
                expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase());
            }
        }
        boolean unpackWAR = unpackWARs;
        if (unpackWAR && context instanceof StandardContext) {
            unpackWAR = ((StandardContext) context).getUnpackWAR();
        }
        // watched inside it
        if (isExternalWar) {
            if (unpackWAR) {
                deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified()));
                addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context);
            } else {
                addWatchedResources(deployedApp, null, context);
            }
        } else {
            // Find an existing matching war and expanded folder
            if (!isExternal) {
                File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war");
                if (warDocBase.exists()) {
                    deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified()));
                } else {
                    // Trigger a redeploy if a WAR is added
                    deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(0));
                }
            }
            if (unpackWAR) {
                deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified()));
                addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context);
            } else {
                addWatchedResources(deployedApp, null, context);
            }
            if (!isExternal) {
                // For external docBases, the context.xml will have been
                // added above.
                deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified()));
            }
        }
        // Add the global redeploy resources (which are never deleted) at
        // the end so they don't interfere with the deletion process
        addGlobalRedeployResources(deployedApp);
    }
    if (host.findChild(context.getName()) != null) {
        deployed.put(context.getName(), deployedApp);
    }
    if (log.isInfoEnabled()) {
        log.info(sm.getString("hostConfig.deployDescriptor.finished", contextXml.getAbsolutePath(), Long.valueOf(System.currentTimeMillis() - startTime)));
    }
}
Also used : Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) StandardContext(org.apache.catalina.core.StandardContext) LifecycleListener(org.apache.catalina.LifecycleListener) JarFile(java.util.jar.JarFile) File(java.io.File) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException)

Example 20 with LifecycleListener

use of org.apache.catalina.LifecycleListener in project tomcat by apache.

the class LifecycleListenerRule method begin.

// --------------------------------------------------------- Public Methods
/**
     * Handle the beginning of an XML element.
     *
     * @param attributes The attributes of this element
     *
     * @exception Exception if a processing error occurs
     */
@Override
public void begin(String namespace, String name, Attributes attributes) throws Exception {
    Container c = (Container) digester.peek();
    Container p = null;
    Object obj = digester.peek(1);
    if (obj instanceof Container) {
        p = (Container) obj;
    }
    String className = null;
    // Check the container for the specified attribute
    if (attributeName != null) {
        String value = attributes.getValue(attributeName);
        if (value != null)
            className = value;
    }
    // Check the container's parent for the specified attribute
    if (p != null && className == null) {
        String configClass = (String) IntrospectionUtils.getProperty(p, attributeName);
        if (configClass != null && configClass.length() > 0) {
            className = configClass;
        }
    }
    // Use the default
    if (className == null) {
        className = listenerClass;
    }
    // Instantiate a new LifecycleListener implementation object
    Class<?> clazz = Class.forName(className);
    LifecycleListener listener = (LifecycleListener) clazz.newInstance();
    // Add this LifecycleListener to our associated component
    c.addLifecycleListener(listener);
}
Also used : Container(org.apache.catalina.Container) LifecycleListener(org.apache.catalina.LifecycleListener)

Aggregations

LifecycleListener (org.apache.catalina.LifecycleListener)22 Container (org.apache.catalina.Container)6 Valve (org.apache.catalina.Valve)6 File (java.io.File)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Lifecycle (org.apache.catalina.Lifecycle)5 JarFile (java.util.jar.JarFile)4 Context (org.apache.catalina.Context)4 StandardContext (org.apache.catalina.core.StandardContext)4 Realm (org.apache.catalina.Realm)3 ClusterValve (org.apache.catalina.ha.ClusterValve)3 FileInputStream (java.io.FileInputStream)2 Cluster (org.apache.catalina.Cluster)2 LifecycleException (org.apache.catalina.LifecycleException)2 Manager (org.apache.catalina.Manager)2 Connector (org.apache.catalina.connector.Connector)2 StandardHost (org.apache.catalina.core.StandardHost)2 NamingResourcesImpl (org.apache.catalina.deploy.NamingResourcesImpl)2 BufferedOutputStream (java.io.BufferedOutputStream)1