Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
  * 
  * 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.apache.jasper.compiler;
 
 import static org.jboss.web.JasperMessages.MESSAGES;
 
 import java.net.URL;
 import java.util.List;
 
 
1. Processes and extracts the directive info in a tag file. 2. Compiles and loads tag files used in a JSP file.

Author(s):
Kin-man Chung
 
 
 class TagFileProcessor {
 
     private Vector tempVector;

    
A visitor the tag file
 
     private static class TagFileDirectiveVisitor extends Node.Visitor {
 
         private static final JspUtil.ValidAttribute[] tagDirectiveAttrs = {
                 new JspUtil.ValidAttribute("display-name"),
                 new JspUtil.ValidAttribute("body-content"),
                 new JspUtil.ValidAttribute("dynamic-attributes"),
                 new JspUtil.ValidAttribute("small-icon"),
                 new JspUtil.ValidAttribute("large-icon"),
                 new JspUtil.ValidAttribute("description"),
                 new JspUtil.ValidAttribute("example"),
                 new JspUtil.ValidAttribute("pageEncoding"),
                 new JspUtil.ValidAttribute("language"),
                 new JspUtil.ValidAttribute("import"),
                 new JspUtil.ValidAttribute("deferredSyntaxAllowedAsLiteral"), // JSP 2.1
                 new JspUtil.ValidAttribute("trimDirectiveWhitespaces"), // JSP 2.1
                 new JspUtil.ValidAttribute("isELIgnored") };
 
         private static final JspUtil.ValidAttribute[] attributeDirectiveAttrs = {
                 new JspUtil.ValidAttribute("name"true),
                 new JspUtil.ValidAttribute("required"),
                 new JspUtil.ValidAttribute("fragment"),
                 new JspUtil.ValidAttribute("rtexprvalue"),
                 new JspUtil.ValidAttribute("type"),
                 new JspUtil.ValidAttribute("deferredValue"),            // JSP 2.1
                 new JspUtil.ValidAttribute("deferredValueType"),        // JSP 2.1
                 new JspUtil.ValidAttribute("deferredMethod"),           // JSP 2
                 new JspUtil.ValidAttribute("deferredMethodSignature"),  // JSP 21
                 new JspUtil.ValidAttribute("description") };
 
         private static final JspUtil.ValidAttribute[] variableDirectiveAttrs = {
                 new JspUtil.ValidAttribute("name-given"),
                 new JspUtil.ValidAttribute("name-from-attribute"),
                 new JspUtil.ValidAttribute("alias"),
                 new JspUtil.ValidAttribute("variable-class"),
                 new JspUtil.ValidAttribute("scope"),
                 new JspUtil.ValidAttribute("declare"),
                 new JspUtil.ValidAttribute("description") };
 
         private ErrorDispatcher err;
 
        private TagLibraryInfo tagLibInfo;
        private String name = null;
        private String path = null;
        private TagExtraInfo tei = null;
        private String bodycontent = null;
        private String description = null;
        private String displayName = null;
        private String smallIcon = null;
        private String largeIcon = null;
        private String dynamicAttrsMapName;
        private String example = null;
        private Vector attributeVector;
        private Vector variableVector;
        private static final String ATTR_NAME = .tagFileProcessorAttrName();
        private static final String VAR_NAME_GIVEN = .tagFileProcessorVarNameGiven();
        private static final String VAR_NAME_FROM = .tagFileProcessorVarNameFrom();
        private static final String VAR_ALIAS = .tagFileProcessorVarAlias();
        private static final String TAG_DYNAMIC = .tagFileProcessorTagDynamic();
        private HashMap nameTable = new HashMap();
        private HashMap nameFromTable = new HashMap();
        public TagFileDirectiveVisitor(Compiler compiler,
                TagLibraryInfo tagLibInfoString nameString path) {
             = compiler.getErrorDispatcher();
            this. = tagLibInfo;
            this. = name;
            this. = path;
             = new Vector();
             = new Vector();
        }
        public void visit(Node.TagDirective nthrows JasperException {
             = checkConflict(n"body-content");
            if ( != null
                    && !
                            .equalsIgnoreCase(.)
                    && !
                            .equalsIgnoreCase(.)
                    && !
                            .equalsIgnoreCase(.)) {
            }
                    "dynamic-attributes");
            if ( != null) {
                checkUniqueName(n);
            }
             = checkConflict(n"small-icon");
             = checkConflict(n"large-icon");
             = checkConflict(n"description");
             = checkConflict(n"display-name");
             = checkConflict(n"example");
        }
        private String checkConflict(Node nString oldAttrValueString attr)
                throws JasperException {
            String result = oldAttrValue;
            String attrValue = n.getAttributeValue(attr);
            if (attrValue != null) {
                if (oldAttrValue != null && !oldAttrValue.equals(attrValue)) {
                    .jspError(n.getStart(), .invalidConflictingTagDirectiveAttributeValues(attr,
                            oldAttrValueattrValue));
                }
                result = attrValue;
            }
            return result;
        }
        public void visit(Node.AttributeDirective nthrows JasperException {
            JspUtil.checkAttributes(.n,
                    );
            // JSP 2.1 Table JSP.8-3
            // handle deferredValue and deferredValueType
            boolean deferredValue = false;
            boolean deferredValueSpecified = false;
            String deferredValueString = n.getAttributeValue("deferredValue");
            if (deferredValueString != null) {
                deferredValueSpecified = true;
                deferredValue = JspUtil.booleanValue(deferredValueString);
            }
            String deferredValueType = n.getAttributeValue("deferredValueType");
            if (deferredValueType != null) {
                if (deferredValueSpecified && !deferredValue) {
                    .jspError(n.getStart(), .cannotUseValueTypeWithoutDeferredValue());
                } else {
                    deferredValue = true;
                }
            } else if (deferredValue) {
                deferredValueType = "java.lang.Object";
            } else {
                deferredValueType = "java.lang.String";
            }
            // JSP 2.1 Table JSP.8-3
            // handle deferredMethod and deferredMethodSignature
            boolean deferredMethod = false;
            boolean deferredMethodSpecified = false;
            String deferredMethodString = n.getAttributeValue("deferredMethod");
            if (deferredMethodString != null) {
                deferredMethodSpecified = true;
                deferredMethod = JspUtil.booleanValue(deferredMethodString);
            }
            String deferredMethodSignature = n
                    .getAttributeValue("deferredMethodSignature");
            if (deferredMethodSignature != null) {
                if (deferredMethodSpecified && !deferredMethod) {
                    .jspError(n.getStart(), .cannotUseMethodSignatureWithoutDeferredMethod());
                } else {
                    deferredMethod = true;
                }
            } else if (deferredMethod) {
                deferredMethodSignature = "void methodname()";
            }
            if (deferredMethod && deferredValue) {
                .jspError(n.getStart(), .cannotUseBothDeferredValueAndMethod());
            }
            
            String attrName = n.getAttributeValue("name");
            boolean required = JspUtil.booleanValue(n
                    .getAttributeValue("required"));
            boolean rtexprvalue = true;
            String rtexprvalueString = n.getAttributeValue("rtexprvalue");
            if (rtexprvalueString != null) {
                rtexprvalue = JspUtil.booleanValue(rtexprvalueString);
            }
            boolean fragment = JspUtil.booleanValue(n
                    .getAttributeValue("fragment"));
            String type = n.getAttributeValue("type");
            if (fragment) {
                // type is fixed to "JspFragment" and a translation error
                // must occur if specified.
                if (type != null) {
                    .jspError(n.getStart(), .cannotUseFragmentWithType());
                }
                // rtexprvalue is fixed to "true" and a translation error
                // must occur if specified.
                rtexprvalue = true;
                if (rtexprvalueString != null) {
                    .jspError(n.getStart(), .cannotUseFragmentWithRtexprValue());
                }
            } else {
                if (type == null)
                    type = "java.lang.String";
                
                if (deferredValue) {
                    type = ValueExpression.class.getName();
                } else if (deferredMethod) {
                    type = MethodExpression.class.getName();
                }
            }
            if (("2.0".equals(.getRequiredVersion()) || ("1.2".equals(.getRequiredVersion())))
                    && (deferredMethodSpecified || deferredMethod
                            || deferredValueSpecified || deferredValue)) {
                .jspError(.invalidTagFileJspVersion());
            }
            
            TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(attrName,
                    requiredtypertexprvaluefragmentnulldeferredValue,
                    deferredMethoddeferredValueTypedeferredMethodSignature);
            .addElement(tagAttributeInfo);
            checkUniqueName(attrNamentagAttributeInfo);
        }
        public void visit(Node.VariableDirective nthrows JasperException {
            JspUtil.checkAttributes(.n,
                    );
            String nameGiven = n.getAttributeValue("name-given");
            String nameFromAttribute = n
                    .getAttributeValue("name-from-attribute");
            if (nameGiven == null && nameFromAttribute == null) {
            }
            if (nameGiven != null && nameFromAttribute != null) {
            }
            String alias = n.getAttributeValue("alias");
            if (nameFromAttribute != null && alias == null
                    || nameFromAttribute == null && alias != null) {
            }
            String className = n.getAttributeValue("variable-class");
            if (className == null)
                className = "java.lang.String";
            String declareStr = n.getAttributeValue("declare");
            boolean declare = true;
            if (declareStr != null)
                declare = JspUtil.booleanValue(declareStr);
            int scope = .;
            String scopeStr = n.getAttributeValue("scope");
            if (scopeStr != null) {
                if ("NESTED".equals(scopeStr)) {
                    // Already the default
                } else if ("AT_BEGIN".equals(scopeStr)) {
                    scope = .;
                } else if ("AT_END".equals(scopeStr)) {
                    scope = .;
                }
            }
            if (nameFromAttribute != null) {
                /*
                 * An alias has been specified. We use 'nameGiven' to hold the
                 * value of the alias, and 'nameFromAttribute' to hold the name
                 * of the attribute whose value (at invocation-time) denotes the
                 * name of the variable that is being aliased
                 */
                nameGiven = alias;
                checkUniqueName(nameFromAttributen);
                checkUniqueName(aliasn);
            } else {
                // name-given specified
                checkUniqueName(nameGivenn);
            }
            .addElement(new TagVariableInfo(nameGiven,
                    nameFromAttributeclassNamedeclarescope));
        }
        /*
         * Returns the vector of attributes corresponding to attribute
         * directives.
         */
        public Vector getAttributesVector() {
            return ;
        }
        /*
         * Returns the vector of variables corresponding to variable directives.
         */
        public Vector getVariablesVector() {
            return ;
        }
        /*
         * Returns the value of the dynamic-attributes tag directive attribute.
         */
        public String getDynamicAttributesMapName() {
            return ;
        }
        public TagInfo getTagInfo() throws JasperException {
            if ( == null) {
                // XXX Get it from tag file name
            }
            if ( == null) {
                 = .;
            }
            String tagClassName = JspUtil.getTagHandlerClassName(
                    .getReliableURN(), );
            TagVariableInfo[] tagVariableInfos = new TagVariableInfo[
                    .size()];
            .copyInto(tagVariableInfos);
            TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[
                    .size()];
            .copyInto(tagAttributeInfo);
            return new JasperTagInfo(tagClassName,
                    tagAttributeInfo,
                    tagVariableInfos,
                    );
        }
        static class NameEntry {
            private String type;
            private Node node;
            private TagAttributeInfo attr;
            NameEntry(String typeNode nodeTagAttributeInfo attr) {
                this. = type;
                this. = node;
                this. = attr;
            }
            String getType() {
                return ;
            }
            Node getNode() {
                return ;
            }
            TagAttributeInfo getTagAttributeInfo() {
                return ;
            }
        }

        
Reports a translation error if names specified in attributes of directives are not unique in this translation unit. The value of the following attributes must be unique. 1. 'name' attribute of an attribute directive 2. 'name-given' attribute of a variable directive 3. 'alias' attribute of variable directive 4. 'dynamic-attributes' of a tag directive except that 'dynamic-attributes' can (and must) have the same value when it appears in multiple tag directives. Also, 'name-from' attribute of a variable directive cannot have the same value as that from another variable directive.
        private void checkUniqueName(String nameString typeNode n)
                throws JasperException {
            checkUniqueName(nametypennull);
        }
        private void checkUniqueName(String nameString typeNode n,
                TagAttributeInfo attrthrows JasperException {
            HashMap table = (type == ) ?  : ;
            NameEntry nameEntry = (NameEntrytable.get(name);
            if (nameEntry != null) {
                if (type !=  || nameEntry.getType() != ) {
                    int line = nameEntry.getNode().getStart().getLineNumber();
                    .jspError(n.getStart(), .invalidDuplicateNames(type,
                            nameEntry.getType(), line));
                }
            } else {
                table.put(namenew NameEntry(typenattr));
            }
        }

        
Perform miscellean checks after the nodes are visited.
        void postCheck() throws JasperException {
            // Check that var.name-from-attributes has valid values.
            Iterator iter = .keySet().iterator();
            while (iter.hasNext()) {
                String nameFrom = (Stringiter.next();
                NameEntry nameEntry = (NameEntry.get(nameFrom);
                NameEntry nameFromEntry = (NameEntry
                        .get(nameFrom);
                Node nameFromNode = nameFromEntry.getNode();
                if (nameEntry == null) {
                    .jspError(nameFromNode.getStart(),
                            .cannotFindAttribute(nameFrom));
                } else {
                    Node node = nameEntry.getNode();
                    TagAttributeInfo tagAttr = nameEntry.getTagAttributeInfo();
                    if (!"java.lang.String".equals(tagAttr.getTypeName())
                            || !tagAttr.isRequired()
                            || tagAttr.canBeRequestTime()) {
                        .jspError(nameFromNode.getStart(), .invalidAttributeFound(node.getStart()
                                        .getLineNumber(), nameFrom));
                    }
                }
            }
        }
    }

    
Parses the tag file, and collects information on the directives included in it. The method is used to obtain the info on the tag file, when the handler that it represents is referenced. The tag file is not compiled here.

Deprecated:
Use parseTagFileDirectives(org.apache.jasper.compiler.ParserController,java.lang.String,java.lang.String,java.net.URL,javax.servlet.jsp.tagext.TagLibraryInfo) See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471
Parameters:
pc the current ParserController used in this compilation
name the tag name as specified in the TLD
tagfile the path for the tagfile
tagLibInfo the TagLibraryInfo object associated with this TagInfo
Returns:
a TagInfo object assembled from the directives in the tag file.
    public static TagInfo parseTagFileDirectives(ParserController pc,
            String nameString pathTagLibraryInfo tagLibInfo)
            throws JasperException {
        return parseTagFileDirectives(pcnamepath,
                pc.getJspCompilationContext().getTagFileJarUrl(path),
                tagLibInfo);
    }
    
    
Parses the tag file, and collects information on the directives included in it. The method is used to obtain the info on the tag file, when the handler that it represents is referenced. The tag file is not compiled here.

Parameters:
pc the current ParserController used in this compilation
name the tag name as specified in the TLD
tagfile the path for the tagfile
tagFileJarUrl the url for the Jar containign the tag file
tagLibInfo the TagLibraryInfo object associated with this TagInfo
Returns:
a TagInfo object assembled from the directives in the tag file.
    public static TagInfo parseTagFileDirectives(ParserController pc,
            String nameString pathURL tagFileJarUrlTagLibraryInfo tagLibInfo)
            throws JasperException {
        ErrorDispatcher err = pc.getCompiler().getErrorDispatcher();
        Node.Nodes page = null;
        try {
            page = pc.parseTagFileDirectives(pathtagFileJarUrl);
        } catch (FileNotFoundException e) {
            err.jspError(.fileNotFound(path));
        } catch (IOException e) {
            err.jspError(.fileNotFound(path));
        }
        TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor(pc
                .getCompiler(), tagLibInfonamepath);
        page.visit(tagFileVisitor);
        tagFileVisitor.postCheck();
        return tagFileVisitor.getTagInfo();
    }


    
Compiles and loads a tagfile.
    private Class loadTagFile(Compiler compilerString tagFilePath,
            TagInfo tagInfoPageInfo parentPageInfothrows JasperException {
        URL tagFileJarUrl = null;
        if (tagFilePath.startsWith("/META-INF/")) {
            try {
                String[] location = compiler.getCompilationContext().getTldLocation(tagInfo.getTagLibrary().getURI());
                URL jarUrl = compiler.getCompilationContext().getServletContext().getResource(location[0]);
                tagFileJarUrl = new URL("jar:" + jarUrl + "!/");
            } catch (MalformedURLException e) {
                // Ignore ...
            }
        }
        String tagFileJarPath;
        if (tagFileJarUrl == null) {
            tagFileJarPath = "";
        } else {
            tagFileJarPath = tagFileJarUrl.toString();
        }
        JspCompilationContext ctxt = compiler.getCompilationContext();
        JspRuntimeContext rctxt = ctxt.getRuntimeContext();
        synchronized (rctxt) {
            JspServletWrapper wrapper = rctxt.getWrapper(tagFileJarPath + tagFilePath);
            if (wrapper == null) {
                wrapper = new JspServletWrapper(ctxt.getServletContext(), ctxt
                        .getOptions(), tagFilePathtagInfoctxt
                        .getRuntimeContext(), tagFileJarUrl);
                rctxt.addWrapper(tagFileJarPath + tagFilePathwrapper);
                // Use same classloader and classpath for compiling tag files
                wrapper.getJspEngineContext().setClassLoader(ctxt.getClassLoader());
                wrapper.getJspEngineContext().setClassPath(ctxt.getClassPath());
            } else {
                // Make sure that JspCompilationContext gets the latest TagInfo
                // for the tag file. TagInfo instance was created the last
                // time the tag file was scanned for directives, and the tag
                // file may have been modified since then.
                wrapper.getJspEngineContext().setTagInfo(tagInfo);
            }
            Class tagClazz;
            int tripCount = wrapper.incTripCount();
            try {
                if (tripCount > 0) {
                    // When tripCount is greater than zero, a circular
                    // dependency exists. The circularily dependant tag
                    // file is compiled in prototype mode, to avoid infinite
                    // recursion.
                    JspServletWrapper tempWrapper = new JspServletWrapper(ctxt
                            .getServletContext(), ctxt.getOptions(),
                            tagFilePathtagInfoctxt.getRuntimeContext(),
                            ctxt.getTagFileJarUrl(tagFilePath));
                    // Use same classloader and classpath for compiling tag files
                    tempWrapper.getJspEngineContext().setClassLoader(ctxt.getClassLoader());
                    tempWrapper.getJspEngineContext().setClassPath(ctxt.getClassPath());
                    tagClazz = tempWrapper.loadTagFilePrototype();
                    .add(tempWrapper.getJspEngineContext()
                            .getCompiler());
                } else {
                    tagClazz = wrapper.loadTagFile();
                }
            } finally {
                wrapper.decTripCount();
            }
            // Add the dependants for this tag file to its parent's
            // dependant list. The only reliable dependency information
            // can only be obtained from the tag instance.
            try {
                Object tagIns = tagClazz.newInstance();
                if (tagIns instanceof JspSourceDependent) {
                    Iterator iter = ((List) ((JspSourceDependenttagIns)
                            .getDependants()).iterator();
                    while (iter.hasNext()) {
                        parentPageInfo.addDependant((Stringiter.next());
                    }
                }
            } catch (Exception e) {
                // ignore errors
            }
            return tagClazz;
        }
    }
    /*
     * Visitor which scans the page and looks for tag handlers that are tag
     * files, compiling (if necessary) and loading them.
     */
    private class TagFileLoaderVisitor extends Node.Visitor {
        private Compiler compiler;
        private PageInfo pageInfo;
        TagFileLoaderVisitor(Compiler compiler) {
            this. = compiler;
            this. = compiler.getPageInfo();
        }
        public void visit(Node.CustomTag nthrows JasperException {
            TagFileInfo tagFileInfo = n.getTagFileInfo();
            if (tagFileInfo != null) {
                String tagFilePath = tagFileInfo.getPath();
                if (tagFilePath.startsWith("/META-INF/")) {
                    // For tags in JARs, add the TLD and the tag as a dependency
                    String[] location =
                        .getCompilationContext().getTldLocation(
                                tagFileInfo.getTagInfo().getTagLibrary().getURI());
                    // Add TLD
                    .addDependant("jar:" + location[0] + "!/" +
                            location[1]);
                    // Add Tag
                    .addDependant("jar:" + location[0] + "!" +
                            tagFilePath);
                } else {
                    .addDependant(tagFilePath);
                }
                Class c = loadTagFile(tagFilePathn.getTagInfo(),
                        );
                n.setTagHandlerClass(c);
            }
            visitBody(n);
        }
    }

    
Implements a phase of the translation that compiles (if necessary) the tag files used in a JSP files. The directives in the tag files are assumed to have been proccessed and encapsulated as TagFileInfo in the CustomTag nodes.
    public void loadTagFiles(Compiler compilerNode.Nodes page)
            throws JasperException {
         = new Vector();
        page.visit(new TagFileLoaderVisitor(compiler));
    }

    
Removed the java and class files for the tag prototype generated from the current compilation.

Parameters:
classFileName If non-null, remove only the class file with with this name.
    public void removeProtoTypeFiles(String classFileName) {
        Iterator iter = .iterator();
        while (iter.hasNext()) {
            Compiler c = (Compileriter.next();
            if (classFileName == null) {
                c.removeGeneratedClassFiles();
            } else if (classFileName.equals(c.getCompilationContext()
                    .getClassFileName())) {
                c.removeGeneratedClassFiles();
                .remove(c);
                return;
            }
        }
    }
New to GrepCode? Check out our FAQ X