JspUtil.java

Index Score
org.apache.jasper.compiler
Apache Tomcat

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
CYCLOMATICCyclomatic complexity
EXEC_COMMENTSComments in executable code
COMPARISONSNumber of comparison operators
INTERFACE_COMPLEXITYInterface complexity
LINE_COMMENTNumber of line comments
PARAMSNumber of formal parameter declarations
BLOCKSNumber of blocks
RETURNSNumber of return points from functions
LOOPSNumber of loops
SIZESize of the file in bytes
UNIQUE_OPERANDSNumber of unique operands
ELOCEffective lines of code
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
PROGRAM_VOCABHalstead program vocabulary
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
LOCLines of code
OPERANDSNumber of operands
LOGICAL_LINESNumber of statements
LINESNumber of lines in the source file
JAVA0117JAVA0117 Missing javadoc: method 'method'
EXITSProcedure exits
JAVA0177JAVA0177 Variable declaration missing initializer
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
COMMENTSComment lines
FUNCTIONSNumber of function declarations
JAVA0173JAVA0173 Unused method parameter
DECL_COMMENTSComments in declarations
DOC_COMMENTNumber of javadoc comment lines
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0076JAVA0076 Use of magic number
UNIQUE_OPERATORSNumber of unique operators
JAVA0067JAVA0067 Array descriptor on identifier name
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0119JAVA0119 Control variable changed within body of for loop
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0032JAVA0032 Switch statement missing default
JAVA0160JAVA0160 Method does not throw specified exception
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0285JAVA0285 Dereference of potentially null variable
JAVA0123JAVA0123 Use all three components of for loop
WHITESPACENumber of whitespace lines
NEST_DEPTHMaximum nesting depth
JAVA0145JAVA0145 Tab character used in source file
/* * 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 java.io.CharArrayWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.el.FunctionMapper; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; import org.xml.sax.Attributes; /** * This class has all the utility method(s). * Ideally should move all the bean containers here. * * @author Mandar Raje. * @author Rajiv Mordani. * @author Danno Ferrin * @author Pierre Delisle * @author Shawn Bayern * @author Mark Roth */ public class JspUtil { private static final String WEB_INF_TAGS = "/WEB-INF/tags/"; private static final String META_INF_TAGS = "/META-INF/tags/"; // Delimiters for request-time expressions (JSP and XML syntax) private static final String OPEN_EXPR = "<%="; private static final String CLOSE_EXPR = "%>"; private static final String OPEN_EXPR_XML = "%="; private static final String CLOSE_EXPR_XML = "%"; private static int tempSequenceNumber = 0; //private static ExpressionEvaluatorImpl expressionEvaluator //= new ExpressionEvaluatorImpl(); private static final String javaKeywords[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throws", "transient", "try", "void", "volatile", "while" }; public static final int CHUNKSIZE = 1024; public static char[] removeQuotes(char []chars) { CharArrayWriter caw = new CharArrayWriter(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '%' && chars[i+1] == '\\' && chars[i+2] == '>') { caw.write('%'); caw.write('>'); i = i + 2; } else { caw.write(chars[i]); } } return caw.toCharArray(); } public static char[] escapeQuotes (char []chars) { // Prescan to convert %\> to %> String s = new String(chars); while (true) { int n = s.indexOf("%\\>"); if (n < 0) break; StringBuffer sb = new StringBuffer(s.substring(0, n)); sb.append("%>"); sb.append(s.substring(n + 3)); s = sb.toString(); } chars = s.toCharArray(); return (chars); // Escape all backslashes not inside a Java string literal /* CharArrayWriter caw = new CharArrayWriter(); boolean inJavaString = false; for (int i = 0; i < chars.length; i++) { if (chars[i] == '"') inJavaString = !inJavaString; // escape out the escape character if (!inJavaString && (chars[i] == '\\')) caw.write('\\'); caw.write(chars[i]); } return caw.toCharArray(); */ } /** * Checks if the token is a runtime expression. * In standard JSP syntax, a runtime expression starts with '<%' and * ends with '%>'. When the JSP document is in XML syntax, a runtime * expression starts with '%=' and ends with '%'. * * @param token The token to be checked * return whether the token is a runtime expression or not. */ public static boolean isExpression(String token, boolean isXml) { String openExpr; String closeExpr; if (isXml) { openExpr = OPEN_EXPR_XML; closeExpr = CLOSE_EXPR_XML; } else { openExpr = OPEN_EXPR; closeExpr = CLOSE_EXPR; } if (token.startsWith(openExpr) && token.endsWith(closeExpr)) { return true; } else { return false; } } /** * @return the "expression" part of a runtime expression, * taking the delimiters out. */ public static String getExpr (String expression, boolean isXml) { String returnString; String openExpr; String closeExpr; if (isXml) { openExpr = OPEN_EXPR_XML; closeExpr = CLOSE_EXPR_XML; } else { openExpr = OPEN_EXPR; closeExpr = CLOSE_EXPR; } int length = expression.length(); if (expression.startsWith(openExpr) && expression.endsWith(closeExpr)) { returnString = expression.substring( openExpr.length(), length - closeExpr.length()); } else { returnString = ""; } return returnString; } /** * Takes a potential expression and converts it into XML form */ public static String getExprInXml(String expression) { String returnString; int length = expression.length(); if (expression.startsWith(OPEN_EXPR) && expression.endsWith(CLOSE_EXPR)) { returnString = expression.substring (1, length - 1); } else { returnString = expression; } return escapeXml(returnString.replace(Constants.ESC, '$')); } /** * Checks to see if the given scope is valid. * * @param scope The scope to be checked * @param n The Node containing the 'scope' attribute whose value is to be * checked * @param err error dispatcher * * @throws JasperException if scope is not null and different from * &quot;page&quot;, &quot;request&quot;, &quot;session&quot;, and * &quot;application&quot; */ public static void checkScope(String scope, Node n, ErrorDispatcher err) throws JasperException { if (scope != null && !scope.equals("page") && !scope.equals("request") && !scope.equals("session") && !scope.equals("application")) { err.jspError(n, "jsp.error.invalid.scope", scope); } } /** * Checks if all mandatory attributes are present and if all attributes * present have valid names. Checks attributes specified as XML-style * attributes as well as attributes specified using the jsp:attribute * standard action. */ public static void checkAttributes(String typeOfTag, Node n, ValidAttribute[] validAttributes, ErrorDispatcher err) throws JasperException { Attributes attrs = n.getAttributes(); Mark start = n.getStart(); boolean valid = true; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = (attrs == null) ? 0 : attrs.getLength(); Vector temp = new Vector(tempLength, 1); for (int i = 0; i < tempLength; i++) { String qName = attrs.getQName(i); if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:"))) temp.addElement(qName); } // Add names of attributes specified using jsp:attribute Node.Nodes tagBody = n.getBody(); if( tagBody != null ) { int numSubElements = tagBody.size(); for( int i = 0; i < numSubElements; i++ ) { Node node = tagBody.getNode( i ); if( node instanceof Node.NamedAttribute ) { String attrName = node.getAttributeValue( "name" ); temp.addElement( attrName ); // Check if this value appear in the attribute of the node if (n.getAttributeValue(attrName) != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", attrName); } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break; } } } /* * First check to see if all the mandatory attributes are present. * If so only then proceed to see if the other attributes are valid * for the particular tag. */ String missingAttribute = null; for (int i = 0; i < validAttributes.length; i++) { int attrPos; if (validAttributes[i].mandatory) { attrPos = temp.indexOf(validAttributes[i].name); if (attrPos != -1) { temp.remove(attrPos); valid = true; } else { valid = false; missingAttribute = validAttributes[i].name; break; } } } // If mandatory attribute is missing then the exception is thrown if (!valid) err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag, missingAttribute); // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp.size(); if (attrLeftLength == 0) return; // Now check to see if the rest of the attributes are valid too. String attribute = null; for (int j = 0; j < attrLeftLength; j++) { valid = false; attribute = (String) temp.elementAt(j); for (int i = 0; i < validAttributes.length; i++) { if (attribute.equals(validAttributes[i].name)) { valid = true; break; } } if (!valid) err.jspError(start, "jsp.error.invalid.attribute", typeOfTag, attribute); } // XXX *could* move EL-syntax validation here... (sb) } public static String escapeQueryString(String unescString) { if ( unescString == null ) return null; String escString = ""; String shellSpChars = "\\\""; for(int index=0; index<unescString.length(); index++) { char nextChar = unescString.charAt(index); if( shellSpChars.indexOf(nextChar) != -1 ) escString += "\\"; escString += nextChar; } return escString; } /** * Escape the 5 entities defined by XML. */ public static String escapeXml(String s) { if (s == null) return null; StringBuffer sb = new StringBuffer(); for(int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c == '<') { sb.append("&lt;"); } else if (c == '>') { sb.append("&gt;"); } else if (c == '\'') { sb.append("&apos;"); } else if (c == '&') { sb.append("&amp;"); } else if (c == '"') { sb.append("&quot;"); } else { sb.append(c); } } return sb.toString(); } /** * Replaces any occurrences of the character <tt>replace</tt> with the * string <tt>with</tt>. */ public static String replace(String name, char replace, String with) { StringBuffer buf = new StringBuffer(); int begin = 0; int end; int last = name.length(); while (true) { end = name.indexOf(replace, begin); if (end < 0) { end = last; } buf.append(name.substring(begin, end)); if (end == last) { break; } buf.append(with); begin = end + 1; } return buf.toString(); } public static class ValidAttribute { String name; boolean mandatory; boolean rtexprvalue; // not used now public ValidAttribute (String name, boolean mandatory, boolean rtexprvalue ) { this.name = name; this.mandatory = mandatory; this.rtexprvalue = rtexprvalue; } public ValidAttribute (String name, boolean mandatory) { this( name, mandatory, false ); } public ValidAttribute (String name) { this (name, false); } } /** * Convert a String value to 'boolean'. * Besides the standard conversions done by * Boolean.valueOf(s).booleanValue(), the value "yes" * (ignore case) is also converted to 'true'. * If 's' is null, then 'false' is returned. * * @param s the string to be converted * @return the boolean value associated with the string s */ public static boolean booleanValue(String s) { boolean b = false; if (s != null) { if (s.equalsIgnoreCase("yes")) { b = true; } else { b = Boolean.valueOf(s).booleanValue(); } } return b; } /** * Returns the <tt>Class</tt> object associated with the class or * interface with the given string name. * * <p> The <tt>Class</tt> object is determined by passing the given string * name to the <tt>Class.forName()</tt> method, unless the given string * name represents a primitive type, in which case it is converted to a * <tt>Class</tt> object by appending ".class" to it (e.g., "int.class"). */ public static Class toClass(String type, ClassLoader loader) throws ClassNotFoundException { Class c = null; int i0 = type.indexOf('['); int dims = 0; if (i0 > 0) { // This is an array. Count the dimensions for (int i = 0; i < type.length(); i++) { if (type.charAt(i) == '[') dims++; } type = type.substring(0, i0); } if ("boolean".equals(type)) c = boolean.class; else if ("char".equals(type)) c = char.class; else if ("byte".equals(type)) c = byte.class; else if ("short".equals(type)) c = short.class; else if ("int".equals(type)) c = int.class; else if ("long".equals(type)) c = long.class; else if ("float".equals(type)) c = float.class; else if ("double".equals(type)) c = double.class; else if (type.indexOf('[') < 0) c = loader.loadClass(type); if (dims == 0) return c; if (dims == 1) return java.lang.reflect.Array.newInstance(c, 1).getClass(); // Array of more than i dimension return java.lang.reflect.Array.newInstance(c, new int[dims]).getClass(); } /** * Produces a String representing a call to the EL interpreter. * @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 XmlEscape True if the result should do XML escaping * @return a String representing a call to the EL interpreter. */ public static String interpreterCall(boolean isTagFile, String expression, Class expectedType, String fnmapvar, boolean XmlEscape ) { /* * Determine which context object to use. */ String jspCtxt = null; if (isTagFile) jspCtxt = "this.getJspContext()"; else jspCtxt = "_jspx_page_context"; /* * Determine whether to use the expected type's textual name * or, if it's a primitive, the name of its correspondent boxed * type. */ String targetType = expectedType.getName(); String primitiveConverterMethod = null; if (expectedType.isPrimitive()) { if (expectedType.equals(Boolean.TYPE)) { targetType = Boolean.class.getName(); primitiveConverterMethod = "booleanValue"; } else if (expectedType.equals(Byte.TYPE)) { targetType = Byte.class.getName(); primitiveConverterMethod = "byteValue"; } else if (expectedType.equals(Character.TYPE)) { targetType = Character.class.getName(); primitiveConverterMethod = "charValue"; } else if (expectedType.equals(Short.TYPE)) { targetType = Short.class.getName(); primitiveConverterMethod = "shortValue"; } else if (expectedType.equals(Integer.TYPE)) { targetType = Integer.class.getName(); primitiveConverterMethod = "intValue"; } else if (expectedType.equals(Long.TYPE)) { targetType = Long.class.getName(); primitiveConverterMethod = "longValue"; } else if (expectedType.equals(Float.TYPE)) { targetType = Float.class.getName(); primitiveConverterMethod = "floatValue"; } else if (expectedType.equals(Double.TYPE)) { targetType = Double.class.getName(); primitiveConverterMethod = "doubleValue"; } } if (primitiveConverterMethod != null) { XmlEscape = false; } /* * Build up the base call to the interpreter. */ // XXX - We use a proprietary call to the interpreter for now // as the current standard machinery is inefficient and requires // lots of wrappers and adapters. This should all clear up once // the EL interpreter moves out of JSTL and into its own project. // In the future, this should be replaced by code that calls // ExpressionEvaluator.parseExpression() and then cache the resulting // expression objects. The interpreterCall would simply select // one of the pre-cached expressions and evaluate it. // Note that PageContextImpl implements VariableResolver and // the generated Servlet/SimpleTag implements FunctionMapper, so // that machinery is already in place (mroth). targetType = toJavaSourceType(targetType); StringBuffer call = new StringBuffer( "(" + targetType + ") " + "org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate" + "(" + Generator.quote(expression) + ", " + targetType + ".class, " + "(PageContext)" + jspCtxt + ", " + fnmapvar + ", " + XmlEscape + ")"); /* * Add the primitive converter method if we need to. */ if (primitiveConverterMethod != null) { call.insert(0, "("); call.append(")." + primitiveConverterMethod + "()"); } return call.toString(); } /** * Validates the syntax of all ${} expressions within the given string. * @param where the approximate location of the expressions in the JSP page * @param expressions a string containing zero or more "${}" expressions * @param err an error dispatcher to use * @deprecated now delegated to the org.apache.el Package */ public static void validateExpressions(Mark where, String expressions, Class expectedType, FunctionMapper functionMapper, ErrorDispatcher err) throws JasperException { // try { // // JspUtil.expressionEvaluator.parseExpression( expressions, // expectedType, functionMapper ); // } // catch( ELParseException e ) { // err.jspError(where, "jsp.error.invalid.expression", expressions, // e.toString() ); // } // catch( ELException e ) { // err.jspError(where, "jsp.error.invalid.expression", expressions, // e.toString() ); // } } /** * Resets the temporary variable name. * (not thread-safe) */ public static void resetTemporaryVariableName() { tempSequenceNumber = 0; } /** * Generates a new temporary variable name. * (not thread-safe) */ public static String nextTemporaryVariableName() { return Constants.TEMP_VARIABLE_NAME_PREFIX + (tempSequenceNumber++); } public static String coerceToPrimitiveBoolean(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToBoolean(" + s + ")"; } else { if (s == null || s.length() == 0) return "false"; else return Boolean.valueOf(s).toString(); } } public static String coerceToBoolean(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Boolean) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Boolean.class)"; } else { if (s == null || s.length() == 0) { return "new Boolean(false)"; } else { // Detect format error at translation time return "new Boolean(" + Boolean.valueOf(s).toString() + ")"; } } } public static String coerceToPrimitiveByte(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToByte(" + s + ")"; } else { if (s == null || s.length() == 0) return "(byte) 0"; else return "((byte)" + Byte.valueOf(s).toString() + ")"; } } public static String coerceToByte(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Byte) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Byte.class)"; } else { if (s == null || s.length() == 0) { return "new Byte((byte) 0)"; } else { // Detect format error at translation time return "new Byte((byte)" + Byte.valueOf(s).toString() + ")"; } } } public static String coerceToChar(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToChar(" + s + ")"; } else { if (s == null || s.length() == 0) { return "(char) 0"; } else { char ch = s.charAt(0); // this trick avoids escaping issues return "((char) " + (int) ch + ")"; } } } public static String coerceToCharacter(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Character) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Character.class)"; } else { if (s == null || s.length() == 0) { return "new Character((char) 0)"; } else { char ch = s.charAt(0); // this trick avoids escaping issues return "new Character((char) " + (int) ch + ")"; } } } public static String coerceToPrimitiveDouble(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToDouble(" + s + ")"; } else { if (s == null || s.length() == 0) return "(double) 0"; else return Double.valueOf(s).toString(); } } public static String coerceToDouble(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Double) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Double.class)"; } else { if (s == null || s.length() == 0) { return "new Double(0)"; } else { // Detect format error at translation time return "new Double(" + Double.valueOf(s).toString() + ")"; } } } public static String coerceToPrimitiveFloat(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToFloat(" + s + ")"; } else { if (s == null || s.length() == 0) return "(float) 0"; else return Float.valueOf(s).toString() + "f"; } } public static String coerceToFloat(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Float) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Float.class)"; } else { if (s == null || s.length() == 0) { return "new Float(0)"; } else { // Detect format error at translation time return "new Float(" + Float.valueOf(s).toString() + "f)"; } } } public static String coerceToInt(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToInt(" + s + ")"; } else { if (s == null || s.length() == 0) return "0"; else return Integer.valueOf(s).toString(); } } public static String coerceToInteger(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Integer) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Integer.class)"; } else { if (s == null || s.length() == 0) { return "new Integer(0)"; } else { // Detect format error at translation time return "new Integer(" + Integer.valueOf(s).toString() + ")"; } } } public static String coerceToPrimitiveShort(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToShort(" + s + ")"; } else { if (s == null || s.length() == 0) return "(short) 0"; else return "((short) " + Short.valueOf(s).toString() + ")"; } } public static String coerceToShort(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Short) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Short.class)"; } else { if (s == null || s.length() == 0) { return "new Short((short) 0)"; } else { // Detect format error at translation time return "new Short(\"" + Short.valueOf(s).toString() + "\")"; } } } public static String coerceToPrimitiveLong(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToLong(" + s + ")"; } else { if (s == null || s.length() == 0) return "(long) 0"; else return Long.valueOf(s).toString() + "l"; } } public static String coerceToLong(String s, boolean isNamedAttribute) { if (isNamedAttribute) { return "(Long) org.apache.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Long.class)"; } else { if (s == null || s.length() == 0) { return "new Long(0)"; } else { // Detect format error at translation time return "new Long(" + Long.valueOf(s).toString() + "l)"; } } } public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { err.jspError("jsp.error.file.not.found", fname); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { err.jspError("jsp.error.file.not.found", fname); } return in; } /** * Gets the fully-qualified class name of the tag handler corresponding to * the given tag file path. * * @param path Tag file path * @param err Error dispatcher * * @return Fully-qualified class name of the tag handler corresponding to * the given tag file path */ public static String getTagHandlerClassName(String path, ErrorDispatcher err) throws JasperException { String className = null; int begin = 0; int index; index = path.lastIndexOf(".tag"); if (index == -1) { err.jspError("jsp.error.tagfile.badSuffix", path); } //It's tempting to remove the ".tag" suffix here, but we can't. //If we remove it, the fully-qualified class name of this tag //could conflict with the package name of other tags. //For instance, the tag file // /WEB-INF/tags/foo.tag //would have fully-qualified class name // org.apache.jsp.tag.web.foo //which would conflict with the package name of the tag file // /WEB-INF/tags/foo/bar.tag index = path.indexOf(WEB_INF_TAGS); if (index != -1) { className = "org.apache.jsp.tag.web."; begin = index + WEB_INF_TAGS.length(); } else { index = path.indexOf(META_INF_TAGS); if (index != -1) { className = "org.apache.jsp.tag.meta."; begin = index + META_INF_TAGS.length(); } else { err.jspError("jsp.error.tagfile.illegalPath", path); } } className += makeJavaPackage(path.substring(begin)); return className; } /** * Converts the given path to a Java package or fully-qualified class name * * @param path Path to convert * * @return Java package corresponding to the given path */ public static final String makeJavaPackage(String path) { String classNameComponents[] = split(path,"/"); StringBuffer legalClassNames = new StringBuffer(); for (int i = 0; i < classNameComponents.length; i++) { legalClassNames.append(makeJavaIdentifier(classNameComponents[i])); if (i < classNameComponents.length - 1) { legalClassNames.append('.'); } } return legalClassNames.toString(); } /** * Splits a string into it's components. * @param path String to split * @param pat Pattern to split at * @return the components of the path */ private static final String [] split(String path, String pat) { Vector comps = new Vector(); int pos = path.indexOf(pat); int start = 0; while( pos >= 0 ) { if(pos > start ) { String comp = path.substring(start,pos); comps.add(comp); } start = pos + pat.length(); pos = path.indexOf(pat,start); } if( start < path.length()) { comps.add(path.substring(start)); } String [] result = new String[comps.size()]; for(int i=0; i < comps.size(); i++) { result[i] = (String)comps.elementAt(i); } return result; } /** * Converts the given identifier to a legal Java identifier * * @param identifier Identifier to convert * * @return Legal Java identifier corresponding to the given identifier */ public static final String makeJavaIdentifier(String identifier) { StringBuffer modifiedIdentifier = new StringBuffer(identifier.length()); if (!Character.isJavaIdentifierStart(identifier.charAt(0))) { modifiedIdentifier.append('_'); } for (int i = 0; i < identifier.length(); i++) { char ch = identifier.charAt(i); if (Character.isJavaIdentifierPart(ch) && ch != '_') { modifiedIdentifier.append(ch); } else if (ch == '.') { modifiedIdentifier.append('_'); } else { modifiedIdentifier.append(mangleChar(ch)); } } if (isJavaKeyword(modifiedIdentifier.toString())) { modifiedIdentifier.append('_'); } return modifiedIdentifier.toString(); } /** * Mangle the specified character to create a legal Java class name. */ public static final String mangleChar(char ch) { char[] result = new char[5]; result[0] = '_'; result[1] = Character.forDigit((ch >> 12) & 0xf, 16); result[2] = Character.forDigit((ch >> 8) & 0xf, 16); result[3] = Character.forDigit((ch >> 4) & 0xf, 16); result[4] = Character.forDigit(ch & 0xf, 16); return new String(result); } /** * Test whether the argument is a Java keyword */ public static boolean isJavaKeyword(String key) { int i = 0; int j = javaKeywords.length; while (i < j) { int k = (i+j)/2; int result = javaKeywords[k].compareTo(key); if (result == 0) { return true; } if (result < 0) { i = k+1; } else { j = k; } } return false; } /** * Converts the given Xml name to a legal Java identifier. This is * slightly more efficient than makeJavaIdentifier in that we only need * to worry about '.', '-', and ':' in the string. We also assume that * the resultant string is further concatenated with some prefix string * so that we don't have to worry about it being a Java key word. * * @param name Identifier to convert * * @return Legal Java identifier corresponding to the given identifier */ public static final String makeXmlJavaIdentifier(String name) { if (name.indexOf('-') >= 0) name = replace(name, '-', "$1"); if (name.indexOf('.') >= 0) name = replace(name, '.', "$2"); if (name.indexOf(':') >= 0) name = replace(name, ':', "$3"); return name; } static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { return getReader(fname, encoding, jarFile, ctxt, err, 0); } static InputStreamReader getReader(String fname, String encoding, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err, int skip) throws JasperException, IOException { InputStreamReader reader = null; InputStream in = getInputStream(fname, jarFile, ctxt, err); for (int i = 0; i < skip; i++) { in.read(); } try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException ex) { err.jspError("jsp.error.unsupported.encoding", encoding); } return reader; } /** * Handles taking input from TLDs * 'java.lang.Object' -> 'java.lang.Object.class' * 'int' -> 'int.class' * 'void' -> 'Void.TYPE' * 'int[]' -> 'int[].class' * * @param type * @return */ public static String toJavaSourceTypeFromTld(String type) { if (type == null || "void".equals(type)) { return "Void.TYPE"; } return type + ".class"; } /** * Class.getName() return arrays in the form "[[[<et>", where et, * the element type can be one of ZBCDFIJS or L<classname>; * It is converted into forms that can be understood by javac. */ public static String toJavaSourceType(String type) { if (type.charAt(0) != '[') { return type; } int dims = 1; String t = null; for (int i = 1; i < type.length(); i++) { if (type.charAt(i) == '[') { dims++; } else { switch (type.charAt(i)) { case 'Z': t = "boolean"; break; case 'B': t = "byte"; break; case 'C': t = "char"; break; case 'D': t = "double"; break; case 'F': t = "float"; break; case 'I': t = "int"; break; case 'J': t = "long"; break; case 'S': t = "short"; break; case 'L': t = type.substring(i+1, type.indexOf(';')); break; } break; } } StringBuffer resultType = new StringBuffer(t); for (; dims > 0; dims--) { resultType.append("[]"); } return resultType.toString(); } /** * Compute the canonical name from a Class instance. Note that a * simple replacment of '$' with '.' of a binary name would not work, * as '$' is a legal Java Identifier character. * @param c A instance of java.lang.Class * @return The canonical name of c. */ public static String getCanonicalName(Class c) { String binaryName = c.getName(); c = c.getDeclaringClass(); if (c == null) { return binaryName; } StringBuffer buf = new StringBuffer(binaryName); do { buf.setCharAt(c.getName().length(), '.'); c = c.getDeclaringClass(); } while ( c != null); return buf.toString(); } }

The table below shows all metrics for JspUtil.java.

MetricValueDescription
BLOCKS189.00Number of blocks
BLOCK_COMMENT46.00Number of block comment lines
COMMENTS267.00Comment lines
COMMENT_DENSITY 0.43Comment density
COMPARISONS150.00Number of comparison operators
CYCLOMATIC215.00Cyclomatic complexity
DECL_COMMENTS27.00Comments in declarations
DOC_COMMENT163.00Number of javadoc comment lines
ELOC622.00Effective lines of code
EXEC_COMMENTS42.00Comments in executable code
EXITS89.00Procedure exits
FUNCTIONS48.00Number of function declarations
HALSTEAD_DIFFICULTY95.21Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY218.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 1.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 1.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003439.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 2.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 8.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 1.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 1.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA010820.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 9.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 4.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 1.00JAVA0116 Missing javadoc: field 'field'
JAVA011723.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 1.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 1.00JAVA0119 Control variable changed within body of for loop
JAVA0123 1.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 1.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 1.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 5.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 9.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 2.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 1.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1136.00Number of lines in the source file
LINE_COMMENT58.00Number of line comments
LOC761.00Lines of code
LOGICAL_LINES368.00Number of statements
LOOPS20.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS1720.00Number of operands
OPERATORS3266.00Number of operators
PARAMS97.00Number of formal parameter declarations
PROGRAM_LENGTH4986.00Halstead program length
PROGRAM_VOCAB622.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS121.00Number of return points from functions
SIZE37888.00Size of the file in bytes
UNIQUE_OPERANDS560.00Number of unique operands
UNIQUE_OPERATORS62.00Number of unique operators
WHITESPACE108.00Number of whitespace lines