Package org.apache.cocoon.components.language.generator

Source Code of org.apache.cocoon.components.language.generator.ProgramGeneratorImpl

/*

============================================================================
                   The Apache Software License, Version 1.1
============================================================================

Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.

Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:

1. Redistributions of  source code must  retain the above copyright  notice,
    this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any, must
    include  the following  acknowledgment:  "This product includes  software
    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
    Alternately, this  acknowledgment may  appear in the software itself,  if
    and wherever such third-party acknowledgments normally appear.

4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
    used to  endorse or promote  products derived from  this software without
    prior written permission. For written permission, please contact
    apache@apache.org.

5. Products  derived from this software may not  be called "Apache", nor may
    "Apache" appear  in their name,  without prior written permission  of the
    Apache Software Foundation.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
(INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software  consists of voluntary contributions made  by many individuals
on  behalf of the Apache Software  Foundation and was  originally created by
Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
Software Foundation, please see <http://www.apache.org/>.

*/
package org.apache.cocoon.components.language.generator;

import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentSelector;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.Recomposable;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLoggable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.thread.ThreadSafe;

import org.apache.cocoon.Constants;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.classloader.ClassLoaderManager;
import org.apache.cocoon.components.language.LanguageException;
import org.apache.cocoon.components.language.markup.MarkupLanguage;
import org.apache.cocoon.components.language.programming.CodeFormatter;
import org.apache.cocoon.components.language.programming.ProgrammingLanguage;
import org.apache.cocoon.components.language.programming.Program;
import org.apache.cocoon.environment.Source;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.util.IOUtils;
import org.xml.sax.InputSource;

import java.io.File;
import java.net.MalformedURLException;

/**
* The default implementation of <code>ProgramGenerator</code>
*
* @author <a href="mailto:ricardo@apache.org">Ricardo Rocha</a>
* @author <a href="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
* @version CVS $Id: ProgramGeneratorImpl.java,v 1.15.2.1 2002/04/14 03:42:51 vgritsenko Exp $
*/
public class ProgramGeneratorImpl extends AbstractLoggable
    implements ProgramGenerator, Contextualizable, Composable, Parameterizable,
               Disposable, ThreadSafe {

    /** The auto-reloading option */
    protected boolean autoReload = false;

    /** The pre-loading option */
    protected boolean preload = false;

    /**
     * The ComponentSelector for programs. Caches Program by program
     * source file.
     */
    protected GeneratorSelector cache;

    /** The component manager */
    protected ComponentManager manager;

    /** The markup language component selector */
    protected ComponentSelector markupSelector;

    /** The programming language component selector */
    protected ComponentSelector languageSelector;

    /** The working directory */
    protected File workDir;

    /** The ClassLoaderManager */
    protected ClassLoaderManager classManager;

    /** The root package */
    protected String rootPackage;

    /** Servlet Context Directory */
    protected String contextDir;

    /** Contextualize this class */
    public void contextualize(Context context) throws ContextException {
        if (this.workDir == null) {
            this.workDir = (File) context.get(Constants.CONTEXT_WORK_DIR);
        }

        if (this.contextDir == null) {
            org.apache.cocoon.environment.Context ctx =
                (org.apache.cocoon.environment.Context) context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);

            // Determine the context directory, preferably as a file
            // FIXME (SW) - this is purposely redundant with some code in CocoonServlet
            //              to have the same rootPath. How to avoid this ?
            try {
                String rootPath = ctx.getRealPath("/");
                if (rootPath != null) {
                    this.contextDir = new File(rootPath).toURL().toExternalForm();
                } else {
                    String webInf = ctx.getResource("/WEB-INF").toExternalForm();
                    this.contextDir = webInf.substring(0, webInf.length() - "WEB-INF".length());
                }
                getLogger().debug("Context directory is " + this.contextDir);
            } catch (MalformedURLException e) {
                getLogger().warn("Could not get context directory", e);
                this.contextDir = "";
            }
        }
    }

    /**
     * Set the global component manager. This method also sets the
     * <code>ComponentSelector</code> used as language factory for both markup
     * and programming languages.
     * @param manager The global component manager
     */
    public void compose(ComponentManager manager) throws ComponentException {
        if ((this.manager == null) && (manager != null)) {
            this.manager = manager;
            this.cache = (GeneratorSelector) this.manager.lookup(GeneratorSelector.ROLE + "Selector");
            this.markupSelector = (ComponentSelector)this.manager.lookup(MarkupLanguage.ROLE + "Selector");
            this.languageSelector = (ComponentSelector)this.manager.lookup(ProgrammingLanguage.ROLE + "Selector");
            this.classManager = (ClassLoaderManager)this.manager.lookup(ClassLoaderManager.ROLE);
        }
    }

    /**
     * Set the sitemap-provided configuration. This method sets the persistent code repository and the auto-reload option
     * @param params The configuration information
     * @exception ParameterException Not thrown here
     */
    public void parameterize(Parameters params) throws ParameterException {
        this.autoReload = params.getParameterAsBoolean("auto-reload", autoReload);
        this.rootPackage = params.getParameter("root-package", "org.apache.cocoon.www");
        this.preload = params.getParameterAsBoolean("preload", preload);
    }

    /**
     * Generates program source file name in the working directory
     * from the source SystemID
     */
    private String getNormalizedName(final String systemId) {
        StringBuffer contextFilename = new StringBuffer(this.rootPackage.replace('.', File.separatorChar));
        contextFilename.append(File.separator);
        if(systemId.startsWith(this.contextDir)) {
            // VG: File is located under contextDir, using relative file name
            contextFilename.append(systemId.substring(this.contextDir.length()));
        } else {
            // VG: File is located outside of contextDir, using systemId
            contextFilename.append(systemId);
        }
        String normalizedName = IOUtils.normalizedFilename(contextFilename.toString());
        return normalizedName;
    }

    /**
     * Load a program built from an XML document written in a <code>MarkupLanguage</code>
     *
     * @param fileName The input document's <code>File</code>
     * @param markupLanguageName The <code>MarkupLanguage</code> in which the input document is written
     * @param programmingLanguageName The <code>ProgrammingLanguage</code> in which the program must be written
     * @return The loaded program instance
     * @exception Exception If an error occurs during generation or loading
     */
    public CompiledComponent load(ComponentManager newManager,
                                  String fileName,
                                  String markupLanguageName,
                                  String programmingLanguageName,
                                  SourceResolver resolver)
        throws Exception {

        final Source source = resolver.resolve(fileName);
        final String id = source.getSystemId();

        ProgrammingLanguage programmingLanguage = null;
        MarkupLanguage markupLanguage = null;
        try {
            // Create file name for the program generated from the provided source.
            final String normalizedName = getNormalizedName(id);

            // Ensure no 2 requests for the same file overlap
            Program program = null;
            CompiledComponent programInstance = null;

            // Attempt to load program object from cache
            try {
                programInstance = (CompiledComponent)this.cache.select(normalizedName);
            } catch (Exception e) {
                getLogger().debug("The instance was not accessible from the internal cache. Proceeding.");
            }

            if (programInstance == null && this.preload) {
                // Preloading: Load program if its source/[object file] is available
                try {
                    markupLanguage =
                            (MarkupLanguage)this.markupSelector.select(markupLanguageName);
                    programmingLanguage =
                            (ProgrammingLanguage)this.languageSelector.select(programmingLanguageName);
                    programmingLanguage.setLanguageName(programmingLanguageName);
                    program = programmingLanguage.preload(normalizedName,
                            this.workDir, markupLanguage.getEncoding());

                    this.cache.addGenerator(newManager, normalizedName, program);
                    programInstance = (CompiledComponent)this.cache.select(normalizedName);
                } catch (Exception e) {
                    getLogger().debug("The program was not preloaded");
                }
            }

            /*
             * FIXME: It's the program (not the instance) that must
             * be queried for changes!!!
             */
            if (programInstance != null && this.autoReload) {
                // Autoreloading: Unload program if its source is modified
                long lastModified = source.getLastModified();
                if (lastModified == 0 || programInstance.modifiedSince(lastModified)) {
                    // Release the component.
                    release(programInstance);
                    programInstance = null;

                    // Unload program
                    if (programmingLanguage == null) {
                        programmingLanguage =
                                (ProgrammingLanguage)this.languageSelector.select(programmingLanguageName);
                        programmingLanguage.setLanguageName(programmingLanguageName);
                    }

                    programmingLanguage.unload(program, normalizedName, this.workDir);
                    this.cache.removeGenerator(normalizedName);
                    program = null;
                }
            }

            // Not preloaded or just unloaded: (re)create.
            if (programInstance == null) {
                if (programmingLanguage == null) {
                    programmingLanguage =
                            (ProgrammingLanguage)this.languageSelector.select(programmingLanguageName);
                    programmingLanguage.setLanguageName(programmingLanguageName);
                }
                if (markupLanguage == null) {
                    markupLanguage =
                            (MarkupLanguage)this.markupSelector.select(markupLanguageName);
                }
                programInstance = this.createResource(newManager,
                        source, normalizedName, markupLanguage,
                        programmingLanguage, resolver);
            }

            // Recompose with the new manager if needed
            if (programInstance instanceof Recomposable) {
                ((Recomposable)programInstance).recompose(newManager);
            }
            return programInstance;
        } finally {
            source.recycle();
            this.markupSelector.release(markupLanguage);
            this.languageSelector.release(programmingLanguage);
        }
    }

    /**
     * Helper method to create resources in a threadsafe manner.
     */
    private CompiledComponent createResource(ComponentManager newManager,
                                             Source source,
                                             String normalizedName,
                                             MarkupLanguage markupLanguage,
                                             ProgrammingLanguage programmingLanguage,
                                             SourceResolver resolver)
            throws Exception {

        CompiledComponent programInstance = null;

        // Prevent 2 requests from generating this resource simultaneously
        synchronized (this) {
            // Select first. Works for threads entering this synchronized block
            // after another thread
            try {
                return (CompiledComponent)this.cache.select(normalizedName);
            } catch (Exception cme) { }

            // If failed, generate. This is for the first thread entering this block
            getLogger().debug("Creating resource " + normalizedName);
            try {
                Program program = this.generateResource(source,
                        normalizedName, markupLanguage, programmingLanguage, resolver);

                // Store generated program in cache
                this.cache.addGenerator(newManager, normalizedName, program);
            } catch (LanguageException le) {
                getLogger().debug("Language Exception", le);
                throw new ProcessingException("Language Exception", le);
            }

            // Select instance of newly generated program
            try {
                programInstance = (CompiledComponent)this.cache.select(normalizedName);
            } catch (Exception cme) {
                getLogger().debug("Can't load ServerPage", cme);
                throw new ProcessingException("Can't load ServerPage", cme);
            }
        }

        return programInstance;
    }

    /**
     * Generates Program out of Source using specified languages.
     */
    private Program generateResource(Source source,
                                     String normalizedName,
                                     MarkupLanguage markupLanguage,
                                     ProgrammingLanguage programmingLanguage,
                                     SourceResolver resolver)
            throws Exception {

        // Input Source
        // FIXME(VG): Use Source.toSAX()
        InputSource is = source.getInputSource();

        // Generate code
        String code = markupLanguage.generateCode(is, normalizedName, programmingLanguage, resolver);
        String encoding = markupLanguage.getEncoding();

        // Format source code if applicable
        CodeFormatter codeFormatter = programmingLanguage.getCodeFormatter();
        if (codeFormatter != null) {
            code = codeFormatter.format(code, encoding);
        }

        // Store generated code
        final File sourceFile = new File(this.workDir, normalizedName + "." + programmingLanguage.getSourceExtension());
        final File sourceDir = sourceFile.getParentFile();
        if (sourceDir != null) {
            sourceDir.mkdirs();
        }
        IOUtils.serializeString(sourceFile, code);

        // [Compile]/Load generated program
        Program program = programmingLanguage.load(normalizedName,
                this.workDir, markupLanguage.getEncoding());

        return program;
    }

    public void release(CompiledComponent component) {
        this.cache.release(component);
    }

    /**
     *  dispose
     */
    public void dispose() {
        this.manager.release(this.cache);
        this.cache = null;
        this.manager.release(this.markupSelector);
        this.markupSelector = null;
        this.manager.release(this.languageSelector);
        this.languageSelector = null;
        this.manager.release(this.classManager);
        this.classManager = null;

        this.manager = null;

        this.workDir = null;
        this.contextDir = null;
    }
}
TOP

Related Classes of org.apache.cocoon.components.language.generator.ProgramGeneratorImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.