org.tinygroup.jspengine.EmbeddedServletOptions.java Source code

Java tutorial

Introduction

Here is the source code for org.tinygroup.jspengine.EmbeddedServletOptions.java

Source

/**
 *  Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
 *
 *  Licensed under the GPL, Version 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.gnu.org/licenses/gpl.html
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.tinygroup.jspengine;

import org.tinygroup.jspengine.compiler.JspConfig;
import org.tinygroup.jspengine.compiler.Localizer;
import org.tinygroup.jspengine.compiler.TagPluginManager;
import org.tinygroup.jspengine.compiler.TldLocationsCache;
import org.tinygroup.jspengine.org.apache.commons.logging.Log;
import org.tinygroup.jspengine.org.apache.commons.logging.LogFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.io.File;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Properties;

/**
 * A class to hold all init parameters specific to the JSP engine. 
 *
 * @author Anil K. Vijendran
 * @author Hans Bergsten
 * @author Pierre Delisle
 */
public final class EmbeddedServletOptions implements Options {

    // Logger
    private static Log log = LogFactory.getLog(EmbeddedServletOptions.class);

    private Properties settings = new Properties();

    /**
     * Is Jasper being used in development mode?
     */
    private boolean development = true;

    /**
     * Should Ant fork its java compiles of JSP pages.
     */
    public boolean fork = true;

    /**
     * Do you want to keep the generated Java files around?
     */
    private boolean keepGenerated;

    /**
     * If class files are generated as byte arrays, should they be saved to
     * disk at the end of compilations?
     */
    private boolean saveBytecode = false;

    /**
     * Should white spaces between directives or actions be trimmed?
     */
    private boolean trimSpaces = false;

    /**
     * Determines whether tag handler pooling is enabled.
     */
    private boolean isPoolingEnabled = true;

    /**
     * Do you want support for "mapped" files? This will generate
     * servlet that has a print statement per line of the JSP file.
     * This seems like a really nice feature to have for debugging.
     */
    private boolean mappedFile = true;

    /**
     * Do you want stack traces and such displayed in the client's
     * browser? If this is false, such messages go to the standard
     * error or a log file if the standard error is redirected. 
     */
    private boolean sendErrorToClient = false;

    /**
     * Do we want to include debugging information in the class file?
     */
    private boolean classDebugInfo = true;

    /**
     * Background compile thread check interval in seconds.
     */
    private int checkInterval = 0;

    /**
     * Is the generation of SMAP info for JSR45 debuggin suppressed?
     */
    private boolean isSmapSuppressed = false;

    /**
     * Should SMAP info for JSR45 debugging be dumped to a file?
     */
    private boolean isSmapDumped = false;

    /**
     * Are Text strings to be generated as char arrays?
     */
    private boolean genStringAsCharArray = false;

    private boolean genStringAsByteArray = true;

    private boolean defaultBufferNone = false;

    private boolean errorOnUseBeanInvalidClassAttribute = false;

    /**
     * I want to see my generated servlets. Which directory are they
     * in?
     */
    private File scratchDir;

    /**
     * Need to have this as is for versions 4 and 5 of IE. Can be set from
     * the initParams so if it changes in the future all that is needed is
     * to have a jsp initParam of type ieClassId="<value>"
     */
    private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";

    /**
     * What classpath should I use while compiling generated servlets?
     */
    private String classpath = null;

    // START PWC 1.2 6311155
    private String sysClassPath = null;
    // END PWC 1.2 6311155

    private boolean delegate = true;

    /**
     * Compiler to use.
     */
    private String compiler = null;

    /**
     * Compiler target VM.
     */
    private String compilerTargetVM = "1.5";

    /**
     * The compiler source VM.
     */
    private String compilerSourceVM = "1.5";

    /**
     * Cache for the TLD locations
     */
    private TldLocationsCache tldLocationsCache = null;

    /**
     * Jsp config information
     */
    private JspConfig jspConfig = null;

    /**
     * TagPluginManager
     */
    private TagPluginManager tagPluginManager = null;

    /**
     * Java platform encoding to generate the JSP
     * page servlet.
     */
    private String javaEncoding = "UTF8";

    /**
     * Modification test interval.
     */
    private int modificationTestInterval = 0;

    /**
     * Is generation of X-Powered-By response header enabled/disabled?
     */
    private boolean xpoweredBy;

    // BEGIN S1AS 6181923
    private boolean usePrecompiled;
    // END S1AS 6181923

    // START SJSAS 6384538
    private boolean isValidationEnabled;
    // END SJSAS 6384538

    // START SJSWS
    /*
     * Initial capacity of HashMap which maps JSPs to their corresponding
     * servlets
     */
    private int initialCapacity = Constants.DEFAULT_INITIAL_CAPACITY;
    // END SJSWS

    public String getProperty(String name) {
        return settings.getProperty(name);
    }

    public void setProperty(String name, String value) {
        if (name != null && value != null) {
            settings.setProperty(name, value);
        }
    }

    /**
     * Are we keeping generated code around?
     */
    public boolean getKeepGenerated() {
        return keepGenerated;
    }

    public boolean getSaveBytecode() {
        return this.saveBytecode;
    }

    /**
     * Should white spaces between directives or actions be trimmed?
     */
    public boolean getTrimSpaces() {
        return trimSpaces;
    }

    public boolean isPoolingEnabled() {
        return isPoolingEnabled;
    }

    /**
     * Are we supporting HTML mapped servlets?
     */
    public boolean getMappedFile() {
        return mappedFile;
    }

    /**
     * Should errors be sent to client or thrown into stderr?
     */
    public boolean getSendErrorToClient() {
        return sendErrorToClient;
    }

    /**
     * Should class files be compiled with debug information?
     */
    public boolean getClassDebugInfo() {
        return classDebugInfo;
    }

    /**
     * Background JSP compile thread check intervall
     */
    public int getCheckInterval() {
        return checkInterval;
    }

    /**
     * Modification test interval.
     */
    public int getModificationTestInterval() {
        return modificationTestInterval;
    }

    /**
     * Is Jasper being used in development mode?
     */
    public boolean getDevelopment() {
        return development;
    }

    /**
     * Is the generation of SMAP info for JSR45 debuggin suppressed?
     */
    public boolean isSmapSuppressed() {
        return isSmapSuppressed;
    }

    /**
     * Should SMAP info for JSR45 debugging be dumped to a file?
     */
    public boolean isSmapDumped() {
        return isSmapDumped;
    }

    /**
     * Are Text strings to be generated as char arrays?
     */
    public boolean genStringAsCharArray() {
        return this.genStringAsCharArray;
    }

    public boolean genStringAsByteArray() {
        return this.genStringAsByteArray;
    }

    public boolean isDefaultBufferNone() {
        return defaultBufferNone;
    }

    /**
     * Class ID for use in the plugin tag when the browser is IE. 
     */
    public String getIeClassId() {
        return ieClassId;
    }

    /**
     * What is my scratch dir?
     */
    public File getScratchDir() {
        return scratchDir;
    }

    /**
     * What classpath should I use while compiling the servlets
     * generated from JSP files?
     */
    public String getClassPath() {
        return classpath;
    }

    // START PWC 1.2 6311155
    /**
     * Gets the system class path.
     *
     * @return The system class path
     */
    public String getSystemClassPath() {
        return sysClassPath;
    }
    // END PWC 1.2 6311155

    /**
     * Is generation of X-Powered-By response header enabled/disabled?
     */
    public boolean isXpoweredBy() {
        return xpoweredBy;
    }

    /**
     * Compiler to use.
     */
    public String getCompiler() {
        return compiler;
    }

    /**
     * @see Options#getCompilerTargetVM
     */
    public String getCompilerTargetVM() {
        return compilerTargetVM;
    }

    /**
     * @see Options#getCompilerSourceVM
     */
    public String getCompilerSourceVM() {
        return compilerSourceVM;
    }

    public boolean getErrorOnUseBeanInvalidClassAttribute() {
        return errorOnUseBeanInvalidClassAttribute;
    }

    public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
        errorOnUseBeanInvalidClassAttribute = b;
    }

    public TldLocationsCache getTldLocationsCache() {
        return tldLocationsCache;
    }

    public void setTldLocationsCache(TldLocationsCache tldC) {
        tldLocationsCache = tldC;
    }

    public String getJavaEncoding() {
        return javaEncoding;
    }

    public boolean getFork() {
        return fork;
    }

    public JspConfig getJspConfig() {
        return jspConfig;
    }

    public TagPluginManager getTagPluginManager() {
        return tagPluginManager;
    }

    // START SJSWS
    /**
     * Gets initial capacity of HashMap which maps JSPs to their corresponding
     * servlets.
     */
    public int getInitialCapacity() {
        return initialCapacity;
    }
    // END SJSWS 

    // BEGIN S1AS 6181923
    /**
     * Returns the value of the usePrecompiled (or use-precompiled) init
     * param.
     */
    public boolean getUsePrecompiled() {
        return usePrecompiled;
    }
    // END S1AS 6181923

    // START SJSAS 6384538
    public boolean isValidationEnabled() {
        return isValidationEnabled;
    }
    // END SJSAS 6384538

    public boolean isDelegate() {
        return delegate;
    }

    /**
     * Create an EmbeddedServletOptions object using data available from
     * ServletConfig and ServletContext. 
     */
    public EmbeddedServletOptions(ServletConfig config, ServletContext context) throws JasperException {

        // JVM version numbers
        try {
            if (Float.parseFloat(System.getProperty("java.specification.version")) > 1.4) {
                compilerSourceVM = compilerTargetVM = "1.5";
            } else {
                compilerSourceVM = compilerTargetVM = "1.4";
            }
        } catch (NumberFormatException e) {
            // Ignore
        }

        Enumeration enumeration = config.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String k = (String) enumeration.nextElement();
            String v = config.getInitParameter(k);
            setProperty(k, v);
        }

        /* SJSAS 6384538
        // quick hack
        String validating=config.getInitParameter( "validating");
        if( "false".equals( validating )) ParserUtils.validating=false;
        */
        // START SJSAS 6384538
        String validating = config.getInitParameter("validating");
        if ("true".equals(validating)) {
            isValidationEnabled = true;
        }
        validating = config.getInitParameter("enableTldValidation");
        if ("true".equals(validating)) {
            isValidationEnabled = true;
        }
        // END SJSAS 6384538

        // keepgenerated default is false for JDK6 for later, true otherwise
        keepGenerated = getBoolean(config, !isJDK6(), "keepgenerated");
        saveBytecode = getBoolean(config, saveBytecode, "saveBytecode");
        trimSpaces = getBoolean(config, trimSpaces, "trimSpaces");
        isPoolingEnabled = getBoolean(config, isPoolingEnabled, "enablePooling");
        mappedFile = getBoolean(config, mappedFile, "mappedfile");
        sendErrorToClient = getBoolean(config, sendErrorToClient, "sendErrToClient");
        classDebugInfo = getBoolean(config, classDebugInfo, "classdebuginfo");
        development = getBoolean(config, development, "development");
        isSmapSuppressed = getBoolean(config, isSmapSuppressed, "suppressSmap");
        isSmapDumped = getBoolean(config, isSmapDumped, "dumpSmap");
        genStringAsCharArray = getBoolean(config, genStringAsCharArray, "genStrAsCharArray");
        genStringAsByteArray = getBoolean(config, genStringAsByteArray, "genStrAsByteArray");
        defaultBufferNone = getBoolean(config, defaultBufferNone, "defaultBufferNone");
        errorOnUseBeanInvalidClassAttribute = getBoolean(config, errorOnUseBeanInvalidClassAttribute,
                "errorOnUseBeanInvalidClassAttribute");
        fork = getBoolean(config, fork, "fork");
        xpoweredBy = getBoolean(config, xpoweredBy, "xpoweredBy");

        String checkIntervalStr = config.getInitParameter("checkInterval");
        if (checkIntervalStr != null) {
            parseCheckInterval(checkIntervalStr);
        }

        String modificationTestIntervalStr = config.getInitParameter("modificationTestInterval");
        if (modificationTestIntervalStr != null) {
            parseModificationTestInterval(modificationTestIntervalStr);
        }

        String ieClassId = config.getInitParameter("ieClassId");
        if (ieClassId != null)
            this.ieClassId = ieClassId;

        String classpath = config.getInitParameter("classpath");
        if (classpath != null)
            this.classpath = classpath;

        // START PWC 1.2 6311155
        String sysClassPath = config.getInitParameter("com.sun.appserv.jsp.classpath");
        this.sysClassPath = sysClassPath != null ? sysClassPath : System.getProperty("java.class.path");

        // END PWC 1.2 6311155

        if ("false".equals(config.getInitParameter("delegate"))) {
            delegate = false;
        }

        /*
         * scratchdir
         */
        String dir = config.getInitParameter("scratchdir");
        if (dir != null) {
            scratchDir = new File(dir);
        } else {
            // First try the Servlet 2.2 javax.servlet.context.tempdir property
            scratchDir = (File) context.getAttribute(Constants.TMP_DIR);
            if (scratchDir == null) {
                // Not running in a Servlet 2.2 container.
                // Try to get the JDK 1.2 java.io.tmpdir property
                dir = System.getProperty("java.io.tmpdir");
                if (dir != null)
                    scratchDir = new File(dir);
            }
        }
        if (this.scratchDir == null) {
            log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
            return;
        }

        if (!(scratchDir.exists() && scratchDir.canRead() && scratchDir.canWrite() && scratchDir.isDirectory()))
            log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir", scratchDir.getAbsolutePath()));

        this.compiler = config.getInitParameter("compiler");

        String compilerTargetVM = config.getInitParameter("compilerTargetVM");
        if (compilerTargetVM != null) {
            this.compilerTargetVM = compilerTargetVM;
        }

        String compilerSourceVM = config.getInitParameter("compilerSourceVM");
        if (compilerSourceVM != null) {
            this.compilerSourceVM = compilerSourceVM;
        }

        String javaEncoding = config.getInitParameter("javaEncoding");
        if (javaEncoding != null) {
            this.javaEncoding = javaEncoding;
        }

        String reloadIntervalString = config.getInitParameter("reload-interval");
        if (reloadIntervalString != null) {
            int reloadInterval = 0;
            try {
                reloadInterval = Integer.parseInt(reloadIntervalString);
            } catch (NumberFormatException e) {
                if (log.isWarnEnabled()) {
                    log.warn(Localizer.getMessage("jsp.warning.reloadInterval"));
                }
            }
            if (reloadInterval == -1) {
                // Never check JSPs for modifications, and disable
                // recompilation
                this.development = false;
                this.checkInterval = 0;
            } else {
                // Check JSPs for modifications at specified interval in
                // both (development and non-development) modes
                parseCheckInterval(reloadIntervalString);
                parseModificationTestInterval(reloadIntervalString);
            }
        }

        // BEGIN S1AS 6181923
        String usePrecompiled = config.getInitParameter("usePrecompiled");
        if (usePrecompiled == null) {
            usePrecompiled = config.getInitParameter("use-precompiled");
        }
        if (usePrecompiled != null) {
            if (usePrecompiled.equalsIgnoreCase("true")) {
                this.usePrecompiled = true;
            } else if (usePrecompiled.equalsIgnoreCase("false")) {
                this.usePrecompiled = false;
            } else {
                if (log.isWarnEnabled()) {
                    log.warn(Localizer.getMessage("jsp.warning.usePrecompiled"));
                }
            }
        }
        // END S1AS 6181923

        // START SJSWS
        String capacity = config.getInitParameter("initialCapacity");
        if (capacity == null) {
            capacity = config.getInitParameter("initial-capacity");
        }
        if (capacity != null) {
            try {
                initialCapacity = Integer.parseInt(capacity);
                // Find a value that is power of 2 and >= the specified 
                // initial capacity, in order to make Hashtable indexing
                // more efficient.
                int value = Constants.DEFAULT_INITIAL_CAPACITY;
                while (value < initialCapacity) {
                    value *= 2;
                }
                initialCapacity = value;
            } catch (NumberFormatException nfe) {
                if (log.isWarnEnabled()) {
                    String msg = Localizer.getMessage("jsp.warning.initialcapacity");
                    msg = MessageFormat.format(msg, capacity, Integer.valueOf(Constants.DEFAULT_INITIAL_CAPACITY));
                    log.warn(msg);
                }
            }
        }

        String jspCompilerPlugin = config.getInitParameter("javaCompilerPlugin");
        if (jspCompilerPlugin != null) {
            if ("org.apache.jasper.compiler.JikesJavaCompiler".equals(jspCompilerPlugin)) {
                this.compiler = "jikes";
            } else if ("org.apache.jasper.compiler.SunJava14Compiler".equals(jspCompilerPlugin)) {
                // use default, do nothing
            } else {
                // use default, issue warning
                if (log.isWarnEnabled()) {
                    String msg = Localizer.getMessage("jsp.warning.unsupportedJavaCompiler");
                    msg = MessageFormat.format(msg, jspCompilerPlugin);
                    log.warn(msg);
                }
            }
        }
        // END SJSWS

        // Setup the global Tag Libraries location cache for this
        // web-application.
        /* SJSAS 6384538
        tldLocationsCache = new TldLocationsCache(context);
        */
        // START SJSAS 6384538
        tldLocationsCache = new TldLocationsCache(context, this);
        // END SJSAS 6384538

        // Setup the jsp config info for this web app.
        /* SJSAS 6384538
        jspConfig = new JspConfig(context);
        */
        // START SJSAS 6384538
        jspConfig = new JspConfig(context, this);
        // END SJSAS 6384538

        // Create a Tag plugin instance
        tagPluginManager = new TagPluginManager(context);
    }

    private void parseCheckInterval(String param) {
        try {
            this.checkInterval = Integer.parseInt(param);
        } catch (NumberFormatException ex) {
            if (log.isWarnEnabled()) {
                log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
            }
        }
    }

    private void parseModificationTestInterval(String param) {
        try {
            this.modificationTestInterval = Integer.parseInt(param);
        } catch (NumberFormatException ex) {
            if (log.isWarnEnabled()) {
                log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
            }
        }
    }

    private boolean getBoolean(ServletConfig config, boolean init, String param) {

        String sParam = config.getInitParameter(param);
        if (sParam != null) {
            if (sParam.equalsIgnoreCase("true")) {
                return true;
            }
            if (sParam.equalsIgnoreCase("false")) {
                return false;
            }
            if (log.isWarnEnabled()) {
                log.warn(Localizer.getMessage("jsp.warning.boolean", param, (init ? "true" : "false")));
            }
        }
        return init;
    }

    /*
     * returns true if running with JDK 6 or later.
     */
    private boolean isJDK6() {
        try {
            Class.forName("javax.tools.ToolProvider");
            return true;
        } catch (ClassNotFoundException ex) {
        }
        return false;
    }
}