This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch 11.0.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 663897f1150aa991fb6bd88e9720c204869a08ee Author: Mark Thomas <ma...@apache.org> AuthorDate: Fri Nov 22 22:38:31 2024 +0000 Code clean-up - formatting. No functional change. --- java/org/apache/jasper/compiler/AntCompiler.java | 54 ++-- .../apache/jasper/compiler/AttributeParser.java | 117 ++++----- .../org/apache/jasper/compiler/BeanRepository.java | 18 +- java/org/apache/jasper/compiler/Collector.java | 42 ++-- java/org/apache/jasper/compiler/Compiler.java | 186 ++++++-------- .../jasper/compiler/DefaultErrorHandler.java | 31 +-- .../apache/jasper/compiler/ELFunctionMapper.java | 61 ++--- java/org/apache/jasper/compiler/ELInterpreter.java | 32 ++- .../jasper/compiler/ELInterpreterFactory.java | 37 ++- java/org/apache/jasper/compiler/ELNode.java | 21 +- java/org/apache/jasper/compiler/ELParser.java | 97 +++---- .../apache/jasper/compiler/EncodingDetector.java | 2 +- .../apache/jasper/compiler/ErrorDispatcher.java | 280 +++++++++------------ java/org/apache/jasper/compiler/ErrorHandler.java | 40 ++- 14 files changed, 414 insertions(+), 604 deletions(-) diff --git a/java/org/apache/jasper/compiler/AntCompiler.java b/java/org/apache/jasper/compiler/AntCompiler.java index 721933f448..5484cf1445 100644 --- a/java/org/apache/jasper/compiler/AntCompiler.java +++ b/java/org/apache/jasper/compiler/AntCompiler.java @@ -75,16 +75,16 @@ public class AntCompiler extends Compiler { logger.setOutputPrintStream(System.out); logger.setErrorPrintStream(System.err); logger.setMessageOutputLevel(Project.MSG_INFO); - project.addBuildListener( logger); + project.addBuildListener(logger); if (System.getProperty(Constants.CATALINA_HOME_PROP) != null) { project.setBasedir(System.getProperty(Constants.CATALINA_HOME_PROP)); } - if( options.getCompiler() != null ) { - if( log.isTraceEnabled() ) { - log.trace("Compiler " + options.getCompiler() ); + if (options.getCompiler() != null) { + if (log.isTraceEnabled()) { + log.trace("Compiler " + options.getCompiler()); } - project.setProperty("build.compiler", options.getCompiler() ); + project.setProperty("build.compiler", options.getCompiler()); } project.init(); return project; @@ -95,9 +95,7 @@ public class AntCompiler extends Compiler { protected final StringBuilder reportBuf = new StringBuilder(); @Override - protected void printMessage(final String message, - final PrintStream stream, - final int priority) { + protected void printMessage(final String message, final PrintStream stream, final int priority) { } @Override @@ -118,7 +116,7 @@ public class AntCompiler extends Compiler { @Override protected void generateClass(Map<String,SmapStratum> smaps) - throws FileNotFoundException, JasperException, Exception { + throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { @@ -131,9 +129,9 @@ public class AntCompiler extends Compiler { StringBuilder errorReport = new StringBuilder(); - StringBuilder info=new StringBuilder(); - info.append("Compile: javaFileName=" + javaFileName + "\n" ); - info.append(" classpath=" + classpath + "\n" ); + StringBuilder info = new StringBuilder(); + info.append("Compile: javaFileName=" + javaFileName + "\n"); + info.append(" classpath=" + classpath + "\n"); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); @@ -155,8 +153,7 @@ public class AntCompiler extends Compiler { } if (log.isTraceEnabled()) { - log.trace( "Using classpath: " + System.getProperty("java.class.path") + - File.pathSeparator + classpath); + log.trace("Using classpath: " + System.getProperty("java.class.path") + File.pathSeparator + classpath); } // Initializing sourcepath @@ -181,7 +178,7 @@ public class AntCompiler extends Compiler { javac.setSrcdir(srcPath); javac.setTempdir(options.getScratchDir()); javac.setFork(ctxt.getOptions().getFork()); - info.append(" srcDir=" + srcPath + "\n" ); + info.append(" srcDir=" + srcPath + "\n"); // Set the Java compiler to use if (options.getCompiler() != null) { @@ -203,7 +200,7 @@ public class AntCompiler extends Compiler { PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); - info.append(" include="+ ctxt.getJavaPath() + "\n" ); + info.append(" include=" + ctxt.getJavaPath() + "\n"); BuildException be = null; @@ -211,7 +208,7 @@ public class AntCompiler extends Compiler { if (ctxt.getOptions().getFork()) { javac.execute(); } else { - synchronized(javacLock) { + synchronized (javacLock) { javac.execute(); } } @@ -233,16 +230,15 @@ public class AntCompiler extends Compiler { if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); if (!javaFile.delete()) { - throw new JasperException(Localizer.getMessage( - "jsp.warning.compiler.javafile.delete.fail", javaFile)); + throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile)); } } if (be != null) { String errorReportString = errorReport.toString(); log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString)); - JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors( - errorReportString, javaFileName, pageNodes); + JavacErrorDetail[] javacErrors = + ErrorDispatcher.parseJavacErrors(errorReportString, javaFileName, pageNodes); if (javacErrors != null) { errDispatcher.javacError(javacErrors); } else { @@ -250,7 +246,7 @@ public class AntCompiler extends Compiler { } } - if( log.isDebugEnabled() ) { + if (log.isDebugEnabled()) { long t2 = System.currentTimeMillis(); log.debug(Localizer.getMessage("jsp.compiled", ctxt.getServletJavaFileName(), Long.valueOf(t2 - t1))); } @@ -277,6 +273,7 @@ public class AntCompiler extends Compiler { /** * Construct the handler to capture the output of the given steam. + * * @param wrapped The wrapped stream */ public SystemLogHandler(PrintStream wrapped) { @@ -297,15 +294,13 @@ public class AntCompiler extends Compiler { /** * Thread <-> PrintStream associations. */ - protected static final ThreadLocal<PrintStream> streams = - new ThreadLocal<>(); + protected static final ThreadLocal<PrintStream> streams = new ThreadLocal<>(); /** * Thread <-> ByteArrayOutputStream associations. */ - protected static final ThreadLocal<ByteArrayOutputStream> data = - new ThreadLocal<>(); + protected static final ThreadLocal<ByteArrayOutputStream> data = new ThreadLocal<>(); // --------------------------------------------------------- Public Methods @@ -322,6 +317,7 @@ public class AntCompiler extends Compiler { /** * Stop capturing thread's output and return captured data as a String. + * * @return the captured output */ public static String unsetThread() { @@ -340,6 +336,7 @@ public class AntCompiler extends Compiler { /** * Find PrintStream to which the output must be written to. + * * @return the current stream */ protected PrintStream findStream() { @@ -371,7 +368,7 @@ public class AntCompiler extends Compiler { @Override protected void setError() { - //findStream().setError(); + // findStream().setError(); } @Override @@ -380,8 +377,7 @@ public class AntCompiler extends Compiler { } @Override - public void write(byte[] b) - throws IOException { + public void write(byte[] b) throws IOException { findStream().write(b); } diff --git a/java/org/apache/jasper/compiler/AttributeParser.java b/java/org/apache/jasper/compiler/AttributeParser.java index 50528dd0fc..48c14e1a42 100644 --- a/java/org/apache/jasper/compiler/AttributeParser.java +++ b/java/org/apache/jasper/compiler/AttributeParser.java @@ -17,40 +17,33 @@ package org.apache.jasper.compiler; /** - * Converts a JSP attribute value into the unquoted equivalent. The attribute - * may contain EL expressions, in which case care needs to be taken to avoid any - * ambiguities. For example, consider the attribute values "${1+1}" and - * "\${1+1}". After unquoting, both appear as "${1+1}" but the first should - * evaluate to "2" and the second to "${1+1}". Literal \, $ and # need special - * treatment to ensure there is no ambiguity. The JSP attribute unquoting - * covers \\, \", \', \$, \#, %\>, <\%, &apos; and &quot; + * Converts a JSP attribute value into the unquoted equivalent. The attribute may contain EL expressions, in which case + * care needs to be taken to avoid any ambiguities. For example, consider the attribute values "${1+1}" and "\${1+1}". + * After unquoting, both appear as "${1+1}" but the first should evaluate to "2" and the second to "${1+1}". Literal \, + * $ and # need special treatment to ensure there is no ambiguity. The JSP attribute unquoting covers \\, \", \', \$, + * \#, %\>, <\%, &apos; and &quot; */ public class AttributeParser { /** - * Parses the provided input String as a JSP attribute and returns an - * unquoted value. + * Parses the provided input String as a JSP attribute and returns an unquoted value. * - * @param input The input. - * @param quote The quote character for the attribute or 0 for - * scripting expressions. - * @param isELIgnored Is expression language being ignored on the page - * where the JSP attribute is defined. - * @param isDeferredSyntaxAllowedAsLiteral - * Are deferred expressions treated as literals? - * @param strict Should the rules of JSP.1.6 for escaping of quotes - * be strictly applied? - * @param quoteAttributeEL Should the rules of JSP.1.6 for escaping in - * attributes be applied to EL in attribute values? - * @return An unquoted JSP attribute that, if it contains - * expression language can be safely passed to the EL - * processor without fear of ambiguity. + * @param input The input. + * @param quote The quote character for the attribute or 0 for scripting expressions. + * @param isELIgnored Is expression language being ignored on the page where the JSP attribute + * is defined. + * @param isDeferredSyntaxAllowedAsLiteral Are deferred expressions treated as literals? + * @param strict Should the rules of JSP.1.6 for escaping of quotes be strictly applied? + * @param quoteAttributeEL Should the rules of JSP.1.6 for escaping in attributes be applied to EL + * in attribute values? + * + * @return An unquoted JSP attribute that, if it contains expression language can be safely passed to the EL + * processor without fear of ambiguity. */ - public static String getUnquoted(String input, char quote, - boolean isELIgnored, boolean isDeferredSyntaxAllowedAsLiteral, - boolean strict, boolean quoteAttributeEL) { - return new AttributeParser(input, quote, isELIgnored, - isDeferredSyntaxAllowedAsLiteral, strict, quoteAttributeEL).getUnquoted(); + public static String getUnquoted(String input, char quote, boolean isELIgnored, + boolean isDeferredSyntaxAllowedAsLiteral, boolean strict, boolean quoteAttributeEL) { + return new AttributeParser(input, quote, isELIgnored, isDeferredSyntaxAllowedAsLiteral, strict, + quoteAttributeEL).getUnquoted(); } /* The quoted input string. */ @@ -59,15 +52,17 @@ public class AttributeParser { /* The quote used for the attribute - null for scripting expressions. */ private final char quote; - /* Is expression language being ignored - affects unquoting. \$ and \# are - * treated as literals rather than quoted values. */ + /* + * Is expression language being ignored - affects unquoting. \$ and \# are treated as literals rather than quoted + * values. + */ private final boolean isELIgnored; /* Are deferred expression treated as literals */ private final boolean isDeferredSyntaxAllowedAsLiteral; - /* If a quote appears that matches quote, must it always be escaped? See - * JSP.1.6. + /* + * If a quote appears that matches quote, must it always be escaped? See JSP.1.6. */ private final boolean strict; @@ -89,14 +84,12 @@ public class AttributeParser { private final StringBuilder result; - private AttributeParser(String input, char quote, - boolean isELIgnored, boolean isDeferredSyntaxAllowedAsLiteral, + private AttributeParser(String input, char quote, boolean isELIgnored, boolean isDeferredSyntaxAllowedAsLiteral, boolean strict, boolean quoteAttributeEL) { this.input = input; this.quote = quote; this.isELIgnored = isELIgnored; - this.isDeferredSyntaxAllowedAsLiteral = - isDeferredSyntaxAllowedAsLiteral; + this.isDeferredSyntaxAllowedAsLiteral = isDeferredSyntaxAllowedAsLiteral; this.strict = strict; this.quoteAttributeEL = quoteAttributeEL; this.type = getType(input); @@ -105,8 +98,7 @@ public class AttributeParser { } /* - * Work through input looking for literals and expressions until the input - * has all been read. + * Work through input looking for literals and expressions until the input has all been read. */ private String getUnquoted() { while (i < size) { @@ -142,14 +134,14 @@ public class AttributeParser { result.append(type); result.append("{'\\\\'}"); } - } else if (!isELIgnored && ch == '$' && lastChEscaped){ + } else if (!isELIgnored && ch == '$' && lastChEscaped) { if (type == 0) { result.append("\\$"); } else { result.append(type); result.append("{'$'}"); } - } else if (!isELIgnored && ch == '#' && lastChEscaped){ + } else if (!isELIgnored && ch == '#' && lastChEscaped) { // Note if isDeferredSyntaxAllowedAsLiteral==true, \# will // not be treated as an escape if (type == 0) { @@ -158,7 +150,7 @@ public class AttributeParser { result.append(type); result.append("{'#'}"); } - } else if (ch == type){ + } else if (ch == type) { if (i < size) { char next = input.charAt(i); if (next == '{') { @@ -178,12 +170,10 @@ public class AttributeParser { } /* - * Once inside EL, no need to unquote or convert anything. The EL is - * terminated by '}'. The only other valid location for '}' is inside a - * StringLiteral. The literals are delimited by '\'' or '\"'. The only other - * valid location for '\'' or '\"' is also inside a StringLiteral. A quote - * character inside a StringLiteral must be escaped if the same quote - * character is used to delimit the StringLiteral. + * Once inside EL, no need to unquote or convert anything. The EL is terminated by '}'. The only other valid + * location for '}' is inside a StringLiteral. The literals are delimited by '\'' or '\"'. The only other valid + * location for '\'' or '\"' is also inside a StringLiteral. A quote character inside a StringLiteral must be + * escaped if the same quote character is used to delimit the StringLiteral. */ private void parseEL() { boolean endEL = false; @@ -248,14 +238,12 @@ public class AttributeParser { char ch = input.charAt(i); if (ch == '&') { - if (i + 5 < size && input.charAt(i + 1) == 'a' && - input.charAt(i + 2) == 'p' && input.charAt(i + 3) == 'o' && - input.charAt(i + 4) == 's' && input.charAt(i + 5) == ';') { + if (i + 5 < size && input.charAt(i + 1) == 'a' && input.charAt(i + 2) == 'p' && + input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 's' && input.charAt(i + 5) == ';') { ch = '\''; i += 6; - } else if (i + 5 < size && input.charAt(i + 1) == 'q' && - input.charAt(i + 2) == 'u' && input.charAt(i + 3) == 'o' && - input.charAt(i + 4) == 't' && input.charAt(i + 5) == ';') { + } else if (i + 5 < size && input.charAt(i + 1) == 'q' && input.charAt(i + 2) == 'u' && + input.charAt(i + 3) == 'o' && input.charAt(i + 4) == 't' && input.charAt(i + 5) == ';') { ch = '\"'; i += 6; } else { @@ -264,33 +252,27 @@ public class AttributeParser { } else if (ch == '\\' && i + 1 < size) { ch = input.charAt(i + 1); if (ch == '\\' || ch == '\"' || ch == '\'' || - (!isELIgnored && - (ch == '$' || - (!isDeferredSyntaxAllowedAsLiteral && - ch == '#')))) { + (!isELIgnored && (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')))) { i += 2; lastChEscaped = true; } else { ch = '\\'; ++i; } - } else if (ch == '<' && (i + 2 < size) && input.charAt(i + 1) == '\\' && - input.charAt(i + 2) == '%') { + } else if (ch == '<' && (i + 2 < size) && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '%') { // Note this is a hack since nextChar only returns a single char // It is safe since <% does not require special treatment for EL or for literals result.append('<'); - i+=3; + i += 3; return '%'; - } else if (ch == '%' && i + 2 < size && input.charAt(i + 1) == '\\' && - input.charAt(i + 2) == '>') { + } else if (ch == '%' && i + 2 < size && input.charAt(i + 1) == '\\' && input.charAt(i + 2) == '>') { // Note this is a hack since nextChar only returns a single char // It is safe since %> does not require special treatment for EL or for literals result.append('%'); - i+=3; + i += 3; return '>'; } else if (ch == quote && strict) { - String msg = Localizer.getMessage("jsp.error.attribute.noescape", - input, ""+ quote); + String msg = Localizer.getMessage("jsp.error.attribute.noescape", input, "" + quote); throw new IllegalArgumentException(msg); } else { ++i; @@ -300,8 +282,7 @@ public class AttributeParser { } /* - * Determines the type of expression by looking for the first unquoted ${ - * or #{. + * Determines the type of expression by looking for the first unquoted ${ or #{. */ private char getType(String value) { if (value == null) { @@ -322,7 +303,7 @@ public class AttributeParser { // Escape character - skip a character j++; } else if (current == '#' && !isDeferredSyntaxAllowedAsLiteral) { - if (j < (len -1) && value.charAt(j + 1) == '{') { + if (j < (len - 1) && value.charAt(j + 1) == '{') { return '#'; } } else if (current == '$') { diff --git a/java/org/apache/jasper/compiler/BeanRepository.java b/java/org/apache/jasper/compiler/BeanRepository.java index 1a28fdd656..3991773f6e 100644 --- a/java/org/apache/jasper/compiler/BeanRepository.java +++ b/java/org/apache/jasper/compiler/BeanRepository.java @@ -29,14 +29,15 @@ import org.apache.jasper.JasperException; */ public class BeanRepository { - private final HashMap<String, String> beanTypes; + private final HashMap<String,String> beanTypes; private final ClassLoader loader; private final ErrorDispatcher errDispatcher; /** * Constructor. + * * @param loader The class loader - * @param err The error dispatcher that will be used to report errors + * @param err The error dispatcher that will be used to report errors */ public BeanRepository(ClassLoader loader, ErrorDispatcher err) { this.loader = loader; @@ -44,24 +45,22 @@ public class BeanRepository { beanTypes = new HashMap<>(); } - public void addBean(Node.UseBean n, String s, String type, String scope) - throws JasperException { + public void addBean(Node.UseBean n, String s, String type, String scope) throws JasperException { - if (!(scope == null || scope.equals("page") || scope.equals("request") - || scope.equals("session") || scope.equals("application"))) { + if (!(scope == null || scope.equals("page") || scope.equals("request") || scope.equals("session") || + scope.equals("application"))) { errDispatcher.jspError(n, "jsp.error.usebean.badScope"); } beanTypes.put(s, type); } - public Class<?> getBeanType(String bean) - throws JasperException { + public Class<?> getBeanType(String bean) throws JasperException { Class<?> clazz = null; try { clazz = loader.loadClass(beanTypes.get(bean)); } catch (ClassNotFoundException ex) { - throw new JasperException (ex); + throw new JasperException(ex); } return clazz; } @@ -72,4 +71,3 @@ public class BeanRepository { } - diff --git a/java/org/apache/jasper/compiler/Collector.java b/java/org/apache/jasper/compiler/Collector.java index 58c42b82bb..e3d4a7063a 100644 --- a/java/org/apache/jasper/compiler/Collector.java +++ b/java/org/apache/jasper/compiler/Collector.java @@ -19,8 +19,7 @@ package org.apache.jasper.compiler; import org.apache.jasper.JasperException; /** - * Collect info about the page and nodes, and make them available through - * the PageInfo object. + * Collect info about the page and nodes, and make them available through the PageInfo object. * * @author Kin-man Chung * @author Mark Roth @@ -29,8 +28,7 @@ import org.apache.jasper.JasperException; class Collector { /** - * A visitor for collecting information on the page and the body of - * the custom tags. + * A visitor for collecting information on the page and the body of the custom tags. */ private static class CollectVisitor extends Node.Visitor { @@ -80,22 +78,20 @@ class Collector { scriptingElementSeen = true; } usebeanSeen = true; - visitBody(n); + visitBody(n); } @Override public void visit(Node.CustomTag n) throws JasperException { // Check to see what kinds of element we see as child elements - checkSeen( n.getChildInfo(), n ); + checkSeen(n.getChildInfo(), n); } /** - * Check all child nodes for various elements and update the given - * ChildInfo object accordingly. Visits body in the process. + * Check all child nodes for various elements and update the given ChildInfo object accordingly. Visits body in + * the process. */ - private void checkSeen( Node.ChildInfo ci, Node n ) - throws JasperException - { + private void checkSeen(Node.ChildInfo ci, Node n) throws JasperException { // save values collected so far boolean scriptingElementSeenSave = scriptingElementSeen; scriptingElementSeen = false; @@ -111,8 +107,8 @@ class Collector { hasScriptingVars = false; // Scan attribute list for expressions - if( n instanceof Node.CustomTag ) { - Node.CustomTag ct = (Node.CustomTag)n; + if (n instanceof Node.CustomTag) { + Node.CustomTag ct = (Node.CustomTag) n; Node.JspAttribute[] attrs = ct.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].isExpression()) { @@ -124,14 +120,13 @@ class Collector { visitBody(n); - if( (n instanceof Node.CustomTag) && !hasScriptingVars) { - Node.CustomTag ct = (Node.CustomTag)n; - hasScriptingVars = ct.getVariableInfos().length > 0 || - ct.getTagVariableInfos().length > 0; + if ((n instanceof Node.CustomTag) && !hasScriptingVars) { + Node.CustomTag ct = (Node.CustomTag) n; + hasScriptingVars = ct.getVariableInfos().length > 0 || ct.getTagVariableInfos().length > 0; } // Record if the tag element and its body contains any scriptlet. - ci.setScriptless(! scriptingElementSeen); + ci.setScriptless(!scriptingElementSeen); ci.setHasUseBean(usebeanSeen); ci.setHasIncludeAction(includeActionSeen); ci.setHasParamAction(paramActionSeen); @@ -165,12 +160,12 @@ class Collector { @Override public void visit(Node.JspBody n) throws JasperException { - checkSeen( n.getChildInfo(), n ); + checkSeen(n.getChildInfo(), n); } @Override public void visit(Node.NamedAttribute n) throws JasperException { - checkSeen( n.getChildInfo(), n ); + checkSeen(n.getChildInfo(), n); } @Override @@ -189,15 +184,14 @@ class Collector { } private void updatePageInfo(PageInfo pageInfo) { - pageInfo.setScriptless(! scriptingElementSeen); + pageInfo.setScriptless(!scriptingElementSeen); } } - public static void collect(Compiler compiler, Node.Nodes page) - throws JasperException { + public static void collect(Compiler compiler, Node.Nodes page) throws JasperException { - CollectVisitor collectVisitor = new CollectVisitor(); + CollectVisitor collectVisitor = new CollectVisitor(); page.visit(collectVisitor); collectVisitor.updatePageInfo(compiler.getPageInfo()); diff --git a/java/org/apache/jasper/compiler/Compiler.java b/java/org/apache/jasper/compiler/Compiler.java index 731750179f..00f6f27868 100644 --- a/java/org/apache/jasper/compiler/Compiler.java +++ b/java/org/apache/jasper/compiler/Compiler.java @@ -117,29 +117,23 @@ public abstract class Compiler { } // Setup page info area - pageInfo = new PageInfo(new BeanRepository(ctxt.getClassLoader(), - errDispatcher), ctxt); + pageInfo = new PageInfo(new BeanRepository(ctxt.getClassLoader(), errDispatcher), ctxt); JspConfig jspConfig = options.getJspConfig(); - JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(ctxt - .getJspFile()); + JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(ctxt.getJspFile()); /* - * If the current uri is matched by a pattern specified in a - * jsp-property-group in web.xml, initialize pageInfo with those - * properties. + * If the current uri is matched by a pattern specified in a jsp-property-group in web.xml, initialize pageInfo + * with those properties. */ if (jspProperty.isELIgnored() != null) { - pageInfo.setELIgnored(JspUtil.booleanValue(jspProperty - .isELIgnored())); + pageInfo.setELIgnored(JspUtil.booleanValue(jspProperty.isELIgnored())); } if (jspProperty.getErrorOnELNotFound() != null) { - pageInfo.setErrorOnELNotFound(JspUtil.booleanValue(jspProperty - .getErrorOnELNotFound())); + pageInfo.setErrorOnELNotFound(JspUtil.booleanValue(jspProperty.getErrorOnELNotFound())); } if (jspProperty.isScriptingInvalid() != null) { - pageInfo.setScriptingInvalid(JspUtil.booleanValue(jspProperty - .isScriptingInvalid())); + pageInfo.setScriptingInvalid(JspUtil.booleanValue(jspProperty.isScriptingInvalid())); } if (jspProperty.getIncludePrelude() != null) { pageInfo.setIncludePrelude(jspProperty.getIncludePrelude()); @@ -148,34 +142,28 @@ public abstract class Compiler { pageInfo.setIncludeCoda(jspProperty.getIncludeCoda()); } if (jspProperty.isDeferedSyntaxAllowedAsLiteral() != null) { - pageInfo.setDeferredSyntaxAllowedAsLiteral(JspUtil.booleanValue(jspProperty - .isDeferedSyntaxAllowedAsLiteral())); + pageInfo.setDeferredSyntaxAllowedAsLiteral( + JspUtil.booleanValue(jspProperty.isDeferedSyntaxAllowedAsLiteral())); } if (jspProperty.isTrimDirectiveWhitespaces() != null) { - pageInfo.setTrimDirectiveWhitespaces(JspUtil.booleanValue(jspProperty - .isTrimDirectiveWhitespaces())); + pageInfo.setTrimDirectiveWhitespaces(JspUtil.booleanValue(jspProperty.isTrimDirectiveWhitespaces())); } // Default ContentType processing is deferred until after the page has // been parsed if (jspProperty.getBuffer() != null) { - pageInfo.setBufferValue(jspProperty.getBuffer(), null, - errDispatcher); + pageInfo.setBufferValue(jspProperty.getBuffer(), null, errDispatcher); } if (jspProperty.isErrorOnUndeclaredNamespace() != null) { - pageInfo.setErrorOnUndeclaredNamespace( - JspUtil.booleanValue( - jspProperty.isErrorOnUndeclaredNamespace())); + pageInfo.setErrorOnUndeclaredNamespace(JspUtil.booleanValue(jspProperty.isErrorOnUndeclaredNamespace())); } if (ctxt.isTagFile()) { try { - double libraryVersion = Double.parseDouble(ctxt.getTagInfo() - .getTagLibrary().getRequiredVersion()); + double libraryVersion = Double.parseDouble(ctxt.getTagInfo().getTagLibrary().getRequiredVersion()); if (libraryVersion < 2.0) { pageInfo.setIsELIgnored("true", null, errDispatcher, true); } if (libraryVersion < 2.1) { - pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null, - errDispatcher, true); + pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null, errDispatcher, true); } } catch (NumberFormatException ex) { errDispatcher.jspError(ex); @@ -187,32 +175,26 @@ public abstract class Compiler { try { /* - * The setting of isELIgnored changes the behaviour of the parser - * in subtle ways. To add to the 'fun', isELIgnored can be set in - * any file that forms part of the translation unit so setting it - * in a file included towards the end of the translation unit can - * change how the parser should have behaved when parsing content - * up to the point where isELIgnored was set. Arghh! - * Previous attempts to hack around this have only provided partial - * solutions. We now use two passes to parse the translation unit. - * The first just parses the directives and the second parses the - * whole translation unit once we know how isELIgnored has been set. - * TODO There are some possible optimisations of this process. + * The setting of isELIgnored changes the behaviour of the parser in subtle ways. To add to the 'fun', + * isELIgnored can be set in any file that forms part of the translation unit so setting it in a file + * included towards the end of the translation unit can change how the parser should have behaved when + * parsing content up to the point where isELIgnored was set. Arghh! Previous attempts to hack around this + * have only provided partial solutions. We now use two passes to parse the translation unit. The first just + * parses the directives and the second parses the whole translation unit once we know how isELIgnored has + * been set. TODO There are some possible optimisations of this process. */ // Parse the file ParserController parserCtl = new ParserController(ctxt, this); // Pass 1 - the directives - Node.Nodes directives = - parserCtl.parseDirectives(ctxt.getJspFile()); + Node.Nodes directives = parserCtl.parseDirectives(ctxt.getJspFile()); Validator.validateDirectives(this, directives); // Pass 2 - the whole translation unit pageNodes = parserCtl.parse(ctxt.getJspFile()); // Leave this until now since it can only be set once - bug 49726 - if (pageInfo.getContentType() == null && - jspProperty.getDefaultContentType() != null) { + if (pageInfo.getContentType() == null && jspProperty.getDefaultContentType() != null) { pageInfo.setContentType(jspProperty.getDefaultContentType()); } @@ -269,8 +251,8 @@ public abstract class Compiler { if (log.isTraceEnabled()) { t4 = System.currentTimeMillis(); - log.trace("Generated " + javaFileName + " total=" + (t4 - t1) - + " generate=" + (t4 - t3) + " validate=" + (t2 - t1)); + log.trace("Generated " + javaFileName + " total=" + (t4 - t1) + " generate=" + (t4 - t3) + + " validate=" + (t2 - t1)); } } catch (RuntimeException e) { @@ -278,9 +260,7 @@ public abstract class Compiler { File file = new File(javaFileName); if (file.exists()) { if (!file.delete()) { - log.warn(Localizer.getMessage( - "jsp.warning.compiler.javafile.delete.fail", - file.getAbsolutePath())); + log.warn(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath())); } } throw e; @@ -306,19 +286,16 @@ public abstract class Compiler { return smaps; } - private ServletWriter setupContextWriter(String javaFileName) - throws FileNotFoundException, JasperException { + private ServletWriter setupContextWriter(String javaFileName) throws FileNotFoundException, JasperException { ServletWriter writer; // Setup the ServletWriter String javaEncoding = ctxt.getOptions().getJavaEncoding(); OutputStreamWriter osw = null; try { - osw = new OutputStreamWriter( - new FileOutputStream(javaFileName), javaEncoding); + osw = new OutputStreamWriter(new FileOutputStream(javaFileName), javaEncoding); } catch (UnsupportedEncodingException ex) { - errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", - javaEncoding); + errDispatcher.jspError("jsp.error.needAlternateJavaEncoding", javaEncoding); } if (ctxt.getOptions().getTrimSpaces().equals(TrimSpacesOption.EXTENDED)) { @@ -332,58 +309,52 @@ public abstract class Compiler { } /** - * Servlet compilation. This compiles the generated sources into - * Servlets. + * Servlet compilation. This compiles the generated sources into Servlets. * - * @param smaps The source maps for the class(es) generated from the source - * file + * @param smaps The source maps for the class(es) generated from the source file * * @throws FileNotFoundException Source files not found - * @throws JasperException Compilation error - * @throws Exception Some other error + * @throws JasperException Compilation error + * @throws Exception Some other error */ protected abstract void generateClass(Map<String,SmapStratum> smaps) throws FileNotFoundException, JasperException, Exception; /** * Compile the jsp file from the current engine context. + * * @throws FileNotFoundException Source files not found - * @throws JasperException Compilation error - * @throws Exception Some other error + * @throws JasperException Compilation error + * @throws Exception Some other error */ - public void compile() throws FileNotFoundException, JasperException, - Exception { + public void compile() throws FileNotFoundException, JasperException, Exception { compile(true); } /** - * Compile the jsp file from the current engine context. As an side- effect, - * tag files that are referenced by this page are also compiled. + * Compile the jsp file from the current engine context. As an side- effect, tag files that are referenced by this + * page are also compiled. + * + * @param compileClass If true, generate both .java and .class file If false, generate only .java file * - * @param compileClass - * If true, generate both .java and .class file If false, - * generate only .java file * @throws FileNotFoundException Source files not found - * @throws JasperException Compilation error - * @throws Exception Some other error + * @throws JasperException Compilation error + * @throws Exception Some other error */ - public void compile(boolean compileClass) throws FileNotFoundException, - JasperException, Exception { + public void compile(boolean compileClass) throws FileNotFoundException, JasperException, Exception { compile(compileClass, false); } /** - * Compile the jsp file from the current engine context. As an side- effect, - * tag files that are referenced by this page are also compiled. + * Compile the jsp file from the current engine context. As an side- effect, tag files that are referenced by this + * page are also compiled. + * + * @param compileClass If true, generate both .java and .class file If false, generate only .java file + * @param jspcMode true if invoked from JspC, false otherwise * - * @param compileClass - * If true, generate both .java and .class file If false, - * generate only .java file - * @param jspcMode - * true if invoked from JspC, false otherwise * @throws FileNotFoundException Source files not found - * @throws JasperException Compilation error - * @throws Exception Some other error + * @throws JasperException Compilation error + * @throws Exception Some other error */ public void compile(boolean compileClass, boolean jspcMode) throws FileNotFoundException, JasperException, Exception { @@ -405,12 +376,10 @@ public abstract class Compiler { File targetFile = new File(ctxt.getClassFileName()); if (targetFile.exists()) { if (!targetFile.setLastModified(jspLastModified.longValue())) { - throw new JasperException( - Localizer.getMessage("jsp.error.setLastModified", targetFile)); + throw new JasperException(Localizer.getMessage("jsp.error.setLastModified", targetFile)); } if (jsw != null) { - jsw.setServletClassLastModifiedTime( - jspLastModified.longValue()); + jsw.setServletClassLastModifiedTime(jspLastModified.longValue()); } } } @@ -435,34 +404,29 @@ public abstract class Compiler { } /** - * This is a protected method intended to be overridden by subclasses of - * Compiler. This is used by the compile method to do all the compilation. - * @return <code>true</code> if the source generation and compilation - * should occur + * This is a protected method intended to be overridden by subclasses of Compiler. This is used by the compile + * method to do all the compilation. + * + * @return <code>true</code> if the source generation and compilation should occur */ public boolean isOutDated() { return isOutDated(true); } /** - * Determine if a compilation is necessary by checking the time stamp of the - * JSP page with that of the corresponding .class or .java file. If the page - * has dependencies, the check is also extended to its dependents, and so - * on. This method can by overridden by a subclasses of Compiler. + * Determine if a compilation is necessary by checking the time stamp of the JSP page with that of the corresponding + * .class or .java file. If the page has dependencies, the check is also extended to its dependents, and so on. This + * method can by overridden by a subclasses of Compiler. + * + * @param checkClass If true, check against .class file, if false, check against .java file. * - * @param checkClass - * If true, check against .class file, if false, check against - * .java file. - * @return <code>true</code> if the source generation and compilation - * should occur + * @return <code>true</code> if the source generation and compilation should occur */ public boolean isOutDated(boolean checkClass) { - if (jsw != null - && (ctxt.getOptions().getModificationTestInterval() > 0)) { + if (jsw != null && (ctxt.getOptions().getModificationTestInterval() > 0)) { - if (jsw.getLastModificationTest() - + (ctxt.getOptions().getModificationTestInterval() * 1000) > System + if (jsw.getLastModificationTest() + (ctxt.getOptions().getModificationTestInterval() * 1000) > System .currentTimeMillis()) { return false; } @@ -495,8 +459,7 @@ public abstract class Compiler { if (targetLastModified != jspRealLastModified.longValue()) { if (log.isTraceEnabled()) { - log.trace("Compiler: outdated: " + targetFile + " " - + targetLastModified); + log.trace("Compiler: outdated: " + targetFile + " " + targetLastModified); } return true; } @@ -512,7 +475,7 @@ public abstract class Compiler { return false; } - for (Entry<String, Long> include : depends.entrySet()) { + for (Entry<String,Long> include : depends.entrySet()) { try { String key = include.getKey(); URL includeUrl; @@ -535,8 +498,7 @@ public abstract class Compiler { } URLConnection iuc = includeUrl.openConnection(); if (iuc instanceof JarURLConnection) { - includeLastModified = - ((JarURLConnection) iuc).getJarEntry().getTime(); + includeLastModified = ((JarURLConnection) iuc).getJarEntry().getTime(); } else { includeLastModified = iuc.getLastModified(); } @@ -589,15 +551,13 @@ public abstract class Compiler { } if (javaFile.exists()) { if (!javaFile.delete()) { - log.warn(Localizer.getMessage( - "jsp.warning.compiler.javafile.delete.fail", + log.warn(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile.getAbsolutePath())); } } } catch (Exception e) { // Remove as much as possible, log possible exceptions - log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), - e); + log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); } } @@ -609,15 +569,13 @@ public abstract class Compiler { } if (classFile.exists()) { if (!classFile.delete()) { - log.warn(Localizer.getMessage( - "jsp.warning.compiler.classfile.delete.fail", + log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail", classFile.getAbsolutePath())); } } } catch (Exception e) { // Remove as much as possible, log possible exceptions - log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), - e); + log.warn(Localizer.getMessage("jsp.warning.compiler.classfile.delete.fail.unknown"), e); } } } diff --git a/java/org/apache/jasper/compiler/DefaultErrorHandler.java b/java/org/apache/jasper/compiler/DefaultErrorHandler.java index 7ba79b9fd3..400867f5ca 100644 --- a/java/org/apache/jasper/compiler/DefaultErrorHandler.java +++ b/java/org/apache/jasper/compiler/DefaultErrorHandler.java @@ -26,12 +26,10 @@ import org.apache.jasper.JasperException; class DefaultErrorHandler implements ErrorHandler { @Override - public void jspError(String fname, int line, int column, String errMsg, - Exception ex) throws JasperException { + public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + - Localizer.getMessage("jsp.error.location", - Integer.toString(line), Integer.toString(column)) + - ") " + errMsg, ex); + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + + errMsg, ex); } @Override @@ -51,25 +49,19 @@ class DefaultErrorHandler implements ErrorHandler { for (JavacErrorDetail detail : details) { if (detail.getJspBeginLineNumber() >= 0) { - args = new Object[]{ - Integer.valueOf(detail.getJspBeginLineNumber()), - detail.getJspFileName()}; + args = new Object[] { Integer.valueOf(detail.getJspBeginLineNumber()), detail.getJspFileName() }; buf.append(System.lineSeparator()); buf.append(System.lineSeparator()); - buf.append(Localizer.getMessage("jsp.error.single.line.number", - args)); + buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(System.lineSeparator()); buf.append(detail.getErrorMessage()); buf.append(System.lineSeparator()); buf.append(detail.getJspExtract()); } else { - args = new Object[]{ - Integer.valueOf(detail.getJavaLineNumber()), - detail.getJavaFileName()}; + args = new Object[] { Integer.valueOf(detail.getJavaLineNumber()), detail.getJavaFileName() }; buf.append(System.lineSeparator()); buf.append(System.lineSeparator()); - buf.append(Localizer.getMessage("jsp.error.java.line.number", - args)); + buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(System.lineSeparator()); buf.append(detail.getErrorMessage()); } @@ -77,16 +69,13 @@ class DefaultErrorHandler implements ErrorHandler { buf.append(System.lineSeparator()); buf.append(System.lineSeparator()); buf.append("Stacktrace:"); - throw new JasperException( - Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); + throw new JasperException(Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); } @Override - public void javacError(String errorReport, Exception exception) - throws JasperException { + public void javacError(String errorReport, Exception exception) throws JasperException { - throw new JasperException( - Localizer.getMessage("jsp.error.unable.compile"), exception); + throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), exception); } } diff --git a/java/org/apache/jasper/compiler/ELFunctionMapper.java b/java/org/apache/jasper/compiler/ELFunctionMapper.java index 37d25677cc..2ff6be4c48 100644 --- a/java/org/apache/jasper/compiler/ELFunctionMapper.java +++ b/java/org/apache/jasper/compiler/ELFunctionMapper.java @@ -28,27 +28,25 @@ import jakarta.servlet.jsp.tagext.FunctionInfo; import org.apache.jasper.JasperException; /** - * This class generates functions mappers for the EL expressions in the page. - * Instead of a global mapper, a mapper is used for each call to EL - * evaluator, thus avoiding the prefix overlapping and redefinition - * issues. + * This class generates functions mappers for the EL expressions in the page. Instead of a global mapper, a mapper is + * used for each call to EL evaluator, thus avoiding the prefix overlapping and redefinition issues. * * @author Kin-man Chung */ public class ELFunctionMapper { private int currFunc = 0; - private StringBuilder ds; // Contains codes to initialize the functions mappers. - private StringBuilder ss; // Contains declarations of the functions mappers. + private StringBuilder ds; // Contains codes to initialize the functions mappers. + private StringBuilder ss; // Contains declarations of the functions mappers. /** * Creates the functions mappers for all EL expressions in the JSP page. * * @param page The current compilation unit. + * * @throws JasperException EL error */ - public static void map(Node.Nodes page) - throws JasperException { + public static void map(Node.Nodes page) throws JasperException { ELFunctionMapper map = new ELFunctionMapper(); map.ds = new StringBuilder(); @@ -62,22 +60,20 @@ public class ELFunctionMapper { Node root = page.getRoot(); @SuppressWarnings("unused") Node unused = new Node.Declaration(map.ss.toString(), null, root); - unused = new Node.Declaration( - "static {\n" + ds + "}\n", null, root); + unused = new Node.Declaration("static {\n" + ds + "}\n", null, root); } } /** - * A visitor for the page. The places where EL is allowed are scanned - * for functions, and if found functions mappers are created. + * A visitor for the page. The places where EL is allowed are scanned for functions, and if found functions mappers + * are created. */ private class ELFunctionVisitor extends Node.Visitor { /** - * Use a global name map to facilitate reuse of function maps. - * The key used is prefix:function:uri. + * Use a global name map to facilitate reuse of function maps. The key used is prefix:function:uri. */ - private final Map<String, String> gMap = new HashMap<>(); + private final Map<String,String> gMap = new HashMap<>(); @Override public void visit(Node.ParamAction n) throws JasperException { @@ -144,8 +140,7 @@ public class ELFunctionMapper { doMap(n.getEL()); } - private void doMap(Node.JspAttribute attr) - throws JasperException { + private void doMap(Node.JspAttribute attr) throws JasperException { if (attr != null) { doMap(attr.getEL()); } @@ -154,13 +149,13 @@ public class ELFunctionMapper { /** * Creates function mappers, if needed, from ELNodes */ - private void doMap(ELNode.Nodes el) - throws JasperException { + private void doMap(ELNode.Nodes el) throws JasperException { // Only care about functions in ELNode's class Fvisitor extends ELNode.Visitor { private final List<ELNode.Function> funcs = new ArrayList<>(); private final Set<String> keySet = new HashSet<>(); + @Override public void visit(ELNode.Function n) throws JasperException { String key = n.getPrefix() + ":" + n.getName(); @@ -215,10 +210,8 @@ public class ELFunctionMapper { // function mapper even if one isn't used so just pass null ds.append(funcMethod + "(null, null, null, null);\n"); } else { - ds.append(funcMethod + "(\"" + fnQName + "\", " + - getCanonicalName(funcInfo.getFunctionClass()) + - ".class, " + '\"' + f.getMethodName() + "\", " + - "new Class[] {"); + ds.append(funcMethod + "(\"" + fnQName + "\", " + getCanonicalName(funcInfo.getFunctionClass()) + + ".class, " + '\"' + f.getMethodName() + "\", " + "new Class[] {"); String params[] = f.getParameters(); for (int k = 0; k < params.length; k++) { if (k != 0) { @@ -235,7 +228,7 @@ public class ELFunctionMapper { // Count the number of array dimension int aCount = 0; - for (int jj = iArray; jj < params[k].length(); jj++ ) { + for (int jj = iArray; jj < params[k].length(); jj++) { if (params[k].charAt(jj) == '[') { aCount++; } @@ -256,19 +249,17 @@ public class ELFunctionMapper { } /** - * Find the name of the function mapper for an EL. Reuse a - * previously generated one if possible. - * @param functions A List of ELNode.Function instances that - * represents the functions in an EL - * @return A previous generated function mapper name that can be used - * by this EL; null if none found. + * Find the name of the function mapper for an EL. Reuse a previously generated one if possible. + * + * @param functions A List of ELNode.Function instances that represents the functions in an EL + * + * @return A previous generated function mapper name that can be used by this EL; null if none found. */ private String matchMap(List<ELNode.Function> functions) { String mapName = null; for (ELNode.Function f : functions) { - String temName = gMap.get(f.getPrefix() + ':' + f.getName() + - ':' + f.getUri()); + String temName = gMap.get(f.getPrefix() + ':' + f.getName() + ':' + f.getUri()); if (temName == null) { return null; } @@ -290,11 +281,11 @@ public class ELFunctionMapper { } /** - * Convert a binary class name into a canonical one that can be used - * when generating Java source code. + * Convert a binary class name into a canonical one that can be used when generating Java source code. * * @param className Binary class name - * @return Canonical equivalent + * + * @return Canonical equivalent */ private String getCanonicalName(String className) throws JasperException { Class<?> clazz; diff --git a/java/org/apache/jasper/compiler/ELInterpreter.java b/java/org/apache/jasper/compiler/ELInterpreter.java index 73b0ffb595..42b116b56d 100644 --- a/java/org/apache/jasper/compiler/ELInterpreter.java +++ b/java/org/apache/jasper/compiler/ELInterpreter.java @@ -19,28 +19,26 @@ package org.apache.jasper.compiler; import org.apache.jasper.JspCompilationContext; /** - * Defines the interface for the expression language interpreter. This allows - * users to provide custom EL interpreter implementations that can optimise - * EL processing for an application by , for example, performing code generation - * for simple expressions. + * Defines the interface for the expression language interpreter. This allows users to provide custom EL interpreter + * implementations that can optimise EL processing for an application by , for example, performing code generation for + * simple expressions. */ public interface ELInterpreter { /** - * Returns the string representing the code that will be inserted into the - * servlet generated for JSP. The default implementation creates a call to - * {@link org.apache.jasper.runtime.PageContextImpl#proprietaryEvaluate( - * String, Class, jakarta.servlet.jsp.PageContext, - * org.apache.jasper.runtime.ProtectedFunctionMapper)} but other - * implementations may produce more optimised code. - * @param context The compilation context - * @param isTagFile <code>true</code> if in a tag file rather than a JSP - * @param expression a String containing zero or more "${}" expressions + * Returns the string representing the code that will be inserted into the servlet generated for JSP. The default + * implementation creates a call to + * {@link org.apache.jasper.runtime.PageContextImpl#proprietaryEvaluate( String, Class, jakarta.servlet.jsp.PageContext, org.apache.jasper.runtime.ProtectedFunctionMapper)} + * but other implementations may produce more optimised code. + * + * @param context The compilation context + * @param isTagFile <code>true</code> if in a tag file rather than a JSP + * @param expression a String containing zero or more "${}" expressions * @param expectedType the expected type of the interpreted result - * @param fnmapvar Variable pointing to a function map. + * @param fnmapvar Variable pointing to a function map. + * * @return a String representing a call to the EL interpreter. */ - String interpreterCall(JspCompilationContext context, - boolean isTagFile, String expression, - Class<?> expectedType, String fnmapvar); + String interpreterCall(JspCompilationContext context, boolean isTagFile, String expression, Class<?> expectedType, + String fnmapvar); } diff --git a/java/org/apache/jasper/compiler/ELInterpreterFactory.java b/java/org/apache/jasper/compiler/ELInterpreterFactory.java index 30369bc79c..caeee4751b 100644 --- a/java/org/apache/jasper/compiler/ELInterpreterFactory.java +++ b/java/org/apache/jasper/compiler/ELInterpreterFactory.java @@ -21,34 +21,30 @@ import jakarta.servlet.ServletContext; import org.apache.jasper.JspCompilationContext; /** - * Provides {@link ELInterpreter} instances for JSP compilation. - * - * The search order is as follows: + * Provides {@link ELInterpreter} instances for JSP compilation. The search order is as follows: * <ol> - * <li>ELInterpreter instance or implementation class name provided as a - * ServletContext attribute</li> - * <li>Implementation class named in a ServletContext initialisation parameter - * </li> + * <li>ELInterpreter instance or implementation class name provided as a ServletContext attribute</li> + * <li>Implementation class named in a ServletContext initialisation parameter</li> * <li>Default implementation</li> * </ol> */ public class ELInterpreterFactory { - public static final String EL_INTERPRETER_CLASS_NAME = - ELInterpreter.class.getName(); + public static final String EL_INTERPRETER_CLASS_NAME = ELInterpreter.class.getName(); - private static final ELInterpreter DEFAULT_INSTANCE = - new DefaultELInterpreter(); + private static final ELInterpreter DEFAULT_INSTANCE = new DefaultELInterpreter(); /** * Obtain the correct EL Interpreter for the given web application. + * * @param context The Servlet context + * * @return the EL interpreter + * * @throws Exception If an error occurs creating the interpreter */ - public static ELInterpreter getELInterpreter(ServletContext context) - throws Exception { + public static ELInterpreter getELInterpreter(ServletContext context) throws Exception { ELInterpreter result = null; @@ -63,8 +59,7 @@ public class ELInterpreterFactory { // 2. ServletContext init parameter if (result == null) { - String className = - context.getInitParameter(EL_INTERPRETER_CLASS_NAME); + String className = context.getInitParameter(EL_INTERPRETER_CLASS_NAME); if (className != null) { result = createInstance(context, className); } @@ -81,10 +76,8 @@ public class ELInterpreterFactory { } - private static ELInterpreter createInstance(ServletContext context, - String className) throws Exception { - return (ELInterpreter) context.getClassLoader().loadClass( - className).getConstructor().newInstance(); + private static ELInterpreter createInstance(ServletContext context, String className) throws Exception { + return (ELInterpreter) context.getClassLoader().loadClass(className).getConstructor().newInstance(); } @@ -96,11 +89,9 @@ public class ELInterpreterFactory { public static class DefaultELInterpreter implements ELInterpreter { @Override - public String interpreterCall(JspCompilationContext context, - boolean isTagFile, String expression, + public String interpreterCall(JspCompilationContext context, boolean isTagFile, String expression, Class<?> expectedType, String fnmapvar) { - return JspUtil.interpreterCall(isTagFile, expression, expectedType, - fnmapvar); + return JspUtil.interpreterCall(isTagFile, expression, expectedType, fnmapvar); } } } diff --git a/java/org/apache/jasper/compiler/ELNode.java b/java/org/apache/jasper/compiler/ELNode.java index 9fe4e00216..25f218e192 100644 --- a/java/org/apache/jasper/compiler/ELNode.java +++ b/java/org/apache/jasper/compiler/ELNode.java @@ -25,10 +25,8 @@ import jakarta.servlet.jsp.tagext.FunctionInfo; import org.apache.jasper.JasperException; /** - * This class defines internal representation for an EL Expression. - * - * It currently only defines functions. It can be expanded to define - * all the components of an EL expression, if need to. + * This class defines internal representation for an EL Expression. It currently only defines functions. It can be + * expanded to define all the components of an EL expression, if need to. * * @author Kin-man Chung */ @@ -48,7 +46,7 @@ abstract class ELNode { Root(ELNode.Nodes expr, char type) { this.expr = expr; - this.type = type; + this.type = type; } @Override @@ -87,8 +85,7 @@ abstract class ELNode { } /** - * Represents anything in EL expression, other than functions, including - * function arguments etc. + * Represents anything in EL expression, other than functions, including function arguments etc. */ public static class ELText extends ELNode { @@ -109,9 +106,7 @@ abstract class ELNode { } /** - * Represents a function. - * Currently only include the prefix and function name, but not its - * arguments. + * Represents a function. Currently only include the prefix and function name, but not its arguments. */ public static class Function extends ELNode { @@ -184,10 +179,10 @@ abstract class ELNode { */ public static class Nodes { - /* Name used for creating a map for the functions in this - EL expression, for communication to Generator. + /* + * Name used for creating a map for the functions in this EL expression, for communication to Generator. */ - private String mapName = null; // The function map associated this EL + private String mapName = null; // The function map associated this EL private final List<ELNode> list; Nodes() { diff --git a/java/org/apache/jasper/compiler/ELParser.java b/java/org/apache/jasper/compiler/ELParser.java index 8f7ad93b8a..f072a7035e 100644 --- a/java/org/apache/jasper/compiler/ELParser.java +++ b/java/org/apache/jasper/compiler/ELParser.java @@ -23,19 +23,15 @@ import org.apache.jasper.compiler.ELNode.Root; import org.apache.jasper.compiler.ELNode.Text; /** - * This class implements a parser for EL expressions. - * - * It takes strings of the form xxx${..}yyy${..}zzz etc, and turn it into a - * ELNode.Nodes. - * - * Currently, it only handles text outside ${..} and functions in ${ ..}. + * This class implements a parser for EL expressions. It takes strings of the form xxx${..}yyy${..}zzz etc, and turn it + * into a ELNode.Nodes. Currently, it only handles text outside ${..} and functions in ${ ..}. * * @author Kin-man Chung */ public class ELParser { - private Token curToken; // current token + private Token curToken; // current token private Token prevToken; // previous token private String whiteSpace = ""; @@ -51,9 +47,8 @@ public class ELParser { private final boolean isDeferredSyntaxAllowedAsLiteral; - private static final String reservedWords[] = { "and", "div", "empty", - "eq", "false", "ge", "gt", "instanceof", "le", "lt", "mod", "ne", - "not", "null", "or", "true" }; + private static final String reservedWords[] = { "and", "div", "empty", "eq", "false", "ge", "gt", "instanceof", + "le", "lt", "mod", "ne", "not", "null", "or", "true" }; public ELParser(String expression, boolean isDeferredSyntaxAllowedAsLiteral) { index = 0; @@ -65,17 +60,13 @@ public class ELParser { /** * Parse an EL expression * - * @param expression - * The input expression string of the form Char* ('${' Char* - * '}')* Char* - * @param isDeferredSyntaxAllowedAsLiteral - * Are deferred expressions treated as literals? + * @param expression The input expression string of the form Char* ('${' Char* '}')* Char* + * @param isDeferredSyntaxAllowedAsLiteral Are deferred expressions treated as literals? + * * @return Parsed EL expression in ELNode.Nodes */ - public static ELNode.Nodes parse(String expression, - boolean isDeferredSyntaxAllowedAsLiteral) { - ELParser parser = new ELParser(expression, - isDeferredSyntaxAllowedAsLiteral); + public static ELNode.Nodes parse(String expression, boolean isDeferredSyntaxAllowedAsLiteral) { + ELParser parser = new ELParser(expression, isDeferredSyntaxAllowedAsLiteral); while (parser.hasNextChar()) { String text = parser.skipUntilEL(); if (text.length() > 0) { @@ -90,14 +81,10 @@ public class ELParser { } /** - * Parse an EL expression string '${...}'. Currently only separates the EL - * into functions and everything else. + * Parse an EL expression string '${...}'. Currently only separates the EL into functions and everything else. * - * @return An ELNode.Nodes representing the EL expression - * - * Note: This cannot be refactored to use the standard EL implementation as - * the EL API does not provide the level of access required to the - * parsed expression. + * @return An ELNode.Nodes representing the EL expression Note: This cannot be refactored to use the standard EL + * implementation as the EL API does not provide the level of access required to the parsed expression. */ private ELNode.Nodes parseEL() { @@ -140,9 +127,8 @@ public class ELParser { } /** - * Parse for a function FunctionInvocation ::= (identifier ':')? identifier - * '(' (Expression (,Expression)*)? ')' Note: currently we don't parse - * arguments + * Parse for a function FunctionInvocation ::= (identifier ':')? identifier '(' (Expression (,Expression)*)? ')' + * Note: currently we don't parse arguments */ private boolean parseFunction() { if (!(curToken instanceof Id) || isELReserved(curToken.toTrimmedString()) || @@ -200,8 +186,7 @@ public class ELParser { } /** - * Skip until an EL expression ('${' || '#{') is reached, allowing escape - * sequences '\$' and '\#'. + * Skip until an EL expression ('${' || '#{') is reached, allowing escape sequences '\$' and '\#'. * * @return The text string up to the EL expression */ @@ -217,8 +202,7 @@ public class ELParser { } else { buf.append(ch); } - } else if ((ch == '$' || (ch == '#' && !isDeferredSyntaxAllowedAsLiteral)) && - peek(0) == '{') { + } else if ((ch == '$' || (ch == '#' && !isDeferredSyntaxAllowedAsLiteral)) && peek(0) == '{') { this.type = ch; nextChar(); break; @@ -231,24 +215,21 @@ public class ELParser { /** - * Escape '$' and '#', inverting the unescaping performed in - * {@link #skipUntilEL()} but only for ${ and #{ sequences since escaping - * for $ and # is optional. + * Escape '$' and '#', inverting the unescaping performed in {@link #skipUntilEL()} but only for ${ and #{ sequences + * since escaping for $ and # is optional. * - * @param input Non-EL input to be escaped - * @param isDeferredSyntaxAllowedAsLiteral Flag that indicates if deferred - * syntax (#{) is allowed as a literal.\ + * @param input Non-EL input to be escaped + * @param isDeferredSyntaxAllowedAsLiteral Flag that indicates if deferred syntax (#{) is allowed as a literal.\ * * @return The escaped version of the input */ - static String escapeLiteralExpression(String input, - boolean isDeferredSyntaxAllowedAsLiteral) { + static String escapeLiteralExpression(String input, boolean isDeferredSyntaxAllowedAsLiteral) { int len = input.length(); int lastAppend = 0; StringBuilder output = null; for (int i = 0; i < len; i++) { char ch = input.charAt(i); - if (ch =='$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')) { + if (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')) { if (i + 1 < len && input.charAt(i + 1) == '{') { if (output == null) { output = new StringBuilder(len + 20); @@ -270,8 +251,7 @@ public class ELParser { /** - * Escape '\\', '\'' and '\"', inverting the unescaping performed in - * {@link #skipUntilEL()}. + * Escape '\\', '\'' and '\"', inverting the unescaping performed in {@link #skipUntilEL()}. * * @param input Non-EL input to be escaped * @@ -292,9 +272,8 @@ public class ELParser { quote = trimmed.charAt(0); if (quote == '\'' || quote == '\"') { if (trimmed.charAt(trimmedLen - 1) != quote) { - throw new IllegalArgumentException(Localizer.getMessage( - "org.apache.jasper.compiler.ELParser.invalidQuotesForStringLiteral", - input)); + throw new IllegalArgumentException(Localizer + .getMessage("org.apache.jasper.compiler.ELParser.invalidQuotesForStringLiteral", input)); } start = input.indexOf(quote) + 1; end = start + trimmedLen - 2; @@ -326,8 +305,7 @@ public class ELParser { /* - * @return true if there is something left in EL expression buffer other - * than white spaces. + * @return true if there is something left in EL expression buffer other than white spaces. */ private boolean hasNext() { skipSpaces(); @@ -341,8 +319,8 @@ public class ELParser { } /* - * Implementation note: This method assumes that it is always preceded by a - * call to hasNext() in order for whitespace handling to be correct. + * Implementation note: This method assumes that it is always preceded by a call to hasNext() in order for + * whitespace handling to be correct. * * @return The next token in the EL expression buffer. */ @@ -352,9 +330,7 @@ public class ELParser { char ch = nextChar(); if (Character.isJavaIdentifierStart(ch)) { int start = index - 1; - while (index < expression.length() && - Character.isJavaIdentifierPart( - ch = expression.charAt(index))) { + while (index < expression.length() && Character.isJavaIdentifierPart(ch = expression.charAt(index))) { nextChar(); } return new Id(getAndResetWhiteSpace(), expression.substring(start, index)); @@ -371,8 +347,7 @@ public class ELParser { } /* - * Parse a string in single or double quotes, allowing for escape sequences - * '\\', '\"' and "\'" + * Parse a string in single or double quotes, allowing for escape sequences '\\', '\"' and "\'" */ private Token parseQuotedChars(char quote) { StringBuilder buf = new StringBuilder(); @@ -384,9 +359,8 @@ public class ELParser { if (ch == '\\' || ch == '\'' || ch == '\"') { buf.append(ch); } else { - throw new IllegalArgumentException(Localizer.getMessage( - "org.apache.jasper.compiler.ELParser.invalidQuoting", - expression)); + throw new IllegalArgumentException( + Localizer.getMessage("org.apache.jasper.compiler.ELParser.invalidQuoting", expression)); } } else if (ch == quote) { buf.append(ch); @@ -399,8 +373,7 @@ public class ELParser { } /* - * A collection of low level parse methods dealing with character in the EL - * expression buffer. + * A collection of low level parse methods dealing with character in the EL expression buffer. */ private void skipSpaces() { @@ -578,7 +551,7 @@ public class ELParser { @Override public void visit(Text n) throws JasperException { - output.append(escapeLiteralExpression(n.getText(),isDeferredSyntaxAllowedAsLiteral)); + output.append(escapeLiteralExpression(n.getText(), isDeferredSyntaxAllowedAsLiteral)); } @Override diff --git a/java/org/apache/jasper/compiler/EncodingDetector.java b/java/org/apache/jasper/compiler/EncodingDetector.java index c9f53ea77e..aff864dca9 100644 --- a/java/org/apache/jasper/compiler/EncodingDetector.java +++ b/java/org/apache/jasper/compiler/EncodingDetector.java @@ -206,7 +206,7 @@ class EncodingDetector { public final String encoding; public final int skip; - BomResult(String encoding, int skip) { + BomResult(String encoding, int skip) { this.encoding = encoding; this.skip = skip; } diff --git a/java/org/apache/jasper/compiler/ErrorDispatcher.java b/java/org/apache/jasper/compiler/ErrorDispatcher.java index 50aa63991e..9de7018f02 100644 --- a/java/org/apache/jasper/compiler/ErrorDispatcher.java +++ b/java/org/apache/jasper/compiler/ErrorDispatcher.java @@ -29,15 +29,13 @@ import org.apache.jasper.JspCompilationContext; import org.xml.sax.SAXException; /** - * Class responsible for dispatching JSP parse and javac compilation errors - * to the configured error handler. + * Class responsible for dispatching JSP parse and javac compilation errors to the configured error handler. * <p> - * This class is also responsible for localizing any error codes before they - * are passed on to the configured error handler. + * This class is also responsible for localizing any error codes before they are passed on to the configured error + * handler. * <p> - * In the case of a Java compilation error, the compiler error message is - * parsed into an array of JavacErrorDetail instances, which is passed on to - * the configured error handler. + * In the case of a Java compilation error, the compiler error message is parsed into an array of JavacErrorDetail + * instances, which is passed on to the configured error handler. * * @author Jan Luehe * @author Kin-man Chung @@ -58,8 +56,7 @@ public class ErrorDispatcher { /** * Constructor. * - * @param jspcMode true if compilation has been initiated by JspC, false - * otherwise + * @param jspcMode true if compilation has been initiated by JspC, false otherwise */ public ErrorDispatcher(boolean jspcMode) { // XXX check web.xml for custom error handler @@ -68,14 +65,12 @@ public class ErrorDispatcher { } /** - * Dispatches the given JSP parse error to the configured error handler. - * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * * @param errCode Error code - * @param args Arguments for parametric replacement + * @param args Arguments for parametric replacement + * * @throws JasperException An error occurred */ public void jspError(String errCode, String... args) throws JasperException { @@ -83,36 +78,30 @@ public class ErrorDispatcher { } /** - * Dispatches the given JSP parse error to the configured error handler. - * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * - * @param where Error location + * @param where Error location * @param errCode Error code - * @param args Arguments for parametric replacement + * @param args Arguments for parametric replacement + * * @throws JasperException An error occurred */ - public void jspError(Mark where, String errCode, String... args) - throws JasperException { + public void jspError(Mark where, String errCode, String... args) throws JasperException { dispatch(where, errCode, args, null); } /** - * Dispatches the given JSP parse error to the configured error handler. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. - * - * @param n Node that caused the error + * @param n Node that caused the error * @param errCode Error code - * @param args Arguments for parametric replacement + * @param args Arguments for parametric replacement + * * @throws JasperException An error occurred */ - public void jspError(Node n, String errCode, String... args) - throws JasperException { + public void jspError(Node n, String errCode, String... args) throws JasperException { dispatch(n.getStart(), errCode, args, null); } @@ -120,6 +109,7 @@ public class ErrorDispatcher { * Dispatches the given parsing exception to the configured error handler. * * @param e Parsing exception + * * @throws JasperException An error occurred */ public void jspError(Exception e) throws JasperException { @@ -127,124 +117,108 @@ public class ErrorDispatcher { } /** - * Dispatches the given JSP parse error to the configured error handler. - * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * * @param errCode Error code - * @param args Arguments for parametric replacement - * @param e Parsing exception + * @param args Arguments for parametric replacement + * @param e Parsing exception + * * @throws JasperException An error occurred */ - public void jspError(Exception e, String errCode, String... args) - throws JasperException { + public void jspError(Exception e, String errCode, String... args) throws JasperException { dispatch(null, errCode, args, e); } /** - * Dispatches the given JSP parse error to the configured error handler. - * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * - * @param where Error location - * @param e Parsing exception + * @param where Error location + * @param e Parsing exception * @param errCode Error code - * @param args Arguments for parametric replacement + * @param args Arguments for parametric replacement + * * @throws JasperException An error occurred */ - public void jspError(Mark where, Exception e, String errCode, String... args) - throws JasperException { + public void jspError(Mark where, Exception e, String errCode, String... args) throws JasperException { dispatch(where, errCode, args, e); } /** - * Dispatches the given JSP parse error to the configured error handler. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. - * - * @param n Node that caused the error - * @param e Parsing exception + * @param n Node that caused the error + * @param e Parsing exception * @param errCode Error code - * @param args Arguments for parametric replacement + * @param args Arguments for parametric replacement + * * @throws JasperException An error occurred */ - public void jspError(Node n, Exception e, String errCode, String... args) - throws JasperException { + public void jspError(Node n, Exception e, String errCode, String... args) throws JasperException { dispatch(n.getStart(), errCode, args, e); } /** - * Parses the given error message into an array of javac compilation error - * messages (one per javac compilation error line number). + * Parses the given error message into an array of javac compilation error messages (one per javac compilation error + * line number). * * @param errMsg Error message - * @param fname Name of Java source file whose compilation failed - * @param page Node representation of JSP page from which the Java source - * file was generated + * @param fname Name of Java source file whose compilation failed + * @param page Node representation of JSP page from which the Java source file was generated + * + * @return Array of javac compilation errors, or null if the given error message does not contain any compilation + * error line numbers * - * @return Array of javac compilation errors, or null if the given error - * message does not contain any compilation error line numbers * @throws JasperException An error occurred - * @throws IOException IO error which usually should not occur + * @throws IOException IO error which usually should not occur */ - public static JavacErrorDetail[] parseJavacErrors(String errMsg, - String fname, - Node.Nodes page) + public static JavacErrorDetail[] parseJavacErrors(String errMsg, String fname, Node.Nodes page) throws JasperException, IOException { return parseJavacMessage(errMsg, fname, page); } /** - * Dispatches the given javac compilation errors to the configured error - * handler. + * Dispatches the given javac compilation errors to the configured error handler. * * @param javacErrors Array of javac compilation errors + * * @throws JasperException An error occurred */ - public void javacError(JavacErrorDetail[] javacErrors) - throws JasperException { + public void javacError(JavacErrorDetail[] javacErrors) throws JasperException { errHandler.javacError(javacErrors); } /** - * Dispatches the given compilation error report and exception to the - * configured error handler. + * Dispatches the given compilation error report and exception to the configured error handler. * * @param errorReport Compilation error report - * @param e Compilation exception + * @param e Compilation exception + * * @throws JasperException An error occurred */ - public void javacError(String errorReport, Exception e) - throws JasperException { + public void javacError(String errorReport, Exception e) throws JasperException { errHandler.javacError(errorReport, e); } /** - * Dispatches the given JSP parse error to the configured error handler. - * - * The given error code is localized. If it is not found in the - * resource bundle for localized error messages, it is used as the error - * message. + * Dispatches the given JSP parse error to the configured error handler. The given error code is localized. If it is + * not found in the resource bundle for localized error messages, it is used as the error message. * - * @param where Error location + * @param where Error location * @param errCode Error code - * @param args Arguments for parametric replacement - * @param e Parsing exception + * @param args Arguments for parametric replacement + * @param e Parsing exception + * * @throws JasperException An error occurred */ - private void dispatch(Mark where, String errCode, Object[] args, - Exception e) throws JasperException { + private void dispatch(Mark where, String errCode, Object[] args, Exception e) throws JasperException { String file = null; String errMsg = null; int line = -1; @@ -286,8 +260,7 @@ public class ErrorDispatcher { // Get nested exception Exception nestedEx = e; - if ((e instanceof SAXException) - && (((SAXException) e).getException() != null)) { + if ((e instanceof SAXException) && (((SAXException) e).getException() != null)) { nestedEx = ((SAXException) e).getException(); } @@ -299,26 +272,22 @@ public class ErrorDispatcher { } /** - * Parses the given Java compilation error message, which may contain one - * or more compilation errors, into an array of JavacErrorDetail instances. + * Parses the given Java compilation error message, which may contain one or more compilation errors, into an array + * of JavacErrorDetail instances. * <p> - * Each JavacErrorDetail instance contains the information about a single - * compilation error. + * Each JavacErrorDetail instance contains the information about a single compilation error. * - * @param errMsg Compilation error message that was generated by the - * javac compiler - * @param fname Name of Java source file whose compilation failed - * @param page Node representation of JSP page from which the Java source - * file was generated + * @param errMsg Compilation error message that was generated by the javac compiler + * @param fname Name of Java source file whose compilation failed + * @param page Node representation of JSP page from which the Java source file was generated + * + * @return Array of JavacErrorDetail instances corresponding to the compilation errors * - * @return Array of JavacErrorDetail instances corresponding to the - * compilation errors * @throws JasperException An error occurred - * @throws IOException IO error which usually should not occur + * @throws IOException IO error which usually should not occur */ - private static JavacErrorDetail[] parseJavacMessage( - String errMsg, String fname, Node.Nodes page) - throws IOException, JasperException { + private static JavacErrorDetail[] parseJavacMessage(String errMsg, String fname, Node.Nodes page) + throws IOException, JasperException { List<JavacErrorDetail> errors = new ArrayList<>(); StringBuilder errMsgBuf = null; @@ -328,16 +297,15 @@ public class ErrorDispatcher { BufferedReader reader = new BufferedReader(new StringReader(errMsg)); /* - * Parse compilation errors. Each compilation error consists of a file - * path and error line number, followed by a number of lines describing - * the error. + * Parse compilation errors. Each compilation error consists of a file path and error line number, followed by a + * number of lines describing the error. */ String line = null; while ((line = reader.readLine()) != null) { /* - * Error line number is delimited by set of colons. - * Ignore colon following drive letter on Windows (fromIndex = 2). + * Error line number is delimited by set of colons. Ignore colon following drive letter on Windows + * (fromIndex = 2). * * XXX Handle deprecation warnings that don't have line info */ @@ -386,32 +354,36 @@ public class ErrorDispatcher { /** * Create a compilation error. - * @param fname The file name - * @param page The page nodes + * + * @param fname The file name + * @param page The page nodes * @param errMsgBuf The error message - * @param lineNum The source line number of the error + * @param lineNum The source line number of the error + * * @return JavacErrorDetail The error details + * * @throws JasperException An error occurred */ - public static JavacErrorDetail createJavacError(String fname, - Node.Nodes page, StringBuilder errMsgBuf, int lineNum) - throws JasperException { + public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum) + throws JasperException { return createJavacError(fname, page, errMsgBuf, lineNum, null); } /** * Create a compilation error. - * @param fname The file name - * @param page The page nodes + * + * @param fname The file name + * @param page The page nodes * @param errMsgBuf The error message - * @param lineNum The source line number of the error - * @param ctxt The compilation context + * @param lineNum The source line number of the error + * @param ctxt The compilation context + * * @return JavacErrorDetail The error details + * * @throws JasperException An error occurred */ - public static JavacErrorDetail createJavacError(String fname, - Node.Nodes page, StringBuilder errMsgBuf, int lineNum, + public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, StringBuilder errMsgBuf, int lineNum, JspCompilationContext ctxt) throws JasperException { JavacErrorDetail javacError; // Attempt to map javac error line number to line in JSP page @@ -422,50 +394,31 @@ public class ErrorDispatcher { // If this is a scriplet node then there is a one to one mapping between JSP lines and Java lines if (errVisitor.getJspSourceNode() instanceof Node.Scriptlet || errVisitor.getJspSourceNode() instanceof Node.Declaration) { - javacError = new JavacErrorDetail( - fname, - lineNum, - errNode.getStart().getFile(), - errNode.getStart().getLineNumber() + lineNum - - errVisitor.getJspSourceNode().getBeginJavaLine(), - errMsgBuf, - ctxt); + javacError = new JavacErrorDetail(fname, lineNum, errNode.getStart().getFile(), + errNode.getStart().getLineNumber() + lineNum - errVisitor.getJspSourceNode().getBeginJavaLine(), + errMsgBuf, ctxt); } else { - javacError = new JavacErrorDetail( - fname, - lineNum, - errNode.getStart().getFile(), - errNode.getStart().getLineNumber(), - errMsgBuf, - ctxt); + javacError = new JavacErrorDetail(fname, lineNum, errNode.getStart().getFile(), + errNode.getStart().getLineNumber(), errMsgBuf, ctxt); } } else { /* - * javac error line number cannot be mapped to JSP page - * line number. For example, this is the case if a - * scriptlet is missing a closing brace, which causes - * havoc with the try-catch-finally block that the code - * generator places around all generated code: As a result - * of this, the javac error line numbers will be outside - * the range of begin and end java line numbers that were - * generated for the scriptlet, and therefore cannot be - * mapped to the start line number of the scriptlet in the - * JSP page. + * javac error line number cannot be mapped to JSP page line number. For example, this is the case if a + * scriptlet is missing a closing brace, which causes havoc with the try-catch-finally block that the code + * generator places around all generated code: As a result of this, the javac error line numbers will be + * outside the range of begin and end java line numbers that were generated for the scriptlet, and therefore + * cannot be mapped to the start line number of the scriptlet in the JSP page. * * Include just the javac error info in the error detail. */ - javacError = new JavacErrorDetail( - fname, - lineNum, - errMsgBuf); + javacError = new JavacErrorDetail(fname, lineNum, errMsgBuf); } return javacError; } /** - * Visitor responsible for mapping a line number in the generated servlet - * source code to the corresponding JSP node. + * Visitor responsible for mapping a line number in the generated servlet source code to the corresponding JSP node. */ private static class ErrorVisitor extends Node.Visitor { @@ -475,8 +428,8 @@ public class ErrorDispatcher { private final int lineNum; /** - * JSP node whose Java source code range in the generated servlet - * contains the Java source line number to be mapped + * JSP node whose Java source code range in the generated servlet contains the Java source line number to be + * mapped */ private Node found; @@ -491,18 +444,15 @@ public class ErrorDispatcher { @Override public void doVisit(Node n) throws JasperException { - if ((lineNum >= n.getBeginJavaLine()) - && (lineNum < n.getEndJavaLine())) { + if ((lineNum >= n.getBeginJavaLine()) && (lineNum < n.getEndJavaLine())) { found = n; } } /** - * Gets the JSP node to which the source line number in the generated - * servlet code was mapped. + * Gets the JSP node to which the source line number in the generated servlet code was mapped. * - * @return JSP node to which the source line number in the generated - * servlet code was mapped + * @return JSP node to which the source line number in the generated servlet code was mapped */ public Node getJspSourceNode() { return found; diff --git a/java/org/apache/jasper/compiler/ErrorHandler.java b/java/org/apache/jasper/compiler/ErrorHandler.java index 8c8740e097..5e5e22c683 100644 --- a/java/org/apache/jasper/compiler/ErrorHandler.java +++ b/java/org/apache/jasper/compiler/ErrorHandler.java @@ -19,12 +19,9 @@ package org.apache.jasper.compiler; import org.apache.jasper.JasperException; /** - * Interface for handling JSP parse and javac compilation errors. - * - * An implementation of this interface may be registered with the - * ErrorDispatcher by setting the XXX initialization parameter in the JSP - * page compiler and execution servlet in Catalina's web.xml file to the - * implementation's fully qualified class name. + * Interface for handling JSP parse and javac compilation errors. An implementation of this interface may be registered + * with the ErrorDispatcher by setting the XXX initialization parameter in the JSP page compiler and execution servlet + * in Catalina's web.xml file to the implementation's fully qualified class name. * * @author Jan Luehe * @author Kin-man Chung @@ -34,43 +31,42 @@ public interface ErrorHandler { /** * Processes the given JSP parse error. * - * @param fname Name of the JSP file in which the parse error occurred - * @param line Parse error line number - * @param column Parse error column number - * @param msg Parse error message + * @param fname Name of the JSP file in which the parse error occurred + * @param line Parse error line number + * @param column Parse error column number + * @param msg Parse error message * @param exception Parse exception + * * @throws JasperException An error occurred */ - void jspError(String fname, int line, int column, String msg, - Exception exception) throws JasperException; + void jspError(String fname, int line, int column, String msg, Exception exception) throws JasperException; /** * Processes the given JSP parse error. * - * @param msg Parse error message + * @param msg Parse error message * @param exception Parse exception + * * @throws JasperException An error occurred */ - void jspError(String msg, Exception exception) - throws JasperException; + void jspError(String msg, Exception exception) throws JasperException; /** * Processes the given javac compilation errors. * - * @param details Array of JavacErrorDetail instances corresponding to the - * compilation errors + * @param details Array of JavacErrorDetail instances corresponding to the compilation errors + * * @throws JasperException An error occurred */ - void javacError(JavacErrorDetail[] details) - throws JasperException; + void javacError(JavacErrorDetail[] details) throws JasperException; /** * Processes the given javac error report and exception. * * @param errorReport Compilation error report - * @param exception Compilation exception + * @param exception Compilation exception + * * @throws JasperException An error occurred */ - void javacError(String errorReport, Exception exception) - throws JasperException; + void javacError(String errorReport, Exception exception) throws JasperException; } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org