proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/MessageExpression.java
MessageExpression
executeMessageExpression
class MessageExpression extends SimpleExpression { private static final Logger logger = LoggerFactory.getLogger(MessageExpression.class); private static final long serialVersionUID = 8394399541792390735L; private static final Object[] NO_PARAMETERS = new Object[0]; static final char SELECTOR = '#'; private static final char PARAMS_START_CHAR = '('; private static final char PARAMS_END_CHAR = ')'; private static final Pattern MSG_PATTERN = Pattern.compile("^\\s*\\#\\{(.+?)\\}\\s*$", Pattern.DOTALL); private final IStandardExpression base; private final ExpressionSequence parameters; public MessageExpression(final IStandardExpression base, final ExpressionSequence parameters) { super(); Validate.notNull(base, "Base cannot be null"); this.base = base; this.parameters = parameters; } public IStandardExpression getBase() { return this.base; } public ExpressionSequence getParameters() { return this.parameters; } public boolean hasParameters() { return this.parameters != null && this.parameters.size() > 0; } @Override public String getStringRepresentation() { final StringBuilder sb = new StringBuilder(); sb.append(SELECTOR); sb.append(SimpleExpression.EXPRESSION_START_CHAR); sb.append(this.base); if (hasParameters()) { sb.append(PARAMS_START_CHAR); sb.append(this.parameters.getStringRepresentation()); sb.append(PARAMS_END_CHAR); } sb.append(SimpleExpression.EXPRESSION_END_CHAR); return sb.toString(); } static MessageExpression parseMessageExpression(final String input) { final Matcher matcher = MSG_PATTERN.matcher(input); if (!matcher.matches()) { return null; } final String content = matcher.group(1); if (StringUtils.isEmptyOrWhitespace(content)) { return null; } final String trimmedInput = content.trim(); if (trimmedInput.endsWith(String.valueOf(PARAMS_END_CHAR))) { boolean inLiteral = false; int nestParLevel = 0; for (int i = trimmedInput.length() - 1; i >= 0; i--) { final char c = trimmedInput.charAt(i); if (c == TextLiteralExpression.DELIMITER) { if (i == 0 || content.charAt(i - 1) != '\\') { inLiteral = !inLiteral; } } else if (c == PARAMS_END_CHAR) { nestParLevel++; } else if (c == PARAMS_START_CHAR) { nestParLevel--; if (nestParLevel < 0) { return null; } if (nestParLevel == 0) { if (i == 0) { return null; } final String base = trimmedInput.substring(0, i); final String parameters = trimmedInput.substring(i + 1, trimmedInput.length() - 1); final Expression baseExpr = parseDefaultAsLiteral(base); if (baseExpr == null) { return null; } final ExpressionSequence parametersExprSeq = ExpressionSequenceUtils.internalParseExpressionSequence(parameters); if (parametersExprSeq == null) { return null; } return new MessageExpression(baseExpr, parametersExprSeq); } } } return null; } final Expression baseExpr = parseDefaultAsLiteral(trimmedInput); if (baseExpr == null) { return null; } return new MessageExpression(baseExpr, null); } private static Expression parseDefaultAsLiteral(final String input) { if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final Expression expr = Expression.parse(input); if (expr == null) { return Expression.parse(TextLiteralExpression.wrapStringIntoLiteral(input)); } return expr; } static Object executeMessageExpression( final IExpressionContext context, final MessageExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating message: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } if (!(context instanceof ITemplateContext)) { throw new TemplateProcessingException( "Cannot evaluate expression \"" + expression + "\". Message externalization expressions " + "can only be evaluated in a template-processing environment (as a part of an in-template expression) " + "where processing context is an implementation of " + ITemplateContext.class.getClass() + ", which it isn't (" + context.getClass().getName() + ")"); } final ITemplateContext templateContext = (ITemplateContext)context; final IStandardExpression baseExpression = expression.getBase(); Object messageKey = baseExpression.execute(templateContext, expContext); messageKey = LiteralValue.unwrap(messageKey); if (messageKey != null && !(messageKey instanceof String)) { messageKey = messageKey.toString(); } if (StringUtils.isEmptyOrWhitespace((String) messageKey)) { throw new TemplateProcessingException( "Message key for message resolution must be a non-null and non-empty String"); } final Object[] messageParameters; if (expression.hasParameters()) { final ExpressionSequence parameterExpressionSequence = expression.getParameters(); final List<IStandardExpression> parameterExpressionValues = parameterExpressionSequence.getExpressions(); final int parameterExpressionValuesLen = parameterExpressionValues.size(); messageParameters = new Object[parameterExpressionValuesLen]; for (int i = 0; i < parameterExpressionValuesLen; i++) { final IStandardExpression parameterExpression = parameterExpressionValues.get(i); final Object result = parameterExpression.execute(templateContext, expContext); messageParameters[i] = LiteralValue.unwrap(result); } } else { messageParameters = NO_PARAMETERS; } // Note message expressions will always return an absent representation if message does not exist return templateContext.getMessage(null, (String)messageKey, messageParameters, true);
1,242
537
1,779
<methods><variables>static final char EXPRESSION_END_CHAR,static final char EXPRESSION_START_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/MinusExpression.java
MinusExpression
composeMinusExpression
class MinusExpression extends ComplexExpression { private static final long serialVersionUID = -9056215047277857192L; private static final Logger logger = LoggerFactory.getLogger(MinusExpression.class); private static final char OPERATOR = '-'; // Future proof, just in case in the future we add other tokens as operators static final String[] OPERATORS = new String[] {String.valueOf(OPERATOR)}; private final Expression operand; public MinusExpression(final Expression operand) { super(); Validate.notNull(operand, "Operand cannot be null"); this.operand = operand; } public Expression getOperand() { return this.operand; } @Override public String getStringRepresentation() { final StringBuilder sb = new StringBuilder(); sb.append(OPERATOR); if (this.operand instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.operand); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.operand); } return sb.toString(); } public static ExpressionParsingState composeMinusExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} static Object executeMinus( final IExpressionContext context, final MinusExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating minus expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object operandValue = expression.getOperand().execute(context, expContext); if (operandValue == null) { operandValue = "null"; } final BigDecimal operandNumberValue = EvaluationUtils.evaluateAsNumber(operandValue); if (operandNumberValue != null) { // Addition will act as a mathematical 'plus' return operandNumberValue.multiply(BigDecimal.valueOf(-1)); } throw new TemplateProcessingException( "Cannot execute minus: operand is \"" + LiteralValue.unwrap(operandValue) + "\""); } }
// Returning "state" means "try next in chain" or "success" // Returning "null" means parsing error final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final String trimmedInput = input.trim(); // Trying to fail quickly... final int operatorPos = trimmedInput.lastIndexOf(OPERATOR); if (operatorPos == -1) { return state; } if (operatorPos != 0) { // The '-' symbol should be the first character, after trimming. return state; } final String operandStr = trimmedInput.substring(1); final Expression operandExpr = ExpressionParsingUtil.parseAndCompose(state, operandStr); if (operandExpr == null) { return null; } final MinusExpression minusExpression = new MinusExpression(operandExpr); state.setNode(nodeIndex, minusExpression); return state;
657
283
940
<methods><variables>private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/MultiplicationDivisionRemainderExpression.java
MultiplicationDivisionRemainderExpression
isRightAllowed
class MultiplicationDivisionRemainderExpression extends BinaryOperationExpression { private static final long serialVersionUID = -1364531602981256885L; protected static final String MULTIPLICATION_OPERATOR = "*"; protected static final String DIVISION_OPERATOR = "/"; protected static final String DIVISION_OPERATOR_2 = "div"; protected static final String REMAINDER_OPERATOR = "%"; protected static final String REMAINDER_OPERATOR_2 = "mod"; static final String[] OPERATORS = new String[] { MULTIPLICATION_OPERATOR, DIVISION_OPERATOR, DIVISION_OPERATOR_2, REMAINDER_OPERATOR, REMAINDER_OPERATOR_2 }; private static final boolean[] LENIENCIES = new boolean[] { false, false, false, false, false }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { MultiplicationExpression.class, DivisionExpression.class, DivisionExpression.class, RemainderExpression.class, RemainderExpression.class }; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = MultiplicationDivisionRemainderExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = MultiplicationDivisionRemainderExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } protected MultiplicationDivisionRemainderExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } static boolean isRightAllowed(final IStandardExpression right) {<FILL_FUNCTION_BODY>} static boolean isLeftAllowed(final IStandardExpression left) { return left != null && !(left instanceof Token && !(left instanceof NumberTokenExpression)) && !(left instanceof TextLiteralExpression); } static ExpressionParsingState composeMultiplicationDivisionRemainderExpression( final ExpressionParsingState state, final int nodeIndex) { return composeBinaryOperationExpression( state, nodeIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD); } }
return right != null && !(right instanceof Token && !(right instanceof NumberTokenExpression)) && !(right instanceof TextLiteralExpression);
728
39
767
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/MultiplicationExpression.java
MultiplicationExpression
executeMultiplication
class MultiplicationExpression extends MultiplicationDivisionRemainderExpression { private static final long serialVersionUID = 4822815123712162053L; private static final Logger logger = LoggerFactory.getLogger(MultiplicationExpression.class); public MultiplicationExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(MULTIPLICATION_OPERATOR); } static Object executeMultiplication( final IExpressionContext context, final MultiplicationExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating multiplication expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null) { leftValue = "null"; } if (rightValue == null) { rightValue = "null"; } final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { // Addition will act as a mathematical 'plus' return leftNumberValue.multiply(rightNumberValue); } throw new TemplateProcessingException( "Cannot execute multiplication: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\"");
209
290
499
<methods><variables>protected static final java.lang.String DIVISION_OPERATOR,protected static final java.lang.String DIVISION_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String MULTIPLICATION_OPERATOR,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,protected static final java.lang.String REMAINDER_OPERATOR,protected static final java.lang.String REMAINDER_OPERATOR_2,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/NegationExpression.java
NegationExpression
composeNegationExpression
class NegationExpression extends ComplexExpression { private static final long serialVersionUID = -7131967162611145337L; private static final Logger logger = LoggerFactory.getLogger(NegationExpression.class); private static final String OPERATOR_1 = "!"; private static final String OPERATOR_2 = "not"; // Future proof, just in case in the future we add "not" as an operator static final String[] OPERATORS = new String[] {OPERATOR_1, OPERATOR_2}; private final Expression operand; public NegationExpression(final Expression operand) { super(); Validate.notNull(operand, "Operand cannot be null"); this.operand = operand; } public Expression getOperand() { return this.operand; } @Override public String getStringRepresentation() { final StringBuilder sb = new StringBuilder(); sb.append(OPERATOR_1); if (this.operand instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.operand); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.operand); } return sb.toString(); } public static ExpressionParsingState composeNegationExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} static Object executeNegation( final IExpressionContext context, final NegationExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating negation expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final Object operandValue = expression.getOperand().execute(context, expContext); final boolean operandBooleanValue = EvaluationUtils.evaluateAsBoolean(operandValue); return Boolean.valueOf(!operandBooleanValue); } }
// Returning "state" means "try next in chain" or "success" // Returning "null" means parsing error final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final String trimmedInput = input.trim(); // Trying to fail quickly... String operatorFound = null; int operatorPos = trimmedInput.lastIndexOf(OPERATOR_1); if (operatorPos == -1) { operatorPos = trimmedInput.lastIndexOf(OPERATOR_2); if (operatorPos == -1) { return state; } operatorFound = OPERATOR_2; } else { operatorFound = OPERATOR_1; } if (operatorPos != 0) { // The operator (any of them) should be at the first character, after trimming. return state; } final String operandStr = trimmedInput.substring(operatorFound.length()); final Expression operandExpr = ExpressionParsingUtil.parseAndCompose(state, operandStr); if (operandExpr == null) { return null; } final NegationExpression minusExpression = new NegationExpression(operandExpr); state.setNode(nodeIndex, minusExpression); return state;
581
360
941
<methods><variables>private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/NoOpTokenExpression.java
NoOpTokenExpression
parseNoOpTokenExpression
class NoOpTokenExpression extends Token { private static final Logger logger = LoggerFactory.getLogger(NoOpTokenExpression.class); private static final long serialVersionUID = -5180150929940011L; private static final NoOpTokenExpression SINGLETON = new NoOpTokenExpression(); public NoOpTokenExpression() { super(null); } @Override public String getStringRepresentation() { return "_"; } static NoOpTokenExpression parseNoOpTokenExpression(final String input) {<FILL_FUNCTION_BODY>} static Object executeNoOpTokenExpression( final IExpressionContext context, final NoOpTokenExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating no-op token: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return NoOpToken.VALUE; } }
if (input.length() == 1 && input.charAt(0) == '_') { return SINGLETON; } return null;
275
41
316
<methods>public java.lang.String getStringRepresentation() ,public java.lang.Object getValue() ,public static boolean isTokenChar(java.lang.String, int) ,public java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object value
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/NotEqualsExpression.java
NotEqualsExpression
executeNotEquals
class NotEqualsExpression extends EqualsNotEqualsExpression { private static final long serialVersionUID = 5831688164085171802L; private static final Logger logger = LoggerFactory.getLogger(NotEqualsExpression.class); public NotEqualsExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(NOT_EQUALS_OPERATOR); } @SuppressWarnings({"unchecked","null"}) static Object executeNotEquals( final IExpressionContext context, final NotEqualsExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); if (leftValue == null) { return Boolean.valueOf(rightValue != null); } Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) != 0); } else { if (leftValue instanceof Character) { leftValue = leftValue.toString(); // Just a character, no need to use conversionService here } if (rightValue != null && rightValue instanceof Character) { rightValue = rightValue.toString(); // Just a character, no need to use conversionService here } if (rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) != 0); } else { result = Boolean.valueOf(!leftValue.equals(rightValue)); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating NOT EQUALS expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
222
490
712
<methods><variables>protected static final java.lang.String EQUALS_OPERATOR,protected static final java.lang.String EQUALS_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String NOT_EQUALS_OPERATOR,protected static final java.lang.String NOT_EQUALS_OPERATOR_2,protected static final java.lang.String NOT_EQUALS_OPERATOR_3,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/NullTokenExpression.java
NullTokenExpression
executeNullTokenExpression
class NullTokenExpression extends Token { private static final Logger logger = LoggerFactory.getLogger(NullTokenExpression.class); private static final long serialVersionUID = -927282151625647619L; private static final NullTokenExpression SINGLETON = new NullTokenExpression(); public NullTokenExpression() { super(null); } @Override public String getStringRepresentation() { return "null"; } static NullTokenExpression parseNullTokenExpression(final String input) { if ("null".equalsIgnoreCase(input)) { return SINGLETON; } return null; } static Object executeNullTokenExpression( final IExpressionContext context, final NullTokenExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating null token: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return expression.getValue();
238
68
306
<methods>public java.lang.String getStringRepresentation() ,public java.lang.Object getValue() ,public static boolean isTokenChar(java.lang.String, int) ,public java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object value
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/NumberTokenExpression.java
NumberTokenExpression
parseNumberTokenExpression
class NumberTokenExpression extends Token { private static final Logger logger = LoggerFactory.getLogger(NumberTokenExpression.class); private static final long serialVersionUID = -3729844055243242571L; public static final char DECIMAL_POINT = '.'; static Number computeValue(final String value) { final BigDecimal bigDecimalValue = new BigDecimal(value); if (bigDecimalValue.scale() > 0) { return bigDecimalValue; } return bigDecimalValue.toBigInteger(); } public NumberTokenExpression(final String value) { super(computeValue(value)); } @Override public String getStringRepresentation() { final Object value = getValue(); if (value instanceof BigDecimal) { return ((BigDecimal)getValue()).toPlainString(); } return value.toString(); } static NumberTokenExpression parseNumberTokenExpression(final String input) {<FILL_FUNCTION_BODY>} static Object executeNumberTokenExpression( final IExpressionContext context, final NumberTokenExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating number token: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return expression.getValue(); } }
if (StringUtils.isEmptyOrWhitespace(input)) { return null; } boolean decimalFound = false; final int inputLen = input.length(); for (int i = 0; i < inputLen; i++) { final char c = input.charAt(i); if (Character.isDigit(c)) { continue; } else if (c == DECIMAL_POINT) { if (decimalFound) { return null; } decimalFound = true; continue; } else { return null; } } try { return new NumberTokenExpression(input); } catch (final NumberFormatException e) { // It seems after all it wasn't valid as a number return null; }
399
204
603
<methods>public java.lang.String getStringRepresentation() ,public java.lang.Object getValue() ,public static boolean isTokenChar(java.lang.String, int) ,public java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object value
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/OGNLContextPropertyAccessor.java
OGNLContextPropertyAccessor
getSourceAccessor
class OGNLContextPropertyAccessor implements PropertyAccessor { private static final Logger LOGGER = LoggerFactory.getLogger(OGNLContextPropertyAccessor.class); public static final String RESTRICT_REQUEST_PARAMETERS = "%RESTRICT_REQUEST_PARAMETERS%"; static final String REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME = "param"; OGNLContextPropertyAccessor() { super(); } public Object getProperty(final Map ognlContext, final Object target, final Object name) throws OgnlException { if (!(target instanceof IContext)) { throw new IllegalStateException( "Wrong target type. This property accessor is only usable for " + IContext.class.getName() + " implementations, and " + "in this case the target object is " + (target == null? "null" : ("of class " + target.getClass().getName()))); } if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(name) && ognlContext != null && ognlContext.containsKey(RESTRICT_REQUEST_PARAMETERS)) { throw new OgnlException( "Access to variable \"" + name + "\" is forbidden in this context. Note some restrictions apply to " + "variable access. For example, direct access to request parameters is forbidden in preprocessing and " + "unescaped expressions, in TEXT template mode, in fragment insertion specifications and " + "in some specific attribute processors."); } final String propertyName = (name == null? null : name.toString()); /* * NOTE we do not check here whether we are being asked for the 'locale', 'request', 'response', etc. * because there already are specific expression objects for the most important of them, which should * be used instead: #locale, #httpServletRequest, #httpSession, etc. * The variables maps should just be used as a map, without exposure of its more-internal methods... */ final IContext context = (IContext) target; return context.getVariable(propertyName); } public void setProperty(final Map context, final Object target, final Object name, final Object value) throws OgnlException { // IVariablesMap implementations should never be set values from OGNL expressions throw new UnsupportedOperationException("Cannot set values into VariablesMap instances from OGNL Expressions"); } public String getSourceAccessor(final OgnlContext context, final Object target, final Object index) {<FILL_FUNCTION_BODY>} public String getSourceSetter(final OgnlContext context, final Object target, final Object index) { // This method is called during OGNL's bytecode enhancement optimizations in order to determine better- // performing methods to access the properties of an object. Given IVariablesMap implementations should never // be set any values from OGNL, this exception should never be thrown anyway. throw new UnsupportedCompilationException( "Setting expression for " + context.getCurrentObject() + " with index of " + index + " cannot " + "be computed. IVariablesMap implementations are considered read-only by OGNL."); } }
// This method is called during OGNL's bytecode enhancement optimizations in order to determine better- // performing methods to access the properties of an object. It's been written trying to mimic // what is done at MapPropertyAccessor#getSourceAccessor() method, removing all the parts related to indexed // access, which do not apply to IVariablesMap implementations. context.setCurrentAccessor(IContext.class); context.setCurrentType(Object.class); return ".getVariable(" + index + ")";
819
134
953
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/OGNLExpressionObjectsWrapper.java
OGNLExpressionObjectsWrapper
put
class OGNLExpressionObjectsWrapper extends HashMap<String, Object> { private final IExpressionObjects expressionObjects; OGNLExpressionObjectsWrapper(final IExpressionObjects expressionObjects) { super(5); this.expressionObjects = expressionObjects; } @Override public int size() { return super.size() + this.expressionObjects.size(); } @Override public boolean isEmpty() { return this.expressionObjects.size() == 0 && super.isEmpty(); } @Override public Object get(final Object key) { if (this.expressionObjects.containsObject(key.toString())) { return this.expressionObjects.getObject(key.toString()); } return super.get(key); } @Override public boolean containsKey(final Object key) { return this.expressionObjects.containsObject(key.toString()) || super.containsKey(key); } @Override public Object put(final String key, final Object value) {<FILL_FUNCTION_BODY>} @Override public void putAll(final Map<? extends String, ?> m) { // This will call put, and therefore perform the key name check super.putAll(m); } @Override public Object remove(final Object key) { if (this.expressionObjects.containsObject(key.toString())) { throw new IllegalArgumentException( "Cannot remove entry with key \"" + key + "\" from Expression Objects wrapper map: key matches the " + "name of one of the expression objects"); } return super.remove(key); } @Override public void clear() { throw new UnsupportedOperationException("Cannot clear Expression Objects wrapper map"); } @Override public boolean containsValue(final Object value) { throw new UnsupportedOperationException("Cannot perform by-value search on Expression Objects wrapper map"); } @Override public Object clone() { throw new UnsupportedOperationException("Cannot clone Expression Objects wrapper map"); } @Override public Set<String> keySet() { if (super.isEmpty()) { return this.expressionObjects.getObjectNames(); } final Set<String> keys = new LinkedHashSet<String>(this.expressionObjects.getObjectNames()); keys.addAll(super.keySet()); return keys; } @Override public Collection<Object> values() { return super.values(); } @Override public Set<Map.Entry<String, Object>> entrySet() { throw new UnsupportedOperationException( "Cannot retrieve a complete entry set for Expression Objects wrapper map. Get a key set instead"); } @Override public boolean equals(final Object o) { throw new UnsupportedOperationException( "Cannot execute equals operation on Expression Objects wrapper map"); } @Override public int hashCode() { throw new UnsupportedOperationException( "Cannot execute hashCode operation on Expression Objects wrapper map"); } @Override public String toString() { return "{EXPRESSION OBJECTS WRAPPER MAP FOR KEYS: " + keySet() + "}"; } }
if (this.expressionObjects.containsObject(key.toString())) { throw new IllegalArgumentException( "Cannot put entry with key \"" + key + "\" into Expression Objects wrapper map: key matches the " + "name of one of the expression objects"); } return super.put(key, value);
825
80
905
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public java.lang.Object compute(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public java.lang.Object computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends java.lang.Object>) ,public java.lang.Object computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public java.lang.Object merge(java.lang.String, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,? extends java.lang.Object>) ,public java.lang.Object put(java.lang.String, java.lang.Object) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.Object>) ,public java.lang.Object putIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.Object remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public java.lang.Object replace(java.lang.String, java.lang.Object) ,public boolean replace(java.lang.String, java.lang.Object, java.lang.Object) ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public int size() ,public Collection<java.lang.Object> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,java.lang.Object>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,java.lang.Object>[] table,int threshold
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/OrExpression.java
OrExpression
executeOr
class OrExpression extends BinaryOperationExpression { private static final long serialVersionUID = -8085738202412415337L; private static final Logger logger = LoggerFactory.getLogger(OrExpression.class); private static final String OPERATOR = "or"; static final String[] OPERATORS = new String[] {OPERATOR}; private static final boolean[] LENIENCIES = new boolean[] { false }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { OrExpression.class }; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = OrExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = OrExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } public OrExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(OPERATOR); } static boolean isRightAllowed(final IStandardExpression right) { return right != null && !(right instanceof Token && !(right instanceof BooleanTokenExpression)); } static boolean isLeftAllowed(final IStandardExpression left) { return left != null && !(left instanceof Token && !(left instanceof BooleanTokenExpression)); } static ExpressionParsingState composeOrExpression( final ExpressionParsingState state, final int inputIndex) { return composeBinaryOperationExpression( state, inputIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD); } static Object executeOr( final IExpressionContext context, final OrExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating OR expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final Object leftValue = expression.getLeft().execute(context, expContext); // Short circuit final boolean leftBooleanValue = EvaluationUtils.evaluateAsBoolean(leftValue); if (leftBooleanValue) { return Boolean.TRUE; } final Object rightValue = expression.getRight().execute(context, expContext); final boolean rightBooleanValue = EvaluationUtils.evaluateAsBoolean(rightValue); return Boolean.valueOf(rightBooleanValue);
626
177
803
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/RemainderExpression.java
RemainderExpression
executeRemainder
class RemainderExpression extends MultiplicationDivisionRemainderExpression { private static final long serialVersionUID = -8830009392616779821L; private static final Logger logger = LoggerFactory.getLogger(RemainderExpression.class); public RemainderExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(REMAINDER_OPERATOR); } static Object executeRemainder( final IExpressionContext context, final RemainderExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating remainder expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null) { leftValue = "null"; } if (rightValue == null) { rightValue = "null"; } final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { // Addition will act as a mathematical 'plus' return leftNumberValue.remainder(rightNumberValue); } throw new TemplateProcessingException( "Cannot execute division: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\"");
214
290
504
<methods><variables>protected static final java.lang.String DIVISION_OPERATOR,protected static final java.lang.String DIVISION_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String MULTIPLICATION_OPERATOR,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,protected static final java.lang.String REMAINDER_OPERATOR,protected static final java.lang.String REMAINDER_OPERATOR_2,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/SelectionVariableExpression.java
SelectionVariableExpression
executeSelectionVariableExpression
class SelectionVariableExpression extends SimpleExpression implements IStandardVariableExpression { private static final Logger logger = LoggerFactory.getLogger(SelectionVariableExpression.class); private static final long serialVersionUID = 854441190427550056L; static final char SELECTOR = '*'; private static final Pattern SELECTION_VAR_PATTERN = Pattern.compile("^\\s*\\*\\{(.+?)\\}\\s*$", Pattern.DOTALL); private final String expression; private final boolean convertToString; private volatile Object cachedExpression = null; public SelectionVariableExpression(final String expression) { this(expression, false); } /** * * @param expression expression * @param convertToString convertToString * @since 2.1.0 */ public SelectionVariableExpression(final String expression, final boolean convertToString) { super(); Validate.notNull(expression, "Expression cannot be null"); this.expression = expression; this.convertToString = convertToString; } public String getExpression() { return this.expression; } public boolean getUseSelectionAsRoot() { return true; } /** * * @return the result * @since 2.1.0 */ public boolean getConvertToString() { return this.convertToString; } // Meant only to be used internally, in order to avoid cache calls public Object getCachedExpression() { return this.cachedExpression; } // Meant only to be used internally, in order to avoid cache calls public void setCachedExpression(final Object cachedExpression) { this.cachedExpression = cachedExpression; } @Override public String getStringRepresentation() { return String.valueOf(SELECTOR) + String.valueOf(SimpleExpression.EXPRESSION_START_CHAR) + (this.convertToString? String.valueOf(SimpleExpression.EXPRESSION_START_CHAR) : "") + this.expression + (this.convertToString? String.valueOf(SimpleExpression.EXPRESSION_END_CHAR) : "") + String.valueOf(SimpleExpression.EXPRESSION_END_CHAR); } static SelectionVariableExpression parseSelectionVariableExpression(final String input) { final Matcher matcher = SELECTION_VAR_PATTERN.matcher(input); if (!matcher.matches()) { return null; } final String expression = matcher.group(1); final int expressionLen = expression.length(); if (expressionLen > 2 && expression.charAt(0) == SimpleExpression.EXPRESSION_START_CHAR && expression.charAt(expressionLen - 1) == SimpleExpression.EXPRESSION_END_CHAR) { // Double brackets = enable to-String conversion return new SelectionVariableExpression(expression.substring(1, expressionLen - 1), true); } return new SelectionVariableExpression(expression, false); } static Object executeSelectionVariableExpression( final IExpressionContext context, final SelectionVariableExpression expression, final IStandardVariableExpressionEvaluator expressionEvaluator, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating selection variable expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final StandardExpressionExecutionContext evalExpContext = (expression.getConvertToString()? expContext.withTypeConversion() : expContext.withoutTypeConversion()); final Object result = expressionEvaluator.evaluate(context, expression, evalExpContext); if (!expContext.getForbidUnsafeExpressionResults()) { return result; } // We are only allowing results of type Number and Boolean, and cosidering the rest of data types "unsafe", // as they could be rendered into a non-trustable String. This is mainly useful for helping prevent code // injection in th:on* event handlers. if (result == null || result instanceof Number || result instanceof Boolean) { return result; } throw new TemplateProcessingException( "Only variable expressions returning numbers or booleans are allowed in this context, any other data" + "types are not trusted in the context of this expression, including Strings or any other " + "object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. " + "\"onload\"), in which textual data from variables should better be output to \"data-*\" attributes and then " + "read from the event handler.");
880
367
1,247
<methods><variables>static final char EXPRESSION_END_CHAR,static final char EXPRESSION_START_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/SimpleExpression.java
SimpleExpression
executeSimple
class SimpleExpression extends Expression { private static final long serialVersionUID = 9145380484247069725L; static final char EXPRESSION_START_CHAR = '{'; static final char EXPRESSION_END_CHAR = '}'; protected SimpleExpression() { super(); } static Object executeSimple( final IExpressionContext context, final SimpleExpression expression, final IStandardVariableExpressionEvaluator expressionEvaluator, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (expression instanceof VariableExpression) { return VariableExpression.executeVariableExpression(context, (VariableExpression)expression, expressionEvaluator, expContext); } if (expression instanceof MessageExpression) { return MessageExpression.executeMessageExpression(context, (MessageExpression)expression, expContext); } if (expression instanceof TextLiteralExpression) { return TextLiteralExpression.executeTextLiteralExpression(context, (TextLiteralExpression)expression, expContext); } if (expression instanceof NumberTokenExpression) { return NumberTokenExpression.executeNumberTokenExpression(context, (NumberTokenExpression) expression, expContext); } if (expression instanceof BooleanTokenExpression) { return BooleanTokenExpression.executeBooleanTokenExpression(context, (BooleanTokenExpression) expression, expContext); } if (expression instanceof NullTokenExpression) { return NullTokenExpression.executeNullTokenExpression(context, (NullTokenExpression) expression, expContext); } if (expression instanceof LinkExpression) { // No expContext to be specified: link expressions always execute in RESTRICTED mode for the URL base and NORMAL for URL parameters return LinkExpression.executeLinkExpression(context, (LinkExpression)expression); } if (expression instanceof FragmentExpression) { // No expContext to be specified: fragment expressions always execute in RESTRICTED mode return FragmentExpression.executeFragmentExpression(context, (FragmentExpression)expression); } if (expression instanceof SelectionVariableExpression) { return SelectionVariableExpression.executeSelectionVariableExpression(context, (SelectionVariableExpression)expression, expressionEvaluator, expContext); } if (expression instanceof NoOpTokenExpression) { return NoOpTokenExpression.executeNoOpTokenExpression(context, (NoOpTokenExpression) expression, expContext); } if (expression instanceof GenericTokenExpression) { return GenericTokenExpression.executeGenericTokenExpression(context, (GenericTokenExpression) expression, expContext); } throw new TemplateProcessingException("Unrecognized simple expression: " + expression.getClass().getName());
169
503
672
<methods>public java.lang.Object execute(org.thymeleaf.context.IExpressionContext) ,public java.lang.Object execute(org.thymeleaf.context.IExpressionContext, org.thymeleaf.standard.expression.StandardExpressionExecutionContext) ,public abstract java.lang.String getStringRepresentation() ,public java.lang.String toString() <variables>public static final char NESTING_END_CHAR,public static final char NESTING_START_CHAR,public static final char PARSING_PLACEHOLDER_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/StandardExpressionExecutionContext.java
StandardExpressionExecutionContext
withTypeConversion
class StandardExpressionExecutionContext { public static final StandardExpressionExecutionContext RESTRICTED = new StandardExpressionExecutionContext(true, true, false, false); public static final StandardExpressionExecutionContext RESTRICTED_FORBID_UNSAFE_EXP_RESULTS = new StandardExpressionExecutionContext(true, true, true, false); public static final StandardExpressionExecutionContext NORMAL = new StandardExpressionExecutionContext(false, false, false, false); private static final StandardExpressionExecutionContext RESTRICTED_WITH_TYPE_CONVERSION = new StandardExpressionExecutionContext(true, true, false,true); private static final StandardExpressionExecutionContext RESTRICTED_FORBID_UNSAFE_EXP_RESULTS_WITH_TYPE_CONVERSION = new StandardExpressionExecutionContext(true, true, true, true); private static final StandardExpressionExecutionContext NORMAL_WITH_TYPE_CONVERSION = new StandardExpressionExecutionContext(false, false, false, true); private final boolean restrictVariableAccess; private final boolean restrictInstantiationAndStatic; private final boolean forbidUnsafeExpressionResults; private final boolean performTypeConversion; private StandardExpressionExecutionContext( final boolean restrictVariableAccess, final boolean restrictInstantiationAndStatic, final boolean forbidUnsafeExpressionResults, final boolean performTypeConversion) { super(); this.restrictVariableAccess = restrictVariableAccess; this.restrictInstantiationAndStatic = restrictInstantiationAndStatic; this.forbidUnsafeExpressionResults = forbidUnsafeExpressionResults; this.performTypeConversion = performTypeConversion; } public boolean getRestrictVariableAccess() { return this.restrictVariableAccess; } /** * Restricts whether this execution context restricts the instantiation of new objects and the * access to static classes. * * @return Whether this restriction should be applied or not. * @since 3.0.12 */ public boolean getRestrictInstantiationAndStatic() { return this.restrictInstantiationAndStatic; } public boolean getForbidUnsafeExpressionResults() { return this.forbidUnsafeExpressionResults; } public boolean getPerformTypeConversion() { return this.performTypeConversion; } public StandardExpressionExecutionContext withoutTypeConversion() { if (!getPerformTypeConversion()) { return this; } if (this == NORMAL_WITH_TYPE_CONVERSION) { return NORMAL; } if (this == RESTRICTED_WITH_TYPE_CONVERSION) { return RESTRICTED; } if (this == RESTRICTED_FORBID_UNSAFE_EXP_RESULTS_WITH_TYPE_CONVERSION) { return RESTRICTED_FORBID_UNSAFE_EXP_RESULTS; } return new StandardExpressionExecutionContext( getRestrictVariableAccess(), getRestrictInstantiationAndStatic(), getForbidUnsafeExpressionResults(), false); } public StandardExpressionExecutionContext withTypeConversion() {<FILL_FUNCTION_BODY>} }
if (getPerformTypeConversion()) { return this; } if (this == NORMAL) { return NORMAL_WITH_TYPE_CONVERSION; } if (this == RESTRICTED) { return RESTRICTED_WITH_TYPE_CONVERSION; } if (this == RESTRICTED_FORBID_UNSAFE_EXP_RESULTS) { return RESTRICTED_FORBID_UNSAFE_EXP_RESULTS_WITH_TYPE_CONVERSION; } return new StandardExpressionExecutionContext( getRestrictVariableAccess(), getRestrictInstantiationAndStatic(), getForbidUnsafeExpressionResults(), true);
807
181
988
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/StandardExpressionParser.java
StandardExpressionParser
parseEach
class StandardExpressionParser implements IStandardExpressionParser { public StandardExpressionParser() { super(); } public Expression parseExpression( final IExpressionContext context, final String input) { Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); return (Expression) parseExpression(context, input, true); } public AssignationSequence parseAssignationSequence( final IExpressionContext context, final String input, final boolean allowParametersWithoutValue) { Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); return AssignationUtils.parseAssignationSequence(context, input, allowParametersWithoutValue); } public ExpressionSequence parseExpressionSequence( final IExpressionContext context, final String input) { Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); return ExpressionSequenceUtils.parseExpressionSequence(context, input); } public Each parseEach( final IExpressionContext context, final String input) {<FILL_FUNCTION_BODY>} public FragmentSignature parseFragmentSignature(final IEngineConfiguration configuration, final String input) { Validate.notNull(configuration, "Configuration cannot be null"); Validate.notNull(input, "Input cannot be null"); return FragmentSignatureUtils.parseFragmentSignature(configuration, input); } static IStandardExpression parseExpression( final IExpressionContext context, final String input, final boolean preprocess) { final IEngineConfiguration configuration = context.getConfiguration(); final String preprocessedInput = (preprocess? StandardExpressionPreprocessor.preprocess(context, input) : input); final IStandardExpression cachedExpression = ExpressionCache.getExpressionFromCache(configuration, preprocessedInput); if (cachedExpression != null) { return cachedExpression; } final Expression expression = Expression.parse(preprocessedInput.trim()); if (expression == null) { throw new TemplateProcessingException("Could not parse as expression: \"" + input + "\""); } ExpressionCache.putExpressionIntoCache(configuration, preprocessedInput, expression); return expression; } @Override public String toString() { return "Standard Expression Parser"; } }
Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); return EachUtils.parseEach(context, input);
660
48
708
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/StandardExpressionPreprocessor.java
StandardExpressionPreprocessor
preprocess
class StandardExpressionPreprocessor { private static final char PREPROCESS_DELIMITER = '_'; private static final String PREPROCESS_EVAL = "\\_\\_(.*?)\\_\\_"; private static final Pattern PREPROCESS_EVAL_PATTERN = Pattern.compile(PREPROCESS_EVAL, Pattern.DOTALL); static String preprocess( final IExpressionContext context, final String input) {<FILL_FUNCTION_BODY>} private static String checkPreprocessingMarkUnescaping(final String input) { boolean structureFound = false; // for fast failing byte state = 0; // 1 = \, 2 = _, 3 = \, 4 = _ final int inputLen = input.length(); for (int i = 0; i < inputLen; i++) { final char c = input.charAt(i); if (c == '\\' && (state == 0 || state == 2)) { state++; continue; } if (c == '_' && state == 1) { state++; continue; } if (c == '_' && state == 3) { structureFound = true; break; } state = 0; } if (!structureFound) { // This avoids creating a new String object in the most common case (= nothing to unescape) return input; } state = 0; // 1 = \, 2 = _, 3 = \, 4 = _ final StringBuilder strBuilder = new StringBuilder(inputLen + 6); for (int i = 0; i < inputLen; i++) { final char c = input.charAt(i); if (c == '\\' && (state == 0 || state == 2)) { state++; strBuilder.append('\\'); } else if (c == '_' && state == 1) { state++; strBuilder.append('_'); } else if (c == '_' && state == 3) { state = 0; final int builderLen = strBuilder.length(); strBuilder.delete(builderLen - 3, builderLen); strBuilder.append("__"); } else { state = 0; strBuilder.append(c); } } return strBuilder.toString(); } private StandardExpressionPreprocessor() { super(); } }
if (input.indexOf(PREPROCESS_DELIMITER) == -1) { // Fail quick return input; } final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); if (!(expressionParser instanceof StandardExpressionParser)) { // Preprocess will be only available for the StandardExpressionParser, because the preprocessor // depends on this specific implementation of the parser. return input; } final Matcher matcher = PREPROCESS_EVAL_PATTERN.matcher(input); if (matcher.find()) { final StringBuilder strBuilder = new StringBuilder(input.length() + 24); int curr = 0; do { final String previousText = checkPreprocessingMarkUnescaping(input.substring(curr,matcher.start(0))); final String expressionText = checkPreprocessingMarkUnescaping(matcher.group(1)); strBuilder.append(previousText); final IStandardExpression expression = StandardExpressionParser.parseExpression(context, expressionText, false); if (expression == null) { return null; } final Object result = expression.execute(context, StandardExpressionExecutionContext.RESTRICTED); strBuilder.append(result); curr = matcher.end(0); } while (matcher.find()); final String remaining = checkPreprocessingMarkUnescaping(input.substring(curr)); strBuilder.append(remaining); return strBuilder.toString().trim(); } return checkPreprocessingMarkUnescaping(input);
634
435
1,069
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/StandardExpressions.java
StandardExpressions
getExpressionParser
class StandardExpressions { /** * Name used for registering the <i>Standard Variable Expression Evaluator</i> object as an * <i>execution attribute</i> at the Standard Dialects. */ public static final String STANDARD_VARIABLE_EXPRESSION_EVALUATOR_ATTRIBUTE_NAME = "StandardVariableExpressionEvaluator"; /** * Name used for registering the <i>Standard Expression Parser</i> object as an * <i>execution attribute</i> at the Standard Dialects. */ public static final String STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME = "StandardExpressionParser"; /** * Name used for registering the <i>Standard Conversion Service</i> object as an * <i>execution attribute</i> at the Standard Dialects. */ public static final String STANDARD_CONVERSION_SERVICE_ATTRIBUTE_NAME = "StandardConversionService"; private StandardExpressions() { super(); } /** * <p> * Obtain the expression parser (implementation of {@link IStandardExpressionParser}) registered by * the Standard Dialect that is being currently used. * </p> * * @param configuration the configuration object for the current template execution environment. * @return the parser object. */ public static IStandardExpressionParser getExpressionParser(final IEngineConfiguration configuration) {<FILL_FUNCTION_BODY>} /** * <p> * Obtain the variable expression evaluator (implementation of {@link IStandardVariableExpressionEvaluator}) * registered by the Standard Dialect that is being currently used. * </p> * <p> * Normally, there should be no need to obtain this object from the developers' code (only internally from * {@link IStandardExpression} implementations). * </p> * * @param configuration the configuration object for the current template execution environment. * @return the variable expression evaluator object. */ public static IStandardVariableExpressionEvaluator getVariableExpressionEvaluator(final IEngineConfiguration configuration) { final Object expressionEvaluator = configuration.getExecutionAttributes().get(STANDARD_VARIABLE_EXPRESSION_EVALUATOR_ATTRIBUTE_NAME); if (expressionEvaluator == null || (!(expressionEvaluator instanceof IStandardVariableExpressionEvaluator))) { throw new TemplateProcessingException( "No Standard Variable Expression Evaluator has been registered as an execution argument. " + "This is a requirement for using Standard Expressions, and might happen " + "if neither the Standard or the SpringStandard dialects have " + "been added to the Template Engine and none of the specified dialects registers an " + "attribute of type " + IStandardVariableExpressionEvaluator.class.getName() + " with name " + "\"" + STANDARD_VARIABLE_EXPRESSION_EVALUATOR_ATTRIBUTE_NAME + "\""); } return (IStandardVariableExpressionEvaluator) expressionEvaluator; } /** * <p> * Obtain the conversion service (implementation of {@link IStandardConversionService}) registered by * the Standard Dialect that is being currently used. * </p> * * @param configuration the configuration object for the current template execution environment. * @return the conversion service object. */ public static IStandardConversionService getConversionService(final IEngineConfiguration configuration) { final Object conversionService = configuration.getExecutionAttributes().get(STANDARD_CONVERSION_SERVICE_ATTRIBUTE_NAME); if (conversionService == null || (!(conversionService instanceof IStandardConversionService))) { throw new TemplateProcessingException( "No Standard Conversion Service has been registered as an execution argument. " + "This is a requirement for using Standard Expressions, and might happen " + "if neither the Standard or the SpringStandard dialects have " + "been added to the Template Engine and none of the specified dialects registers an " + "attribute of type " + IStandardConversionService.class.getName() + " with name " + "\"" + STANDARD_CONVERSION_SERVICE_ATTRIBUTE_NAME + "\""); } return (IStandardConversionService) conversionService; } }
final Object parser = configuration.getExecutionAttributes().get(STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME); if (parser == null || (!(parser instanceof IStandardExpressionParser))) { throw new TemplateProcessingException( "No Standard Expression Parser has been registered as an execution argument. " + "This is a requirement for using Standard Expressions, and might happen " + "if neither the Standard or the SpringStandard dialects have " + "been added to the Template Engine and none of the specified dialects registers an " + "attribute of type " + IStandardExpressionParser.class.getName() + " with name " + "\"" + STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME + "\""); } return (IStandardExpressionParser) parser;
1,119
198
1,317
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/SubtractionExpression.java
SubtractionExpression
executeSubtraction
class SubtractionExpression extends AdditionSubtractionExpression { private static final long serialVersionUID = 4125686854902098944L; private static final Logger logger = LoggerFactory.getLogger(SubtractionExpression.class); public SubtractionExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(SUBTRACTION_OPERATOR); } static Object executeSubtraction( final IExpressionContext context, final SubtractionExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating subtraction expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null) { leftValue = "null"; } if (rightValue == null) { rightValue = "null"; } final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { // Addition will act as a mathematical 'plus' return leftNumberValue.subtract(rightNumberValue); } throw new TemplateProcessingException( "Cannot execute subtraction: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\"");
213
292
505
<methods><variables>protected static final java.lang.String ADDITION_OPERATOR,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,protected static final java.lang.String SUBTRACTION_OPERATOR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/TextLiteralExpression.java
TextLiteralExpression
unescapeLiteral
class TextLiteralExpression extends SimpleExpression { private static final Logger logger = LoggerFactory.getLogger(TextLiteralExpression.class); private static final long serialVersionUID = 6511847028638506552L; static final char ESCAPE_PREFIX = '\\'; static final char DELIMITER = '\''; private final LiteralValue value; public TextLiteralExpression(final String value) { super(); Validate.notNull(value, "Value cannot be null"); this.value = new LiteralValue(unwrapLiteral(value)); } public LiteralValue getValue() { return this.value; } private static String unwrapLiteral(final String input) { // We know input is not null final int inputLen = input.length(); if (inputLen > 1 && input.charAt(0) == '\'' && input.charAt(inputLen - 1) == '\'') { return unescapeLiteral(input.substring(1, inputLen - 1)); } return input; } @Override public String getStringRepresentation() { return String.valueOf(DELIMITER) + this.value.getValue().replace(String.valueOf(DELIMITER),("\\" + DELIMITER)) + String.valueOf(DELIMITER); } static TextLiteralExpression parseTextLiteralExpression(final String input) { return new TextLiteralExpression(input); } static Object executeTextLiteralExpression( final IExpressionContext context, final TextLiteralExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating text literal: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return expression.getValue(); } public static String wrapStringIntoLiteral(final String str) { if (str == null) { return null; } int n = str.length(); while (n-- != 0) { if (str.charAt(n) == '\'') { final StringBuilder strBuilder = new StringBuilder(str.length() + 5); strBuilder.append('\''); final int strLen = str.length(); for (int i = 0; i < strLen; i++) { final char c = str.charAt(i); if (c == '\'') { strBuilder.append('\\'); } strBuilder.append(c); } strBuilder.append('\''); return strBuilder.toString(); } } return '\'' + str + '\''; } static boolean isDelimiterEscaped(final String input, final int pos) { // Only an odd number of \'s will indicate escaping if (pos == 0 || input.charAt(pos - 1) != '\\') { return false; } int i = pos - 1; boolean odd = false; while (i >= 0) { if (input.charAt(i) == '\\') { odd = !odd; } else { return odd; } i--; } return odd; } /* * This unescape operation will perform two transformations: * \' -> ' * \\ -> \ */ private static String unescapeLiteral(final String text) {<FILL_FUNCTION_BODY>} }
if (text == null) { return null; } StringBuilder strBuilder = null; final int max = text.length(); int readOffset = 0; int referenceOffset = 0; char c; for (int i = 0; i < max; i++) { c = text.charAt(i); /* * Check the need for an unescape operation at this point */ if (c != ESCAPE_PREFIX || (i + 1) >= max) { continue; } if (c == ESCAPE_PREFIX) { switch (text.charAt(i + 1)) { case '\'': c = '\''; referenceOffset = i + 1; break; case '\\': c = '\\'; referenceOffset = i + 1; break; // We weren't able to consume any valid escape chars, just not consider it an escape operation default: referenceOffset = i; break; } } /* * At this point we know for sure we will need some kind of unescape, so we * can increase the offset and initialize the string builder if needed, along with * copying to it all the contents pending up to this point. */ if (strBuilder == null) { strBuilder = new StringBuilder(max + 5); } if (i - readOffset > 0) { strBuilder.append(text, readOffset, i); } i = referenceOffset; readOffset = i + 1; /* * Write the unescaped char */ strBuilder.append(c); } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: return the original String object if no unescape was actually needed. Otherwise * append the remaining escaped text to the string builder and return. * ----------------------------------------------------------------------------------------------- */ if (strBuilder == null) { return text; } if (max - readOffset > 0) { strBuilder.append(text, readOffset, max); } return strBuilder.toString();
954
541
1,495
<methods><variables>static final char EXPRESSION_END_CHAR,static final char EXPRESSION_START_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/Token.java
Token
isTokenChar
class Token extends SimpleExpression { private static final long serialVersionUID = 4357087922344497120L; private final Object value; protected Token(final Object value) { super(); this.value = value; } public Object getValue() { return this.value; } public String getStringRepresentation() { return this.value.toString(); // Tokens are fine not using the conversion service } @Override public String toString() { return getStringRepresentation(); } public static boolean isTokenChar(final String context, final int pos) {<FILL_FUNCTION_BODY>} public static final class TokenParsingTracer { public static final char TOKEN_SUBSTITUTE = '#'; private TokenParsingTracer() { super(); } public static String trace(final String input) { final int inputLen = input.length(); final StringBuilder strBuilder = new StringBuilder(inputLen + 1); for (int i = 0; i < inputLen; i++) { if (isTokenChar(input, i)) { strBuilder.append(TOKEN_SUBSTITUTE); } else { strBuilder.append(input.charAt(i)); } } return strBuilder.toString(); } } }
/* * TOKEN chars: A-Za-z0-9[]._ (plus '-' in some contexts) * (additionally, also, a series of internationalized characters: accents, other alphabets, etc.) * * '-' can also be a numeric operator, so it will only be considered a token char if: * * there are immediately previous chars which we can consider a token, but not a numeric token * * there are immediately following chars which we can consider a token, but not a numeric token * */ final char c = context.charAt(pos); /* * First, the most common true's */ if (c >= 'a' && c <= 'z') { return true; } if (c >= 'A' && c <= 'Z') { return true; } if (c >= '0' && c <= '9') { return true; } /* * The most common false's now, for failing fast */ if (c == ' ' || c == '\n' || c == '(' || c == ')' || c == '\'' || c == '"' || c == '<' || c == '>' || c == '{' || c == '}' || c == '=' || c == ',' || c == ';' || c == ':' || c == '+' || c == '*' || c == '$' || c == '%' || c == '&' || c == '#') { return false; } /* * Some more (less common) true's */ if (c == '[' || c == ']' || c == '.' || c == '_') { return true; } /* * A special case: the dash */ if (c == '-') { if (pos > 0) { // let's scan backwards, looking for a token char that is not a number for (int i = pos - 1; i >= 0; i--) { if (!isTokenChar(context,i)) { break; } final char cc = context.charAt(i); if (!((cc >= '0' && cc <= '9') || cc == '.')) { // It is a token, but not a digit or ., so the dash is not an operator, it is a token char return true; } } } final int contextLen = context.length(); if (pos + 1 < contextLen) { // let's scan forward, looking for a token char that is not a number for (int i = pos + 1; i < contextLen; i++) { final char cc = context.charAt(i); if (cc == '-') { // We need to avoid cycles (which would happen if we call "isTokenChar" again) return true; } if (!isTokenChar(context,i)) { break; } if (!((cc >= '0' && cc <= '9') || cc == '.')) { // It is a token, but not a digit or ., so the dash is not an operator, it is a token char return true; } } } return false; } /* * Finally, the rest of the true's */ if (c == '\u00B7') { return true; } if (c >= '\u00C0' && c <= '\u00D6') { return true; } if (c >= '\u00D8' && c <= '\u00F6') { return true; } if (c >= '\u00F8' && c <= '\u02FF') { return true; } if (c >= '\u0300' && c <= '\u036F') { return true; } if (c >= '\u0370' && c <= '\u037D') { return true; } if (c >= '\u037F' && c <= '\u1FFF') { return true; } if (c >= '\u200C' && c <= '\u200D') { return true; } if (c >= '\u203F' && c <= '\u2040') { return true; } if (c >= '\u2070' && c <= '\u218F') { return true; } if (c >= '\u2C00' && c <= '\u2FEF') { return true; } if (c >= '\u3001' && c <= '\uD7FF') { return true; } if (c >= '\uF900' && c <= '\uFDCF') { return true; } if (c >= '\uFDF0' && c <= '\uFFFD') { return true; } return (c >= '\uFDF0' && c <= '\uFFFD');
398
1,298
1,696
<methods><variables>static final char EXPRESSION_END_CHAR,static final char EXPRESSION_START_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/VariableExpression.java
VariableExpression
executeVariableExpression
class VariableExpression extends SimpleExpression implements IStandardVariableExpression { private static final Logger logger = LoggerFactory.getLogger(VariableExpression.class); private static final long serialVersionUID = -4911752782987240708L; static final char SELECTOR = '$'; private static final Pattern VAR_PATTERN = Pattern.compile("^\\s*\\$\\{(.+?)\\}\\s*$", Pattern.DOTALL); static final Expression NULL_VALUE = VariableExpression.parseVariableExpression("${null}"); private final String expression; private final boolean convertToString; private volatile Object cachedExpression = null; public VariableExpression(final String expression) { this(expression, false); } /** * * @param expression expression * @param convertToString convertToString * @since 2.1.0 */ public VariableExpression(final String expression, final boolean convertToString) { super(); Validate.notNull(expression, "Expression cannot be null"); this.expression = expression; this.convertToString = convertToString; } public String getExpression() { return this.expression; } public boolean getUseSelectionAsRoot() { return false; } /** * * @return the result * @since 2.1.0 */ public boolean getConvertToString() { return this.convertToString; } // Meant only to be used internally, in order to avoid cache calls public Object getCachedExpression() { return this.cachedExpression; } // Meant only to be used internally, in order to avoid cache calls public void setCachedExpression(final Object cachedExpression) { this.cachedExpression = cachedExpression; } @Override public String getStringRepresentation() { return String.valueOf(SELECTOR) + String.valueOf(SimpleExpression.EXPRESSION_START_CHAR) + (this.convertToString? String.valueOf(SimpleExpression.EXPRESSION_START_CHAR) : "") + this.expression + (this.convertToString? String.valueOf(SimpleExpression.EXPRESSION_END_CHAR) : "") + String.valueOf(SimpleExpression.EXPRESSION_END_CHAR); } static VariableExpression parseVariableExpression(final String input) { final Matcher matcher = VAR_PATTERN.matcher(input); if (!matcher.matches()) { return null; } final String expression = matcher.group(1); final int expressionLen = expression.length(); if (expressionLen > 2 && expression.charAt(0) == SimpleExpression.EXPRESSION_START_CHAR && expression.charAt(expressionLen - 1) == SimpleExpression.EXPRESSION_END_CHAR) { // Double brackets = enable to-String conversion return new VariableExpression(expression.substring(1, expressionLen - 1), true); } return new VariableExpression(expression, false); } static Object executeVariableExpression( final IExpressionContext context, final VariableExpression expression, final IStandardVariableExpressionEvaluator expressionEvaluator, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating variable expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final StandardExpressionExecutionContext evalExpContext = (expression.getConvertToString()? expContext.withTypeConversion() : expContext.withoutTypeConversion()); final Object result = expressionEvaluator.evaluate(context, expression, evalExpContext); if (!expContext.getForbidUnsafeExpressionResults()) { return result; } // We are only allowing results of type Number and Boolean, and cosidering the rest of data types "unsafe", // as they could be rendered into a non-trustable String. This is mainly useful for helping prevent code // injection in th:on* event handlers. if (result == null || result instanceof Number || result instanceof Boolean) { return result; } throw new TemplateProcessingException( "Only variable expressions returning numbers or booleans are allowed in this context, any other data" + "types are not trusted in the context of this expression, including Strings or any other " + "object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. " + "\"onload\"), in which textual data from variables should better be output to \"data-*\" attributes and then " + "read from the event handler.");
906
366
1,272
<methods><variables>static final char EXPRESSION_END_CHAR,static final char EXPRESSION_START_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/inline/StandardCSSInliner.java
StandardCSSInliner
produceEscapedOutput
class StandardCSSInliner extends AbstractStandardInliner { private final IStandardCSSSerializer serializer; public StandardCSSInliner(final IEngineConfiguration configuration) { super(configuration, TemplateMode.CSS); this.serializer = StandardSerializers.getCSSSerializer(configuration); } @Override protected String produceEscapedOutput(final Object input) {<FILL_FUNCTION_BODY>} }
final Writer cssWriter = new FastStringWriter(input instanceof String? ((String)input).length() * 2 : 20); this.serializer.serializeValue(input, cssWriter); return cssWriter.toString();
115
59
174
<methods>public final java.lang.String getName() ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment) <variables>private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode,private final non-sealed boolean writeTextsToOutput
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/inline/StandardHTMLInliner.java
StandardHTMLInliner
produceEscapedOutput
class StandardHTMLInliner extends AbstractStandardInliner { public StandardHTMLInliner(final IEngineConfiguration configuration) { super(configuration, TemplateMode.HTML); } @Override protected String produceEscapedOutput(final Object input) {<FILL_FUNCTION_BODY>} }
if (input == null) { return ""; } return HtmlEscape.escapeHtml4Xml(input.toString());
81
36
117
<methods>public final java.lang.String getName() ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment) <variables>private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode,private final non-sealed boolean writeTextsToOutput
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/inline/StandardJavaScriptInliner.java
StandardJavaScriptInliner
produceEscapedOutput
class StandardJavaScriptInliner extends AbstractStandardInliner { private final IStandardJavaScriptSerializer serializer; public StandardJavaScriptInliner(final IEngineConfiguration configuration) { super(configuration, TemplateMode.JAVASCRIPT); this.serializer = StandardSerializers.getJavaScriptSerializer(configuration); } @Override protected String produceEscapedOutput(final Object input) {<FILL_FUNCTION_BODY>} }
final Writer jsWriter = new FastStringWriter(input instanceof String? ((String)input).length() * 2 : 20); this.serializer.serializeValue(input, jsWriter); return jsWriter.toString();
118
59
177
<methods>public final java.lang.String getName() ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment) <variables>private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode,private final non-sealed boolean writeTextsToOutput
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/inline/StandardTextInliner.java
StandardTextInliner
produceEscapedOutput
class StandardTextInliner extends AbstractStandardInliner { public StandardTextInliner(final IEngineConfiguration configuration) { super(configuration, TemplateMode.TEXT); } @Override protected String produceEscapedOutput(final Object input) {<FILL_FUNCTION_BODY>} }
if (input == null) { return ""; } return HtmlEscape.escapeHtml4Xml(input.toString());
81
36
117
<methods>public final java.lang.String getName() ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment) <variables>private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode,private final non-sealed boolean writeTextsToOutput
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/inline/StandardXMLInliner.java
StandardXMLInliner
produceEscapedOutput
class StandardXMLInliner extends AbstractStandardInliner { public StandardXMLInliner(final IEngineConfiguration configuration) { super(configuration, TemplateMode.XML); } @Override protected String produceEscapedOutput(final Object input) {<FILL_FUNCTION_BODY>} }
if (input == null) { return ""; } // Note we are outputting a body content here, so it is important that we use the version // of XML escaping meant for content, not attributes (slight differences) return XmlEscape.escapeXml10(input.toString());
81
76
157
<methods>public final java.lang.String getName() ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection) ,public final java.lang.CharSequence inline(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment) <variables>private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode,private final non-sealed boolean writeTextsToOutput
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardAssertionTagProcessor.java
AbstractStandardAssertionTagProcessor
doProcess
class AbstractStandardAssertionTagProcessor extends AbstractAttributeTagProcessor { protected AbstractStandardAssertionTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, true); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmptyOrWhitespace(attributeValue)) { return; } final ExpressionSequence expressionSequence = ExpressionSequenceUtils.parseExpressionSequence(context, attributeValue); final List<IStandardExpression> expressions = expressionSequence.getExpressions(); for (final IStandardExpression expression : expressions) { final Object expressionResult = expression.execute(context); final boolean expressionBooleanResult = EvaluationUtils.evaluateAsBoolean(expressionResult); if (!expressionBooleanResult) { throw new TemplateAssertionException( expression.getStringRepresentation(), tag.getTemplateName(), tag.getAttribute(attributeName).getLine(), tag.getAttribute(attributeName).getCol()); } }
154
185
339
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardAttributeModifierTagProcessor.java
AbstractStandardAttributeModifierTagProcessor
doProcess
class AbstractStandardAttributeModifierTagProcessor extends AbstractStandardExpressionAttributeTagProcessor implements IAttributeDefinitionsAware { private final boolean removeIfEmpty; private final String targetAttrCompleteName; private AttributeDefinition targetAttributeDefinition; /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeIfEmpty) { this(templateMode, dialectPrefix, attrName, attrName, precedence, removeIfEmpty); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * @param restrictedExpressionExecution whether the expression to be executed (value of the attribute) should * be executed in restricted mode (no parameter access) or not (default: false). * * @since 3.0.9 */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeIfEmpty, final boolean restrictedExpressionExecution) { this(templateMode, dialectPrefix, attrName, attrName, precedence, removeIfEmpty, restrictedExpressionExecution); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * @param expressionExecutionContext the expression execution context to be applied. * * @since 3.0.10 */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeIfEmpty, final StandardExpressionExecutionContext expressionExecutionContext) { this(templateMode, dialectPrefix, attrName, attrName, precedence, removeIfEmpty, expressionExecutionContext); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param targetAttrCompleteName complete name of target attribute. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final String targetAttrCompleteName, final int precedence, final boolean removeIfEmpty) { super(templateMode, dialectPrefix, attrName, precedence, false); Validate.notNull(targetAttrCompleteName, "Complete name of target attribute cannot be null"); this.targetAttrCompleteName = targetAttrCompleteName; this.removeIfEmpty = removeIfEmpty; } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param targetAttrCompleteName complete name of target attribut. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * @param restrictedExpressionExecution whether the expression to be executed (value of the attribute) should * be executed in restricted mode (no parameter access) or not (default: false). * * @since 3.0.9 */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final String targetAttrCompleteName, final int precedence, final boolean removeIfEmpty, final boolean restrictedExpressionExecution) { super(templateMode, dialectPrefix, attrName, precedence, false, restrictedExpressionExecution); Validate.notNull(targetAttrCompleteName, "Complete name of target attribute cannot be null"); this.targetAttrCompleteName = targetAttrCompleteName; this.removeIfEmpty = removeIfEmpty; } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode. * @param dialectPrefix the dialect prefix. * @param attrName the attribute name to be matched. * @param targetAttrCompleteName complete name of target attribut. * @param precedence the precedence to be applied. * @param removeIfEmpty whether the attribute should be removed if the result of executing the expression is empty. * @param expressionExecutionContext the expression execution context to be applied. * * @since 3.0.10 */ protected AbstractStandardAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final String targetAttrCompleteName, final int precedence, final boolean removeIfEmpty, final StandardExpressionExecutionContext expressionExecutionContext) { super(templateMode, dialectPrefix, attrName, precedence, false, expressionExecutionContext); Validate.notNull(targetAttrCompleteName, "Complete name of target attribute cannot be null"); this.targetAttrCompleteName = targetAttrCompleteName; this.removeIfEmpty = removeIfEmpty; } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) { Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinition of the target attribute in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.targetAttributeDefinition = attributeDefinitions.forName(getTemplateMode(), this.targetAttrCompleteName); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), expressionResult == null ? null : expressionResult.toString()); // These attributes might be "removable if empty", in which case we would simply remove the target attribute... if (this.removeIfEmpty && (newAttributeValue == null || newAttributeValue.length() == 0)) { // We are removing the equivalent attribute name, without the prefix... structureHandler.removeAttribute(this.targetAttributeDefinition.getAttributeName()); structureHandler.removeAttribute(attributeName); } else { // We are setting the equivalent attribute name, without the prefix... StandardProcessorUtils.replaceAttribute( structureHandler, attributeName, this.targetAttributeDefinition, this.targetAttrCompleteName, (newAttributeValue == null ? "" : newAttributeValue)); }
1,800
206
2,006
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardConditionalVisibilityTagProcessor.java
AbstractStandardConditionalVisibilityTagProcessor
doProcess
class AbstractStandardConditionalVisibilityTagProcessor extends AbstractAttributeTagProcessor { /* * It is IMPORTANT THAT THIS CLASS DOES NOT EXTEND FROM AbstractStandardExpressionAttributeTagProcessor because * such thing would mean that the expression would be evaluated in the parent class, and this would affect * the th:case attribute processor, because no shortcut would be possible: once one "th:case" evaluates to true, * the rest of th:case in the same th:switch should not be evaluated AT ALL. */ protected AbstractStandardConditionalVisibilityTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, true); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract boolean isVisible( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue); }
final boolean visible = isVisible(context, tag, attributeName, attributeValue); if (!visible) { structureHandler.removeElement(); }
308
43
351
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardDoubleAttributeModifierTagProcessor.java
AbstractStandardDoubleAttributeModifierTagProcessor
doProcess
class AbstractStandardDoubleAttributeModifierTagProcessor extends AbstractStandardExpressionAttributeTagProcessor implements IAttributeDefinitionsAware { private final boolean removeIfEmpty; private final String attributeOneCompleteName; private final String attributeTwoCompleteName; private AttributeDefinition attributeOneDefinition; private AttributeDefinition attributeTwoDefinition; protected AbstractStandardDoubleAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final String attributeOneCompleteName, final String attributeTwoCompleteName, final boolean removeIfEmpty) { super(templateMode, dialectPrefix, attrName, precedence, true, false); Validate.notNull(attributeOneCompleteName, "Complete name of attribute one cannot be null"); Validate.notNull(attributeTwoCompleteName, "Complete name of attribute one cannot be null"); this.removeIfEmpty = removeIfEmpty; this.attributeOneCompleteName = attributeOneCompleteName; this.attributeTwoCompleteName = attributeTwoCompleteName; } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) { Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinitions of the target attributes in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.attributeOneDefinition = attributeDefinitions.forName(getTemplateMode(), this.attributeOneCompleteName); this.attributeTwoDefinition = attributeDefinitions.forName(getTemplateMode(), this.attributeTwoCompleteName); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), expressionResult == null ? null : expressionResult.toString()); // These attributes might be "removable if empty", in which case we would simply remove the target attributes... if (this.removeIfEmpty && (newAttributeValue == null || newAttributeValue.length() == 0)) { // We are removing the equivalent attribute name, without the prefix... structureHandler.removeAttribute(this.attributeOneDefinition.getAttributeName()); structureHandler.removeAttribute(this.attributeTwoDefinition.getAttributeName()); } else { // We are setting the equivalent attribute name, without the prefix... StandardProcessorUtils.setAttribute(structureHandler, this.attributeOneDefinition, this.attributeOneCompleteName, newAttributeValue); StandardProcessorUtils.setAttribute(structureHandler, this.attributeTwoDefinition, this.attributeTwoCompleteName, newAttributeValue); }
492
224
716
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardExpressionAttributeTagProcessor.java
AbstractStandardExpressionAttributeTagProcessor
doProcess
class AbstractStandardExpressionAttributeTagProcessor extends AbstractAttributeTagProcessor { private final StandardExpressionExecutionContext expressionExecutionContext; private final boolean removeIfNoop; /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode * @param dialectPrefix the dialect prefox * @param attrName the attribute name to be matched * @param precedence the precedence to be applied * @param removeAttribute whether the attribute should be removed after execution * */ protected AbstractStandardExpressionAttributeTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeAttribute) { this(templateMode, dialectPrefix, attrName, precedence, removeAttribute, StandardExpressionExecutionContext.NORMAL); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode * @param dialectPrefix the dialect prefox * @param attrName the attribute name to be matched * @param precedence the precedence to be applied * @param removeAttribute whether the attribute should be removed after execution * @param restrictedExpressionExecution whether the expression to be executed (value of the attribute) should * be executed in restricted mode (no parameter access) or not (default: false). * * @since 3.0.9 */ protected AbstractStandardExpressionAttributeTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeAttribute, final boolean restrictedExpressionExecution) { this(templateMode, dialectPrefix, attrName, precedence, removeAttribute, (restrictedExpressionExecution? StandardExpressionExecutionContext.RESTRICTED : StandardExpressionExecutionContext.NORMAL)); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode * @param dialectPrefix the dialect prefox * @param attrName the attribute name to be matched * @param precedence the precedence to be applied * @param removeAttribute whether the attribute should be removed after execution * @param expressionExecutionContext the expression execution context to be applied * * @since 3.0.10 */ protected AbstractStandardExpressionAttributeTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final boolean removeAttribute, final StandardExpressionExecutionContext expressionExecutionContext) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, removeAttribute); this.removeIfNoop = !removeAttribute; this.expressionExecutionContext = expressionExecutionContext; } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler); }
final Object expressionResult; if (attributeValue != null) { final IStandardExpression expression = EngineEventUtils.computeAttributeExpression(context, tag, attributeName, attributeValue); if (expression != null && expression instanceof FragmentExpression) { // This is merely a FragmentExpression (not complex, not combined with anything), so we can apply a shortcut // so that we don't require a "null" result for this expression if the template does not exist. That will // save a call to resource.exists() which might be costly. final FragmentExpression.ExecutedFragmentExpression executedFragmentExpression = FragmentExpression.createExecutedFragmentExpression(context, (FragmentExpression) expression); expressionResult = FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true); } else { /* * Some attributes will require the execution of the expressions contained in them in RESTRICTED * mode, so that e.g. access to request parameters is forbidden. */ expressionResult = expression.execute(context, this.expressionExecutionContext); } } else { expressionResult = null; } // If the result of this expression is NO-OP, there is nothing to execute if (expressionResult == NoOpToken.VALUE) { if (this.removeIfNoop) { structureHandler.removeAttribute(attributeName); } return; } doProcess( context, tag, attributeName, attributeValue, expressionResult, structureHandler);
839
382
1,221
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardMultipleAttributeModifierTagProcessor.java
AbstractStandardMultipleAttributeModifierTagProcessor
doProcess
class AbstractStandardMultipleAttributeModifierTagProcessor extends AbstractAttributeTagProcessor { protected enum ModificationType { SUBSTITUTION, APPEND, PREPEND, APPEND_WITH_SPACE, PREPEND_WITH_SPACE } private final ModificationType modificationType; private final boolean restrictedExpressionExecution; /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode * @param dialectPrefix the dialect prefox * @param attrName the attribute name to be matched * @param precedence the precedence to be applied * @param modificationType type of modification to be performed on the attribute (replacement, append, prepend) * */ protected AbstractStandardMultipleAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final ModificationType modificationType) { this(templateMode, dialectPrefix, attrName, precedence, modificationType, false); } /** * <p> * Build a new instance of this tag processor. * </p> * * @param templateMode the template mode * @param dialectPrefix the dialect prefox * @param attrName the attribute name to be matched * @param precedence the precedence to be applied * @param modificationType type of modification to be performed on the attribute (replacement, append, prepend) * @param restrictedExpressionExecution whether the expression to be executed (value of the attribute) should * be executed in restricted mode (no parameter acess) or not. * * @since 3.0.9 */ protected AbstractStandardMultipleAttributeModifierTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence, final ModificationType modificationType, final boolean restrictedExpressionExecution) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, true); this.modificationType = modificationType; this.restrictedExpressionExecution = restrictedExpressionExecution; } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final AssignationSequence assignations = AssignationUtils.parseAssignationSequence( context, attributeValue, false /* no parameters without value */); if (assignations == null) { throw new TemplateProcessingException( "Could not parse value as attribute assignations: \"" + attributeValue + "\""); } // Compute the required execution context depending on whether execution should be restricted or not final StandardExpressionExecutionContext expCtx = (this.restrictedExpressionExecution? StandardExpressionExecutionContext.RESTRICTED : StandardExpressionExecutionContext.NORMAL); final List<Assignation> assignationValues = assignations.getAssignations(); final int assignationValuesLen = assignationValues.size(); for (int i = 0; i < assignationValuesLen; i++) { final Assignation assignation = assignationValues.get(i); final IStandardExpression leftExpr = assignation.getLeft(); final Object leftValue = leftExpr.execute(context, expCtx); final IStandardExpression rightExpr = assignation.getRight(); final Object rightValue = rightExpr.execute(context, expCtx); if (rightValue == NoOpToken.VALUE) { // No changes to be done for this attribute continue; } final String newAttributeName = (leftValue == null? null : leftValue.toString()); if (StringUtils.isEmptyOrWhitespace(newAttributeName)) { throw new TemplateProcessingException( "Attribute name expression evaluated as null or empty: \"" + leftExpr + "\""); } if (getTemplateMode() == TemplateMode.HTML && this.modificationType == ModificationType.SUBSTITUTION && ArrayUtils.contains(StandardConditionalFixedValueTagProcessor.ATTR_NAMES, newAttributeName)) { // Attribute is a fixed-value conditional one, like "selected", which can only // appear as selected="selected" or not appear at all. if (EvaluationUtils.evaluateAsBoolean(rightValue)) { structureHandler.setAttribute(newAttributeName, newAttributeName); } else { structureHandler.removeAttribute(newAttributeName); } } else { // Attribute is a "normal" attribute, not a fixed-value conditional one - or we are not just replacing final String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), rightValue == null ? null : rightValue.toString()); if (newAttributeValue == null || newAttributeValue.length() == 0) { if (this.modificationType == ModificationType.SUBSTITUTION) { // Substituting by a no-value will be equivalent to simply removing structureHandler.removeAttribute(newAttributeName); } // Prepend and append simply ignored in this case } else { if (this.modificationType == ModificationType.SUBSTITUTION || !tag.hasAttribute(newAttributeName) || tag.getAttributeValue(newAttributeName).length() == 0) { // Normal value replace structureHandler.setAttribute(newAttributeName, newAttributeValue); } else { String currentValue = tag.getAttributeValue(newAttributeName); if (this.modificationType == ModificationType.APPEND) { structureHandler.setAttribute(newAttributeName, currentValue + newAttributeValue); } else if (this.modificationType == ModificationType.APPEND_WITH_SPACE) { structureHandler.setAttribute(newAttributeName, currentValue + ' ' + newAttributeValue); } else if (this.modificationType == ModificationType.PREPEND) { structureHandler.setAttribute(newAttributeName, newAttributeValue + currentValue); } else { // modification type is PREPEND_WITH_SPACE structureHandler.setAttribute(newAttributeName, newAttributeValue + ' ' + currentValue); } } } } }
611
977
1,588
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardTargetSelectionTagProcessor.java
AbstractStandardTargetSelectionTagProcessor
validateSelectionValue
class AbstractStandardTargetSelectionTagProcessor extends AbstractAttributeTagProcessor { protected AbstractStandardTargetSelectionTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, true); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) { final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); validateSelectionValue(context, tag, attributeName, attributeValue, expression); final Object newSelectionTarget = expression.execute(context); final Map<String,Object> additionalLocalVariables = computeAdditionalLocalVariables(context, tag, attributeName, attributeValue, expression); if (additionalLocalVariables != null && additionalLocalVariables.size() > 0) { for (final Map.Entry<String,Object> variableEntry : additionalLocalVariables.entrySet()) { structureHandler.setLocalVariable(variableEntry.getKey(), variableEntry.getValue()); } } structureHandler.setSelectionTarget(newSelectionTarget); } protected void validateSelectionValue( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IStandardExpression expression) {<FILL_FUNCTION_BODY>} protected Map<String,Object> computeAdditionalLocalVariables( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IStandardExpression expression) { // This method is meant to be overriden. By default, no local variables // will be set. return null; } }
// Meant for being overridden. Nothing to be done in default implementation.
508
22
530
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/AbstractStandardTextInlineSettingTagProcessor.java
AbstractStandardTextInlineSettingTagProcessor
doProcess
class AbstractStandardTextInlineSettingTagProcessor extends AbstractAttributeTagProcessor { /* * NOTE This class does not extend AbstractStandardExpressionAttributeTagProcessor because expressions are * actually NOT ALLOWED as values of a th:inline attribute, so that parsing-time event preprocessors like * org.thymeleaf.templateparser.text.InlinedOutputExpressionProcessorTextHandler and * org.thymeleaf.templateparser.markup.InlinedOutputExpressionProcessorMarkupHandler can * do their job when the standard dialects are enabled, without the need to execute any expressions (and * therefore without the need to pass a context to the PARSING phase of the execution, which should not * depend on any execution context in order to be perfectly CACHEABLE). */ protected AbstractStandardTextInlineSettingTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String attrName, final int precedence) { super(templateMode, dialectPrefix, null, false, attrName, true, precedence, true); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract IInliner getInliner(final ITemplateContext context, final StandardInlineMode inlineMode); }
// Note we are NOT executing the attributeValue as a Standard Expression: we are expecting a literal (see comment above) final IInliner inliner = getInliner(context, StandardInlineMode.parse(attributeValue)); structureHandler.setInliner(inliner);
361
74
435
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardBlockTagProcessor.java
StandardBlockTagProcessor
doProcess
class StandardBlockTagProcessor extends AbstractElementTagProcessor { public static final int PRECEDENCE = 100000; public static final String ELEMENT_NAME = "block"; public StandardBlockTagProcessor(final TemplateMode templateMode, final String dialectPrefix, final String elementName) { super(templateMode, dialectPrefix, elementName, (dialectPrefix != null), null, false, PRECEDENCE); } @Override protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
// We are just removing the "<th:block>", leaving whichever contents (body) it might have generated. structureHandler.removeTags();
167
41
208
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardCaseTagProcessor.java
StandardCaseTagProcessor
isVisible
class StandardCaseTagProcessor extends AbstractStandardConditionalVisibilityTagProcessor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final int PRECEDENCE = 275; public static final String ATTR_NAME = "case"; public static final String CASE_DEFAULT_ATTRIBUTE_VALUE = "*"; public StandardCaseTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE); } @Override protected boolean isVisible( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>} }
/* * Note the th:case processors must admit the concept of SHORTCUT inside the enclosing th:switch, which means * that once one th:case has evaluated to true, no other th:case should be evaluated at all. It is because * of this that this class should not extend from any other that evaluates the attributeValue before calling * this code. */ final StandardSwitchTagProcessor.SwitchStructure switchStructure = (StandardSwitchTagProcessor.SwitchStructure) context.getVariable(StandardSwitchTagProcessor.SWITCH_VARIABLE_NAME); if (switchStructure == null) { throw new TemplateProcessingException( "Cannot specify a \"" + attributeName + "\" attribute in an environment where no " + "switch operator has been defined before."); } if (switchStructure.isExecuted()) { return false; } if (attributeValue != null && attributeValue.trim().equals(CASE_DEFAULT_ATTRIBUTE_VALUE)) { if (this.logger.isTraceEnabled()) { this.logger.trace("[THYMELEAF][{}][{}] Case expression \"{}\" in attribute \"{}\" has been evaluated as: \"{}\"", new Object[] {TemplateEngine.threadIndex(), LoggingUtils.loggifyTemplateName(context.getTemplateData().getTemplate()), attributeValue, attributeName, attributeValue, Boolean.TRUE}); } switchStructure.setExecuted(true); return true; } final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression caseExpression = expressionParser.parseExpression(context, attributeValue); final EqualsExpression equalsExpression = new EqualsExpression(switchStructure.getExpression(), caseExpression); final Object value = equalsExpression.execute(context); final boolean visible = EvaluationUtils.evaluateAsBoolean(value); if (this.logger.isTraceEnabled()) { this.logger.trace("[THYMELEAF][{}][{}] Case expression \"{}\" in attribute \"{}\" has been evaluated as: \"{}\"", new Object[] {TemplateEngine.threadIndex(), LoggingUtils.loggifyTemplateName(context.getTemplateData().getTemplate()), attributeValue, attributeName, attributeValue, Boolean.valueOf(visible)}); } if (visible) { switchStructure.setExecuted(true); } return visible;
198
617
815
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardClassappendTagProcessor.java
StandardClassappendTagProcessor
doProcess
class StandardClassappendTagProcessor extends AbstractStandardExpressionAttributeTagProcessor implements IAttributeDefinitionsAware { public static final int PRECEDENCE = 1100; public static final String ATTR_NAME = "classappend"; public static final String TARGET_ATTR_NAME = "class"; private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML; private AttributeDefinition targetAttributeDefinition; public StandardClassappendTagProcessor(final String dialectPrefix) { super(TEMPLATE_MODE, dialectPrefix, ATTR_NAME, PRECEDENCE, true, false); } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) { Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinition of the target attribute in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.targetAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TARGET_ATTR_NAME); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), expressionResult == null ? null : expressionResult.toString()); // If we are not adding anything, we'll just leave it untouched if (newAttributeValue != null && newAttributeValue.length() > 0) { final AttributeName targetAttributeName = this.targetAttributeDefinition.getAttributeName(); if (tag.hasAttribute(targetAttributeName)) { final String currentValue = tag.getAttributeValue(targetAttributeName); if (currentValue.length() > 0) { newAttributeValue = currentValue + ' ' + newAttributeValue; } } StandardProcessorUtils.setAttribute(structureHandler, this.targetAttributeDefinition, TARGET_ATTR_NAME, newAttributeValue); }
364
202
566
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardConditionalCommentProcessor.java
StandardConditionalCommentProcessor
doProcess
class StandardConditionalCommentProcessor extends AbstractCommentProcessor { public static final int PRECEDENCE = 1100; public StandardConditionalCommentProcessor() { super(TemplateMode.HTML, PRECEDENCE); } @Override protected void doProcess( final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final StandardConditionalCommentUtils.ConditionalCommentParsingResult parsingResult = StandardConditionalCommentUtils.parseConditionalComment(comment); if (parsingResult == null) { // This is NOT a Conditional Comment. Just return return; } final String commentStr = comment.getComment(); /* * Next, we need to get the content of the Conditional Comment and process it as a piece of markup. In fact, * we must process it as a template itself (a template fragment) so that all thymeleaf attributes and * structures inside this content execute correctly, including references to context variables. */ final TemplateManager templateManager = context.getConfiguration().getTemplateManager(); final String parsableContent = commentStr.substring(parsingResult.getContentOffset(), parsingResult.getContentOffset() + parsingResult.getContentLen()); final TemplateModel templateModel = templateManager.parseString( context.getTemplateData(), parsableContent, comment.getLine(), comment.getCol(), null, // No need to force template mode true); final FastStringWriter writer = new FastStringWriter(200); /* * Rebuild the conditional comment start expression */ writer.write("["); writer.write(commentStr, parsingResult.getStartExpressionOffset(), parsingResult.getStartExpressionLen()); writer.write("]>"); /* * Process the parsable content */ templateManager.process(templateModel, context, writer); /* * Rebuild the conditional comment end expression */ writer.write("<!["); writer.write(commentStr, parsingResult.getEndExpressionOffset(), parsingResult.getEndExpressionLen()); writer.write("]"); /* * Re-set the comment content, once processed */ structureHandler.setContent(writer.toString());
117
482
599
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment, org.thymeleaf.processor.comment.ICommentStructureHandler) <variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardConditionalFixedValueTagProcessor.java
StandardConditionalFixedValueTagProcessor
setAttributeDefinitions
class StandardConditionalFixedValueTagProcessor extends AbstractStandardExpressionAttributeTagProcessor implements IAttributeDefinitionsAware { public static final int PRECEDENCE = 1000; public static final String[] ATTR_NAMES = new String[] { "async", "autofocus", "autoplay", "checked", "controls", "declare", "default", "defer", "disabled", "formnovalidate", "hidden", "ismap", "loop", "multiple", "novalidate", "nowrap", "open", "pubdate", "readonly", "required", "reversed", "selected", "scoped", "seamless" }; private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML; private final String targetAttributeCompleteName; private AttributeDefinition targetAttributeDefinition; public StandardConditionalFixedValueTagProcessor(final String dialectPrefix, final String attrName) { super(TEMPLATE_MODE, dialectPrefix, attrName, PRECEDENCE, true, false); // We are discarding the prefix because that is exactly what we want: th:async -> async this.targetAttributeCompleteName = attrName; } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {<FILL_FUNCTION_BODY>} @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) { if (EvaluationUtils.evaluateAsBoolean(expressionResult)) { StandardProcessorUtils.setAttribute(structureHandler, this.targetAttributeDefinition, this.targetAttributeCompleteName, this.targetAttributeCompleteName); } else { structureHandler.removeAttribute(this.targetAttributeDefinition.getAttributeName()); } } }
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinition of the target attribute in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.targetAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, this.targetAttributeCompleteName);
503
94
597
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardDOMEventAttributeTagProcessor.java
StandardDOMEventAttributeTagProcessor
doProcess
class StandardDOMEventAttributeTagProcessor extends AbstractAttributeTagProcessor implements IAttributeDefinitionsAware { public static final int PRECEDENCE = 1000; // These attributes should be removed even if their value evaluates to null or empty string. // The reason why we don't let all these attributes to be processed by the default processor is that some other attribute // processors executing afterwards (e.g. th:field) might need attribute values already processed by these. public static final String[] ATTR_NAMES = new String[] { "onabort", "onafterprint", "onbeforeprint", "onbeforeunload", "onblur", "oncanplay", "oncanplaythrough", "onchange", "onclick", "oncontextmenu", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformchange", "onforminput", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmessage", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onoffline", "ononline", "onpause", "onplay", "onplaying", "onpopstate", "onprogress", "onratechange", "onreadystatechange", "onredo", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "onundo", "onunload", "onvolumechange", "onwaiting" }; private final String targetAttrCompleteName; private AttributeDefinition targetAttributeDefinition; public StandardDOMEventAttributeTagProcessor(final String dialectPrefix, final String attrName) { super(TemplateMode.HTML, dialectPrefix, null, false, attrName, true, PRECEDENCE, false); Validate.notNull(attrName, "Complete name of target attribute cannot be null"); this.targetAttrCompleteName = attrName; } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) { Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinition of the target attribute in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.targetAttributeDefinition = attributeDefinitions.forName(getTemplateMode(), this.targetAttrCompleteName); } protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) { final Object expressionResult; if (attributeValue != null) { IStandardExpression expression = null; try { expression = EngineEventUtils.computeAttributeExpression(context, tag, attributeName, attributeValue); } catch (final TemplateProcessingException e) { // The attribute value seems not to be a Thymeleaf Standard Expression. This is something that could // be perfectly OK, as these event handler attributes are allowed to contain a fragment of // JavaScript as their value, which will be processed as fragments in JAVASCRIPT template mode. } if (expression != null) { // This expression will be evaluated using restricted mode including the prohibition to evaluate // variable expressions that result in a String or in any objects that could be translated to // untrustable text literals. expressionResult = expression.execute(context, StandardExpressionExecutionContext.RESTRICTED_FORBID_UNSAFE_EXP_RESULTS); } else { // The attribute value is not parseable as a Thymeleaf Standard Expression, so we will process it // as a JavaScript fragment, applying the same logic used in AbstractStandardInliner final IAttribute attribute = tag.getAttribute(attributeName); final TemplateManager templateManager = context.getConfiguration().getTemplateManager(); final TemplateModel templateModel = templateManager.parseString( context.getTemplateData(), attributeValue, attribute.getLine(), attribute.getCol(), TemplateMode.JAVASCRIPT, true); final Writer stringWriter = new FastStringWriter(50); templateManager.process(templateModel, context, stringWriter); expressionResult = stringWriter.toString(); } } else { expressionResult = null; } // If the result of this expression is NO-OP, there is nothing to execute if (expressionResult == NoOpToken.VALUE) { structureHandler.removeAttribute(attributeName); return; } doProcess( context, tag, attributeName, attributeValue, expressionResult, structureHandler); } }
final String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), expressionResult == null ? null : expressionResult.toString()); // These attributes are "removable if empty", so we simply remove the target attribute... if (newAttributeValue == null || newAttributeValue.length() == 0) { // We are removing the equivalent attribute name, without the prefix... structureHandler.removeAttribute(this.targetAttributeDefinition.getAttributeName()); structureHandler.removeAttribute(attributeName); } else { // We are setting the equivalent attribute name, without the prefix... StandardProcessorUtils.replaceAttribute( structureHandler, attributeName, this.targetAttributeDefinition, this.targetAttrCompleteName, (newAttributeValue == null ? "" : newAttributeValue)); }
1,481
195
1,676
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardDefaultAttributesTagProcessor.java
StandardDefaultAttributesTagProcessor
processDefaultAttribute
class StandardDefaultAttributesTagProcessor extends AbstractProcessor implements IElementTagProcessor { // Setting to Integer.MAX_VALUE is alright - we will always be limited by the dialect precedence anyway public static final int PRECEDENCE = Integer.MAX_VALUE; private final String dialectPrefix; private final MatchingAttributeName matchingAttributeName; public StandardDefaultAttributesTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, PRECEDENCE); this.dialectPrefix = dialectPrefix; this.matchingAttributeName = MatchingAttributeName.forAllAttributesWithPrefix(getTemplateMode(), dialectPrefix); } public final MatchingElementName getMatchingElementName() { return null; } public final MatchingAttributeName getMatchingAttributeName() { return this.matchingAttributeName; } // Default implementation - meant to be overridden by subclasses if needed public void process( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) { final TemplateMode templateMode = getTemplateMode(); final IAttribute[] attributes = tag.getAllAttributes(); // Should be no problem in performing modifications during iteration, as the attributeNames list // should not be affected by modifications on the original tag attribute set for (final IAttribute attribute : attributes) { final AttributeName attributeName = attribute.getAttributeDefinition().getAttributeName(); if (attributeName.isPrefixed()) { if (TextUtil.equals(templateMode.isCaseSensitive(), attributeName.getPrefix(), this.dialectPrefix)) { // We will process each 'default' attribute separately processDefaultAttribute(getTemplateMode(), context, tag, attribute, structureHandler); } } } } private static void processDefaultAttribute( final TemplateMode templateMode, final ITemplateContext context, final IProcessableElementTag tag, final IAttribute attribute, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
try { final AttributeName attributeName = attribute.getAttributeDefinition().getAttributeName(); final String attributeValue = EscapedAttributeUtils.unescapeAttribute(context.getTemplateMode(), attribute.getValue()); /* * Compute the new attribute name (i.e. the same, without the prefix) */ final String originalCompleteAttributeName = attribute.getAttributeCompleteName(); final String canonicalAttributeName = attributeName.getAttributeName(); final String newAttributeName; if (TextUtil.endsWith(true, originalCompleteAttributeName, canonicalAttributeName)) { newAttributeName = canonicalAttributeName; // We avoid creating a new String instance } else { newAttributeName = originalCompleteAttributeName.substring(originalCompleteAttributeName.length() - canonicalAttributeName.length()); } /* * Obtain the parser */ final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); /* * Execute the expression, handling nulls in a way consistent with the rest of the Standard Dialect */ final Object expressionResult; if (attributeValue != null) { final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); if (expression != null && expression instanceof FragmentExpression) { // This is merely a FragmentExpression (not complex, not combined with anything), so we can apply a shortcut // so that we don't require a "null" result for this expression if the template does not exist. That will // save a call to resource.exists() which might be costly. final FragmentExpression.ExecutedFragmentExpression executedFragmentExpression = FragmentExpression.createExecutedFragmentExpression(context, (FragmentExpression) expression); expressionResult = FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true); } else { // Default attributes will ALWAYS be executed in RESTRICTED mode, for safety reasons (they might // create attributes involved in code execution) expressionResult = expression.execute(context, StandardExpressionExecutionContext.RESTRICTED); } } else { expressionResult = null; } /* * If the result of this expression is NO-OP, there is nothing to execute */ if (expressionResult == NoOpToken.VALUE) { structureHandler.removeAttribute(attributeName); return; } /* * Compute the new attribute value */ final String newAttributeValue = EscapedAttributeUtils.escapeAttribute(templateMode, expressionResult == null ? null : expressionResult.toString()); /* * Set the new value, removing the attribute completely if the expression evaluated to null */ if (newAttributeValue == null || newAttributeValue.length() == 0) { // We are removing the equivalent attribute name, without the prefix... structureHandler.removeAttribute(newAttributeName); structureHandler.removeAttribute(attributeName); } else { // We are setting the equivalent attribute name, without the prefix... structureHandler.replaceAttribute(attributeName, newAttributeName, (newAttributeValue == null? "" : newAttributeValue)); } } catch (final TemplateProcessingException e) { // This is a nice moment to check whether the execution raised an error and, if so, add location information // Note this is similar to what is done at the superclass AbstractElementTagProcessor, but we can be more // specific because we know exactly what attribute was being executed and caused the error if (!e.hasTemplateName()) { e.setTemplateName(tag.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(attribute.getLine(), attribute.getCol()); } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + StandardDefaultAttributesTagProcessor.class.getName() + "'", tag.getTemplateName(), attribute.getLine(), attribute.getCol(), e); }
532
997
1,529
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardEachTagProcessor.java
StandardEachTagProcessor
doProcess
class StandardEachTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 200; public static final String ATTR_NAME = "each"; public StandardEachTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final Each each = EachUtils.parseEach(context, attributeValue); final IStandardExpression iterVarExpr = each.getIterVar(); final Object iterVarValue = iterVarExpr.execute(context); final IStandardExpression statusVarExpr = each.getStatusVar(); final Object statusVarValue; if (statusVarExpr != null) { statusVarValue = statusVarExpr.execute(context); } else { statusVarValue = null; // Will provoke the default behaviour: iterVarValue + 'Stat' } final IStandardExpression iterableExpr = each.getIterable(); final Object iteratedValue = iterableExpr.execute(context); final String iterVarName = (iterVarValue == null? null : iterVarValue.toString()); if (StringUtils.isEmptyOrWhitespace(iterVarName)) { throw new TemplateProcessingException( "Iteration variable name expression evaluated as null: \"" + iterVarExpr + "\""); } final String statusVarName = (statusVarValue == null? null : statusVarValue.toString()); if (statusVarExpr != null && StringUtils.isEmptyOrWhitespace(statusVarName)) { throw new TemplateProcessingException( "Status variable name expression evaluated as null or empty: \"" + statusVarExpr + "\""); } structureHandler.iterateElement(iterVarName, statusVarName, iteratedValue);
171
352
523
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardFragmentTagProcessor.java
StandardFragmentTagProcessor
doProcess
class StandardFragmentTagProcessor extends AbstractElementTagProcessor { public static final int PRECEDENCE = 1500; public static final String ATTR_NAME = "fragment"; public StandardFragmentTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
// Nothing to do, this processor is just a marker. Simply remove the attribute final AttributeName attributeName = getMatchingAttributeName().getMatchingAttributeName(); structureHandler.removeAttribute(attributeName);
159
55
214
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardIfTagProcessor.java
StandardIfTagProcessor
isVisible
class StandardIfTagProcessor extends AbstractStandardConditionalVisibilityTagProcessor { public static final int PRECEDENCE = 300; public static final String ATTR_NAME = "if"; public StandardIfTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE); } @Override protected boolean isVisible( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>} }
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); final Object value = expression.execute(context); return EvaluationUtils.evaluateAsBoolean(value);
155
78
233
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardIncludeTagProcessor.java
StandardIncludeTagProcessor
doProcess
class StandardIncludeTagProcessor extends AbstractStandardFragmentInsertionTagProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(StandardIncludeTagProcessor.class); public static final int PRECEDENCE = 100; public static final String ATTR_NAME = "include"; public StandardIncludeTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE, false, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
if (LOGGER.isWarnEnabled()) { LOGGER.warn( "[THYMELEAF][{}][{}] Deprecated attribute {} found in template {}, line {}, col {}. " + "Please use {} instead, this deprecated attribute will be removed in future versions of Thymeleaf.", new Object[]{ TemplateEngine.threadIndex(), LoggingUtils.loggifyTemplateName(context.getTemplateData().getTemplate()), attributeName, tag.getTemplateName(), Integer.valueOf(tag.getAttribute(attributeName).getLine()), Integer.valueOf(tag.getAttribute(attributeName).getCol()), AttributeNames.forHTMLName(attributeName.getPrefix(), StandardInsertTagProcessor.ATTR_NAME)}); } super.doProcess(context, tag, attributeName, attributeValue, structureHandler);
200
204
404
<methods><variables>private static final java.lang.String FRAGMENT_ATTR_NAME,private static final org.slf4j.Logger LOGGER,private final non-sealed boolean insertOnlyContents,private final non-sealed boolean replaceHost
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInlineEnablementTemplateBoundariesProcessor.java
StandardInlineEnablementTemplateBoundariesProcessor
doProcessTemplateStart
class StandardInlineEnablementTemplateBoundariesProcessor extends AbstractTemplateBoundariesProcessor { public static final int PRECEDENCE = 10; public StandardInlineEnablementTemplateBoundariesProcessor(final TemplateMode templateMode) { super(templateMode, PRECEDENCE); } @Override public void doProcessTemplateStart( final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} @Override public void doProcessTemplateEnd( final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler) { // Empty - nothing to be done on template end } }
switch (getTemplateMode()) { case HTML: structureHandler.setInliner(new StandardHTMLInliner(context.getConfiguration())); break; case XML: structureHandler.setInliner(new StandardXMLInliner(context.getConfiguration())); break; case TEXT: structureHandler.setInliner(new StandardTextInliner(context.getConfiguration())); break; case JAVASCRIPT: structureHandler.setInliner(new StandardJavaScriptInliner(context.getConfiguration())); break; case CSS: structureHandler.setInliner(new StandardCSSInliner(context.getConfiguration())); break; case RAW: // No inliner for RAW template mode. We could use the Raw, but anyway it would be of no use // because in RAW mode the text processor that looks for the inliner to apply does not exist... structureHandler.setInliner(null); break; default: throw new TemplateProcessingException( "Unrecognized template mode: " + getTemplateMode() + ", cannot initialize inlining!"); }
192
291
483
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public abstract void doProcessTemplateEnd(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ITemplateEnd, org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler) ,public abstract void doProcessTemplateStart(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ITemplateStart, org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler) ,public final void processTemplateEnd(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ITemplateEnd, org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler) ,public final void processTemplateStart(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ITemplateStart, org.thymeleaf.processor.templateboundaries.ITemplateBoundariesStructureHandler) <variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInlineHTMLTagProcessor.java
StandardInlineHTMLTagProcessor
getInliner
class StandardInlineHTMLTagProcessor extends AbstractStandardTextInlineSettingTagProcessor { public static final int PRECEDENCE = 1000; public static final String ATTR_NAME = "inline"; public StandardInlineHTMLTagProcessor(final String dialectPrefix) { super(TemplateMode.HTML, dialectPrefix, ATTR_NAME, PRECEDENCE); } @Override protected IInliner getInliner(final ITemplateContext context, final StandardInlineMode inlineMode) {<FILL_FUNCTION_BODY>} }
switch (inlineMode) { case NONE: return NoOpInliner.INSTANCE; case HTML: return new StandardHTMLInliner(context.getConfiguration()); case TEXT: return new StandardTextInliner(context.getConfiguration()); case JAVASCRIPT: return new StandardJavaScriptInliner(context.getConfiguration()); case CSS: return new StandardCSSInliner(context.getConfiguration()); default: throw new TemplateProcessingException( "Invalid inline mode selected: " + inlineMode + ". Allowed inline modes in template mode " + getTemplateMode() + " are: " + "\"" + StandardInlineMode.HTML + "\", \"" + StandardInlineMode.TEXT + "\", " + "\"" + StandardInlineMode.JAVASCRIPT + "\", \"" + StandardInlineMode.CSS + "\" and " + "\"" + StandardInlineMode.NONE + "\""); }
146
247
393
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInlineTextualTagProcessor.java
StandardInlineTextualTagProcessor
getInliner
class StandardInlineTextualTagProcessor extends AbstractStandardTextInlineSettingTagProcessor { public static final int PRECEDENCE = 1000; public static final String ATTR_NAME = "inline"; public StandardInlineTextualTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE); Validate.isTrue(templateMode.isText(), "Template mode must be a textual one"); } @Override protected IInliner getInliner(final ITemplateContext context, final StandardInlineMode inlineMode) {<FILL_FUNCTION_BODY>} }
final TemplateMode templateMode = getTemplateMode(); switch (inlineMode) { case NONE: return NoOpInliner.INSTANCE; case TEXT: if (templateMode == TemplateMode.TEXT) { return new StandardTextInliner(context.getConfiguration()); } break; // will output exception case JAVASCRIPT: if (templateMode == TemplateMode.JAVASCRIPT) { return new StandardJavaScriptInliner(context.getConfiguration()); } break; // will output exception case CSS: if (templateMode == TemplateMode.CSS) { return new StandardCSSInliner(context.getConfiguration()); } break; // will output exception } throw new TemplateProcessingException( "Invalid inline mode selected: " + inlineMode + ". Allowed inline modes in template mode " + getTemplateMode() + " are: \"" + getTemplateMode() + "\" and " + "\"" + StandardInlineMode.NONE + "\"");
176
263
439
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInlineXMLTagProcessor.java
StandardInlineXMLTagProcessor
getInliner
class StandardInlineXMLTagProcessor extends AbstractStandardTextInlineSettingTagProcessor { public static final int PRECEDENCE = 1000; public static final String ATTR_NAME = "inline"; public StandardInlineXMLTagProcessor(final String dialectPrefix) { super(TemplateMode.XML, dialectPrefix, ATTR_NAME, PRECEDENCE); } @Override protected IInliner getInliner(final ITemplateContext context, final StandardInlineMode inlineMode) {<FILL_FUNCTION_BODY>} }
switch (inlineMode) { case NONE: return NoOpInliner.INSTANCE; case XML: return new StandardXMLInliner(context.getConfiguration()); case TEXT: return new StandardTextInliner(context.getConfiguration()); default: throw new TemplateProcessingException( "Invalid inline mode selected: " + inlineMode + ". Allowed inline modes in template mode " + getTemplateMode() + " are: " + "\"" + StandardInlineMode.XML + "\", \"" + StandardInlineMode.TEXT + "\", " + "\"" + StandardInlineMode.NONE + "\""); }
148
167
315
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInliningCDATASectionProcessor.java
StandardInliningCDATASectionProcessor
doProcess
class StandardInliningCDATASectionProcessor extends AbstractCDATASectionProcessor { public static final int PRECEDENCE = 1000; public StandardInliningCDATASectionProcessor(final TemplateMode templateMode) { super(templateMode, PRECEDENCE); } @Override protected void doProcess( final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IInliner inliner = context.getInliner(); if (inliner == null || inliner == NoOpInliner.INSTANCE) { return; } final CharSequence inlined = inliner.inline(context, cdataSection); if (inlined != null && inlined != cdataSection) { structureHandler.setContent(inlined); }
135
110
245
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.ICDATASection, org.thymeleaf.processor.cdatasection.ICDATASectionStructureHandler) <variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInliningCommentProcessor.java
StandardInliningCommentProcessor
doProcess
class StandardInliningCommentProcessor extends AbstractCommentProcessor { public static final int PRECEDENCE = 1000; public StandardInliningCommentProcessor(final TemplateMode templateMode) { super(templateMode, PRECEDENCE); } @Override protected void doProcess( final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IInliner inliner = context.getInliner(); if (inliner == null || inliner == NoOpInliner.INSTANCE) { return; } final CharSequence inlined = inliner.inline(context, comment); if (inlined != null && inlined != comment) { structureHandler.setContent(inlined); }
118
106
224
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IComment, org.thymeleaf.processor.comment.ICommentStructureHandler) <variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardInliningTextProcessor.java
StandardInliningTextProcessor
doProcess
class StandardInliningTextProcessor extends AbstractTextProcessor { public static final int PRECEDENCE = 1000; public StandardInliningTextProcessor(final TemplateMode templateMode) { super(templateMode, PRECEDENCE); } @Override protected void doProcess( final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
if (EngineEventUtils.isWhitespace(text)) { // Fail fast - a whitespace text is never inlineable. And templates tend to have a lot of white space blocks // NOTE we are not using isInlineable() here because before doing so the template mode would have to be // checked (so that th:inline works alright). But white spaces are a safe bet. return; } final IInliner inliner = context.getInliner(); if (inliner == null || inliner == NoOpInliner.INSTANCE) { return; } final CharSequence inlined = inliner.inline(context, text); if (inlined != null && inlined != text) { structureHandler.setText(inlined); }
118
203
321
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IText, org.thymeleaf.processor.text.ITextStructureHandler) <variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardRefAttributeTagProcessor.java
StandardRefAttributeTagProcessor
doProcess
class StandardRefAttributeTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 10000; public static final String ATTR_NAME = "ref"; public StandardRefAttributeTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
// This processor is a no-op. It can simply be used for referencing specific elements in markup, but // produces no results (other than being removed from markup once executed).
177
48
225
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardRemoveTagProcessor.java
StandardRemoveTagProcessor
doProcess
class StandardRemoveTagProcessor extends AbstractStandardExpressionAttributeTagProcessor { public static final int PRECEDENCE = 1600; public static final String ATTR_NAME = "remove"; public static final String VALUE_ALL = "all"; public static final String VALUE_ALL_BUT_FIRST = "all-but-first"; public static final String VALUE_TAG = "tag"; public static final String VALUE_TAGS = "tags"; // 'tags' is also allowed underneath because that's what it does: remove both open and close tags. public static final String VALUE_BODY = "body"; public static final String VALUE_NONE = "none"; public StandardRemoveTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE, true, false); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
if (expressionResult != null) { final String resultStr = expressionResult.toString(); if (VALUE_ALL.equalsIgnoreCase(resultStr)) { structureHandler.removeElement(); } else if (VALUE_TAG.equalsIgnoreCase(resultStr) || VALUE_TAGS.equalsIgnoreCase(resultStr)) { structureHandler.removeTags(); } else if (VALUE_ALL_BUT_FIRST.equalsIgnoreCase(resultStr)) { structureHandler.removeAllButFirstChild(); } else if (VALUE_BODY.equalsIgnoreCase(resultStr)) { structureHandler.removeBody(); } else if (!VALUE_NONE.equalsIgnoreCase(resultStr)) { throw new TemplateProcessingException( "Invalid value specified for \"" + attributeName + "\": only 'all', 'tag', 'body', 'none' " + "and 'all-but-first' are allowed, but \"" + attributeValue + "\" was specified."); } }
300
249
549
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardStyleappendTagProcessor.java
StandardStyleappendTagProcessor
doProcess
class StandardStyleappendTagProcessor extends AbstractStandardExpressionAttributeTagProcessor implements IAttributeDefinitionsAware { public static final int PRECEDENCE = 1100; public static final String ATTR_NAME = "styleappend"; public static final String TARGET_ATTR_NAME = "style"; private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML; private AttributeDefinition targetAttributeDefinition; public StandardStyleappendTagProcessor(final String dialectPrefix) { super(TemplateMode.HTML, dialectPrefix, ATTR_NAME, PRECEDENCE, true, false); } public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) { Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null"); // We precompute the AttributeDefinition of the target attribute in order to being able to use much // faster methods for setting/replacing attributes on the ElementAttributes implementation this.targetAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TARGET_ATTR_NAME); } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
String newAttributeValue = EscapedAttributeUtils.escapeAttribute(getTemplateMode(), expressionResult == null ? null : expressionResult.toString()); // If we are not adding anything, we'll just leave it untouched if (newAttributeValue != null && newAttributeValue.length() > 0) { final AttributeName targetAttributeName = this.targetAttributeDefinition.getAttributeName(); if (tag.hasAttribute(targetAttributeName)) { final String currentValue = tag.getAttributeValue(targetAttributeName); if (currentValue.length() > 0) { newAttributeValue = currentValue + ' ' + newAttributeValue; } } StandardProcessorUtils.setAttribute(structureHandler, this.targetAttributeDefinition, TARGET_ATTR_NAME, newAttributeValue); }
363
202
565
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardSwitchTagProcessor.java
StandardSwitchTagProcessor
doProcess
class StandardSwitchTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 250; public static final String ATTR_NAME = "switch"; public static final String SWITCH_VARIABLE_NAME = "%%SWITCH_EXPR%%"; public StandardSwitchTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} public static final class SwitchStructure { private final IStandardExpression expression; private boolean executed; public SwitchStructure(final IStandardExpression expression) { super(); this.expression = expression; this.executed = false; } public IStandardExpression getExpression() { return this.expression; } public boolean isExecuted() { return this.executed; } public void setExecuted(final boolean executed) { this.executed = executed; } } }
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression switchExpression = expressionParser.parseExpression(context, attributeValue); structureHandler.setLocalVariable(SWITCH_VARIABLE_NAME, new SwitchStructure(switchExpression));
337
80
417
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardTextTagProcessor.java
StandardTextTagProcessor
doProcess
class StandardTextTagProcessor extends AbstractStandardExpressionAttributeTagProcessor { public static final int PRECEDENCE = 1300; public static final String ATTR_NAME = "text"; public StandardTextTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { // We will only use RESTRICTED expression execution mode for TEXT template mode, as it could be used for // writing inside code-oriented HTML attributes and other similar scenarios. super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE, true, (templateMode == TemplateMode.TEXT)); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final Object expressionResult, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} private static String produceEscapedOutput(final TemplateMode templateMode, final String input) { switch (templateMode) { case TEXT: // fall-through case HTML: return HtmlEscape.escapeHtml4Xml(input); case XML: // Note we are outputting a body content here, so it is important that we use the version // of XML escaping meant for content, not attributes (slight differences) return XmlEscape.escapeXml10(input); default: throw new TemplateProcessingException( "Unrecognized template mode " + templateMode + ". Cannot produce escaped output for " + "this template mode."); } } }
final TemplateMode templateMode = getTemplateMode(); /* * Depending on the template mode and the length of the text to be output escaped, we will try to opt for * the most resource-efficient alternative. * * * If we are outputting RAW, there is no escape to do, just pass through. * * If we are outputting HTML, XML or TEXT we know output will be textual (result of calling .toString() on * the expression result), and therefore we can decide between an immediate vs lazy escaping alternative * depending on size. We will perform lazy escaping, writing directly to output Writer, if length > 100. * * If we are outputting JAVASCRIPT or CSS, we will always pass the expression result unchanged to a lazy * escape processor, so that whatever the JS/CSS serializer wants to do, it does it directly on the * output Writer and the entire results are never really needed in memory. */ final CharSequence text; if (templateMode != TemplateMode.JAVASCRIPT && templateMode != TemplateMode.CSS) { final String input = (expressionResult == null? "" : expressionResult.toString()); if (templateMode == TemplateMode.RAW) { // RAW -> just output text = input; } else { if (input.length() > 100) { // Might be a large text -> Lazy escaping on the output Writer text = new LazyEscapingCharSequence(context.getConfiguration(), templateMode, input); } else { // Not large -> better use a bit more of memory, but be faster text = produceEscapedOutput(templateMode, input); } } } else { // JavaScript and CSS serializers always work directly on the output Writer, no need to store the entire // serialized contents in memory (unless the Writer itself wants to do so). text = new LazyEscapingCharSequence(context.getConfiguration(), templateMode, expressionResult); } // Report the result to the engine, whichever the type of process we have applied structureHandler.setBody(text, false);
400
545
945
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardUnlessTagProcessor.java
StandardUnlessTagProcessor
isVisible
class StandardUnlessTagProcessor extends AbstractStandardConditionalVisibilityTagProcessor { public static final int PRECEDENCE = 400; public static final String ATTR_NAME = "unless"; public StandardUnlessTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, ATTR_NAME, PRECEDENCE); } @Override protected boolean isVisible( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>} }
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); final Object value = expression.execute(context); return !EvaluationUtils.evaluateAsBoolean(value);
157
77
234
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardUtextTagProcessor.java
StandardUtextTagProcessor
doProcess
class StandardUtextTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 1400; public static final String ATTR_NAME = "utext"; public StandardUtextTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} /* * This method will be used for determining if we actually need to apply a parser to the unescaped text that we * are going to use a a result of this th:utext execution. If there is no '>' character in it, then it is * nothing but a piece of text, and applying the parser would be overkill */ private static boolean mightContainStructures(final CharSequence unescapedText) { int n = unescapedText.length(); char c; while (n-- != 0) { c = unescapedText.charAt(n); if (c == '>' || c == ']') { // Might be the end of a structure! return true; } } return false; } }
final IEngineConfiguration configuration = context.getConfiguration(); final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration); final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); final Object expressionResult; if (expression != null && expression instanceof FragmentExpression) { // This is merely a FragmentExpression (not complex, not combined with anything), so we can apply a shortcut // so that we don't require a "null" result for this expression if the template does not exist. That will // save a call to resource.exists() which might be costly. final FragmentExpression.ExecutedFragmentExpression executedFragmentExpression = FragmentExpression.createExecutedFragmentExpression(context, (FragmentExpression) expression); expressionResult = FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true); } else { expressionResult = expression.execute(context, StandardExpressionExecutionContext.RESTRICTED); } // If result is no-op, there's nothing to execute if (expressionResult == NoOpToken.VALUE) { return; } /* * First of all we should check whether the expression result is a Fragment so that, in such case, we can * avoid creating a String in memory for it and just append its model. */ if (expressionResult != null && expressionResult instanceof Fragment) { if (expressionResult == Fragment.EMPTY_FRAGMENT) { structureHandler.removeBody(); return; } structureHandler.setBody(((Fragment)expressionResult).getTemplateModel(), false); return; } final String unescapedTextStr = (expressionResult == null ? "" : expressionResult.toString()); /* * We will check if there are configured post processors or not. The reason we do this is because output * inserted as a result of a th:utext attribute, even if it might be markup, will never be considered as * 'processable', i.e. no other processors/inliner will ever be able to act on it. The main reason for this * is to protect against code injection. * * So the only other agents that would be able to modify these th:utext results are POST-PROCESSORS. And * they will indeed need markup to have been parsed in order to separate text from structures, so that's why * we check if there actually are any post-processors and, if not (most common case), simply output the * expression result as if it were a mere (unescaped) text node. */ final Set<IPostProcessor> postProcessors = configuration.getPostProcessors(getTemplateMode()); if (postProcessors.isEmpty()) { structureHandler.setBody(unescapedTextStr, false); return; } /* * We have post-processors, so from here one we will have to decide whether we need to parse the unescaped * text or not... */ if (!mightContainStructures(unescapedTextStr)) { // If this text contains no markup structures, there would be no need to parse it or treat it as markup! structureHandler.setBody(unescapedTextStr, false); return; } /* * We have post-processors AND this text might contain structures, so there is no alternative but parsing */ final TemplateModel parsedFragment = configuration.getTemplateManager().parseString( context.getTemplateData(), unescapedTextStr, 0, 0, // we won't apply offset here because the inserted text does not really come from the template itself null, // No template mode forcing required false); // useCache == false because we could potentially pollute the cache with too many entries (th:utext is too variable!) // Setting 'processable' to false avoiding text inliners processing already generated text, // which in turn avoids code injection. structureHandler.setBody(parsedFragment, false);
370
993
1,363
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardWithTagProcessor.java
StandardWithTagProcessor
doProcess
class StandardWithTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 600; public static final String ATTR_NAME = "with"; public StandardWithTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final AssignationSequence assignations = AssignationUtils.parseAssignationSequence( context, attributeValue, false /* no parameters without value */); if (assignations == null) { throw new TemplateProcessingException( "Could not parse value as attribute assignations: \"" + attributeValue + "\""); } // Normally we would just allow the structure handler to be in charge of declaring the local variables // by using structureHandler.setLocalVariable(...) but in this case we want each variable defined at an // expression to be available for the next expressions, and that forces us to cast our ITemplateContext into // a more specific interface --which shouldn't be used directly except in this specific, special case-- and // put the local variables directly into it. IEngineContext engineContext = null; if (context instanceof IEngineContext) { // NOTE this interface is internal and should not be used in users' code engineContext = (IEngineContext) context; } final List<Assignation> assignationValues = assignations.getAssignations(); final int assignationValuesLen = assignationValues.size(); for (int i = 0; i < assignationValuesLen; i++) { final Assignation assignation = assignationValues.get(i); final IStandardExpression leftExpr = assignation.getLeft(); final Object leftValue = leftExpr.execute(context); final IStandardExpression rightExpr = assignation.getRight(); final Object rightValue = rightExpr.execute(context); final String newVariableName = (leftValue == null? null : leftValue.toString()); if (StringUtils.isEmptyOrWhitespace(newVariableName)) { throw new TemplateProcessingException( "Variable name expression evaluated as null or empty: \"" + leftExpr + "\""); } if (engineContext != null) { // The advantage of this vs. using the structure handler is that we will be able to // use this newly created value in other expressions in the same 'th:with' engineContext.setVariable(newVariableName, rightValue); } else { // The problem is, these won't be available until we execute the next processor structureHandler.setLocalVariable(newVariableName, rightValue); } }
171
562
733
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/processor/StandardXmlNsTagProcessor.java
StandardXmlNsTagProcessor
doProcess
class StandardXmlNsTagProcessor extends AbstractAttributeTagProcessor { public static final int PRECEDENCE = 1000; public static final String ATTR_NAME_PREFIX = "xmlns:"; public StandardXmlNsTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, null, null, false, ATTR_NAME_PREFIX + dialectPrefix, false, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
// Nothing to do really, we are just removing the "xmlns:th" (or equivalent) attribute
187
29
216
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/serializer/StandardCSSSerializer.java
StandardCSSSerializer
serializeValue
class StandardCSSSerializer implements IStandardCSSSerializer { public StandardCSSSerializer() { super(); } public void serializeValue(final Object object, final Writer writer) {<FILL_FUNCTION_BODY>} private static void writeValue(final Writer writer, final Object object) throws IOException { if (object == null) { writeNull(writer); return; } if (object instanceof CharSequence) { writeString(writer, object.toString()); return; } if (object instanceof Character) { writeString(writer, object.toString()); return; } if (object instanceof Number) { writeNumber(writer, (Number) object); return; } if (object instanceof Boolean) { writeBoolean(writer, (Boolean) object); return; } writeString(writer, object.toString()); } private static void writeNull(final Writer writer) throws IOException { writer.write(""); // There isn't really a 'null' token in CSS } private static void writeString(final Writer writer, final String str) throws IOException { writer.write(CssEscape.escapeCssIdentifier(str)); } private static void writeNumber(final Writer writer, final Number number) throws IOException { writer.write(number.toString()); } private static void writeBoolean(final Writer writer, final Boolean bool) throws IOException { writer.write(bool.toString()); } }
try { writeValue(writer, object); } catch (final IOException e) { throw new TemplateProcessingException( "An exception was raised while trying to serialize object to CSS", e); }
400
56
456
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/serializer/StandardSerializers.java
StandardSerializers
getCSSSerializer
class StandardSerializers { /** * Name used for registering the <i>Standard JavaScript Serializer</i> object as an * <i>execution attribute</i> at the Standard Dialects. */ public static final String STANDARD_JAVASCRIPT_SERIALIZER_ATTRIBUTE_NAME = "StandardJavaScriptSerializer"; /** * Name used for registering the <i>Standard CSS Serializer</i> object as an * <i>execution attribute</i> at the Standard Dialects. */ public static final String STANDARD_CSS_SERIALIZER_ATTRIBUTE_NAME = "StandardCSSSerializer"; private StandardSerializers() { super(); } /** * <p> * Obtain the JavaScript serializer (implementation of {@link IStandardJavaScriptSerializer}) registered by * the Standard Dialect that is being currently used. * </p> * * @param configuration the configuration object for the current template execution environment. * @return the parser object. */ public static IStandardJavaScriptSerializer getJavaScriptSerializer(final IEngineConfiguration configuration) { final Object serializer = configuration.getExecutionAttributes().get(STANDARD_JAVASCRIPT_SERIALIZER_ATTRIBUTE_NAME); if (serializer == null || (!(serializer instanceof IStandardJavaScriptSerializer))) { throw new TemplateProcessingException( "No JavaScript Serializer has been registered as an execution argument. " + "This is a requirement for using Standard serialization, and might happen " + "if neither the Standard or the SpringStandard dialects have " + "been added to the Template Engine and none of the specified dialects registers an " + "attribute of type " + IStandardJavaScriptSerializer.class.getName() + " with name " + "\"" + STANDARD_JAVASCRIPT_SERIALIZER_ATTRIBUTE_NAME + "\""); } return (IStandardJavaScriptSerializer) serializer; } /** * <p> * Obtain the CSS serializer (implementation of {@link IStandardCSSSerializer}) registered by * the Standard Dialect that is being currently used. * </p> * * @param configuration the configuration object for the current template execution environment. * @return the variable expression evaluator object. */ public static IStandardCSSSerializer getCSSSerializer(final IEngineConfiguration configuration) {<FILL_FUNCTION_BODY>} }
final Object serializer = configuration.getExecutionAttributes().get(STANDARD_CSS_SERIALIZER_ATTRIBUTE_NAME); if (serializer == null || (!(serializer instanceof IStandardCSSSerializer))) { throw new TemplateProcessingException( "No CSS Serializer has been registered as an execution argument. " + "This is a requirement for using Standard serialization, and might happen " + "if neither the Standard or the SpringStandard dialects have " + "been added to the Template Engine and none of the specified dialects registers an " + "attribute of type " + IStandardCSSSerializer.class.getName() + " with name " + "\"" + STANDARD_CSS_SERIALIZER_ATTRIBUTE_NAME + "\""); } return (IStandardCSSSerializer) serializer;
638
205
843
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/util/StandardConditionalCommentUtils.java
StandardConditionalCommentUtils
parseConditionalComment
class StandardConditionalCommentUtils { /** * <p> * Tries to parse the text passed as argument as a conditional comment. * </p> * <p> * Result is an object of class {@link ConditionalCommentParsingResult}, or * {@code null} if text does not have the expected format for a conditional comment. * </p> * * @param text the text to be parsed * @return a {@link ConditionalCommentParsingResult} object if text could be parsed, * null if format is invalid. */ public static ConditionalCommentParsingResult parseConditionalComment(final CharSequence text) {<FILL_FUNCTION_BODY>} private StandardConditionalCommentUtils() { super(); } public static final class ConditionalCommentParsingResult { private final int startExpressionOffset; private final int startExpressionLen; private final int contentOffset; private final int contentLen; private final int endExpressionOffset; private final int endExpressionLen; public ConditionalCommentParsingResult(final int startExpressionOffset, final int startExpressionLen, final int contentOffset, final int contentLen, final int endExpressionOffset, final int endExpressionLen) { super(); this.startExpressionOffset = startExpressionOffset; this.startExpressionLen = startExpressionLen; this.contentOffset = contentOffset; this.contentLen = contentLen; this.endExpressionOffset = endExpressionOffset; this.endExpressionLen = endExpressionLen; } public int getStartExpressionOffset() { return this.startExpressionOffset; } public int getStartExpressionLen() { return this.startExpressionLen; } public int getContentOffset() { return this.contentOffset; } public int getContentLen() { return this.contentLen; } public int getEndExpressionOffset() { return this.endExpressionOffset; } public int getEndExpressionLen() { return this.endExpressionLen; } } }
final int len = text.length(); int i = 4; // We start right after the "<!--" // discard all initial whitespace while (i < len && Character.isWhitespace(text.charAt(i))) { i++; } // check the first char after whitespace is '[' if (i >= len || text.charAt(i++) != '[') { return null; } final int startExpressionOffset = i; // look for last position of start expression while (i < len && text.charAt(i) != ']') { i++; } if (i >= len) { return null; } final int startExpressionLen = (i - startExpressionOffset); // discard the ']' position i++; // discard all following whitespace while (i < len && Character.isWhitespace(text.charAt(i))) { i++; } // check the first non-whitespace char after ']' is '>' if (i >= len || text.charAt(i++) != '>') { return null; } final int contentOffset = i; // Once we've obtained all we needed from the start of the comment, switch place // and start looking for structures from the end. i = (len - 3) - 1; // we use that '-3' in order to compensate for the ending "-->" // discard all final whitespace while (i > contentOffset && Character.isWhitespace(text.charAt(i))) { i--; } // check the first char after whitespace is ']' if (i <= contentOffset || text.charAt(i--) != ']') { return null; } final int endExpressionLastPos = i + 1; // look for first char of end expression while (i > contentOffset && text.charAt(i) != '[') { i--; } if (i <= contentOffset) { return null; } final int endExpressionOffset = i + 1; final int endExpressionLen = endExpressionLastPos - endExpressionOffset; // discard the '[' sign we have just processed i--; // discard all following whitespace while (i >= contentOffset && Character.isWhitespace(text.charAt(i))) { i--; } // check the first non-whitespace char before '[' is '!' if (i <= contentOffset || text.charAt(i--) != '!') { return null; } // check the first char before '!' is '<' if (i <= contentOffset || text.charAt(i--) != '<') { return null; } final int contentLen = (i + 1) - contentOffset; if (contentLen <= 0 || startExpressionLen <= 0 || endExpressionLen <= 0) { return null; } return new ConditionalCommentParsingResult( startExpressionOffset, startExpressionLen, contentOffset, contentLen, endExpressionOffset, endExpressionLen);
553
801
1,354
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/util/StandardExpressionUtils.java
StandardExpressionUtils
containsOGNLInstantiationOrStaticOrParam
class StandardExpressionUtils { private static final char[] NEW_ARRAY = "wen".toCharArray(); // Inverted "new" private static final int NEW_LEN = NEW_ARRAY.length; private static final char[] PARAM_ARRAY = "marap".toCharArray(); // Inverted "param" private static final int PARAM_LEN = PARAM_ARRAY.length; public static boolean mightNeedExpressionObjects(final String expression) { return expression.indexOf('#') >= 0; } /* * @since 3.0.12 */ public static boolean containsOGNLInstantiationOrStaticOrParam(final String expression) {<FILL_FUNCTION_BODY>} private static boolean isSafeIdentifierChar(final char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; } private StandardExpressionUtils() { super(); } }
/* * Checks whether the expression contains instantiation of objects ("new SomeClass") or makes use of * static methods ("@SomeClass@") as both are forbidden in certain contexts in restricted mode. */ final String exp = ExpressionUtils.normalize(expression); final int explen = exp.length(); int n = explen; int ni = 0; // index for computing position in the NEW_ARRAY int pi = 0; // index for computing position in the PARAM_ARRAY int si = -1; char c; while (n-- != 0) { c = exp.charAt(n); // When checking for the "new" keyword, we need to identify that it is not a part of a larger // identifier, i.e. there is whitespace after it and no character that might be a part of an // identifier before it. if (ni < NEW_LEN && c == NEW_ARRAY[ni] && (ni > 0 || ((n + 1 < explen) && Character.isWhitespace(exp.charAt(n + 1))))) { ni++; if (ni == NEW_LEN && (n == 0 || !isSafeIdentifierChar(exp.charAt(n - 1)))) { return true; // we found an object instantiation } continue; } if (ni > 0) { // We 'restart' the matching counter just in case we had a partial match n += ni; ni = 0; if (si < n) { // This has to be restarted too si = -1; } continue; } ni = 0; // When checking for the "param" keyword, we need to identify that it is not a part of a larger // identifier. if (pi < PARAM_LEN && c == PARAM_ARRAY[pi] && (pi > 0 || ((n + 1 < explen) && !isSafeIdentifierChar(exp.charAt(n + 1))))) { pi++; if (pi == PARAM_LEN && (n == 0 || !isSafeIdentifierChar(exp.charAt(n - 1)))) { return true; // we found a param access } continue; } if (pi > 0) { // We 'restart' the matching counter just in case we had a partial match n += pi; pi = 0; continue; } pi = 0; if (c == '@') { if (si > n) { return true; } si = n; } else if (si > n && !(Character.isJavaIdentifierPart(c) || Character.isWhitespace(c) || c == '.')) { si = -1; } } return false;
274
722
996
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/util/StandardProcessorUtils.java
StandardProcessorUtils
replaceAttribute
class StandardProcessorUtils { public static void replaceAttribute( final IElementTagStructureHandler structureHandler, final AttributeName oldAttributeName, final AttributeDefinition attributeDefinition, final String attributeName, final String attributeValue) {<FILL_FUNCTION_BODY>} public static void setAttribute( final IElementTagStructureHandler structureHandler, final AttributeDefinition attributeDefinition, final String attributeName, final String attributeValue) { if (structureHandler instanceof ElementTagStructureHandler) { ((ElementTagStructureHandler) structureHandler).setAttribute(attributeDefinition, attributeName, attributeValue, null); } else { structureHandler.setAttribute(attributeName, attributeValue); } } private StandardProcessorUtils() { super(); } }
if (structureHandler instanceof ElementTagStructureHandler) { ((ElementTagStructureHandler) structureHandler).replaceAttribute(oldAttributeName, attributeDefinition, attributeName, attributeValue, null); } else { structureHandler.replaceAttribute(oldAttributeName, attributeName, attributeValue); }
204
75
279
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/InlinedOutputExpressionMarkupHandler.java
InlineMarkupAdapterPreProcessorHandler
handleStandaloneElementStart
class InlineMarkupAdapterPreProcessorHandler implements IInlinePreProcessorHandler { private IMarkupHandler handler; InlineMarkupAdapterPreProcessorHandler(final IMarkupHandler handler) { super(); this.handler = handler; } public void handleText( final char[] buffer, final int offset, final int len, final int line, final int col) { try { this.handler.handleText(buffer, offset, len, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleStandaloneElementStart( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) {<FILL_FUNCTION_BODY>} public void handleStandaloneElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) { try { this.handler.handleStandaloneElementEnd(buffer, nameOffset, nameLen, minimized, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleOpenElementStart(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleOpenElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleAutoOpenElementStart(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleAutoOpenElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleCloseElementStart(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleCloseElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleAutoCloseElementStart(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleAutoCloseElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) { try { this.handler.handleAttribute( buffer, nameOffset, nameLen, nameLine, nameCol, operatorOffset, operatorLen, operatorLine, operatorCol, valueContentOffset, valueContentLen, valueOuterOffset, valueOuterLen, valueLine, valueCol); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } }
try { this.handler.handleStandaloneElementStart(buffer, nameOffset, nameLen, minimized, line, col); } catch (final ParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); }
1,405
69
1,474
<methods>public void handleAttribute(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleAutoCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoOpenElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoOpenElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleCDATASection(char[], int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleComment(char[], int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleDocType(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleDocumentEnd(long, long, int, int) throws org.attoparser.ParseException,public void handleDocumentStart(long, int, int) throws org.attoparser.ParseException,public void handleInnerWhiteSpace(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleOpenElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleOpenElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleProcessingInstruction(char[], int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleStandaloneElementEnd(char[], int, int, boolean, int, int) throws org.attoparser.ParseException,public void handleStandaloneElementStart(char[], int, int, boolean, int, int) throws org.attoparser.ParseException,public void handleText(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleUnmatchedCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleUnmatchedCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleXmlDeclaration(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void setParseConfiguration(org.attoparser.config.ParseConfiguration) ,public void setParseSelection(org.attoparser.select.ParseSelection) ,public void setParseStatus(org.attoparser.ParseStatus) <variables>private final org.attoparser.IMarkupHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/TemplateFragmentMarkupReferenceResolver.java
TemplateFragmentMarkupReferenceResolver
forHTMLPrefix
class TemplateFragmentMarkupReferenceResolver implements IMarkupSelectorReferenceResolver { private static final TemplateFragmentMarkupReferenceResolver HTML_INSTANCE_NO_PREFIX; private static final ConcurrentHashMap<String,TemplateFragmentMarkupReferenceResolver> HTML_INSTANCES_BY_PREFIX; private static final TemplateFragmentMarkupReferenceResolver XML_INSTANCE_NO_PREFIX; private static final ConcurrentHashMap<String,TemplateFragmentMarkupReferenceResolver> XML_INSTANCES_BY_PREFIX; private static final String HTML_FORMAT_WITHOUT_PREFIX = "/[ref='%1$s' or data-ref='%1$s' or fragment='%1$s' or data-fragment='%1$s' or fragment^='%1$s(' or data-fragment^='%1$s(' or fragment^='%1$s (' or data-fragment^='%1$s (']"; private static final String HTML_FORMAT_WITH_PREFIX = "/[%1$s:ref='%%1$s' or data-%1$s-ref='%%1$s' or %1$s:fragment='%%1$s' or data-%1$s-fragment='%%1$s' or %1$s:fragment^='%%1$s(' or data-%1$s-fragment^='%%1$s(' or %1$s:fragment^='%%1$s (' or data-%1$s-fragment^='%%1$s (']"; private static final String XML_FORMAT_WITHOUT_PREFIX = "/[ref='%1$s' or fragment='%1$s' or fragment^='%1$s(' or fragment^='%1$s (']"; private static final String XML_FORMAT_WITH_PREFIX = "/[%1$s:ref='%%1$s' or %1$s:fragment='%%1$s' or %1$s:fragment^='%%1$s(' or %1$s:fragment^='%%1$s (']"; private final ConcurrentHashMap<String,String> selectorsByReference = new ConcurrentHashMap<String, String>(20); private final String resolverFormat; static{ HTML_INSTANCE_NO_PREFIX = new TemplateFragmentMarkupReferenceResolver(true, null); XML_INSTANCE_NO_PREFIX = new TemplateFragmentMarkupReferenceResolver(false, null); HTML_INSTANCES_BY_PREFIX = new ConcurrentHashMap<String, TemplateFragmentMarkupReferenceResolver>(3, 0.9f, 2); XML_INSTANCES_BY_PREFIX = new ConcurrentHashMap<String, TemplateFragmentMarkupReferenceResolver>(3, 0.9f, 2); } static TemplateFragmentMarkupReferenceResolver forPrefix(final boolean html, final String standardDialectPrefix) { return html? forHTMLPrefix(standardDialectPrefix) : forXMLPrefix(standardDialectPrefix); } private static TemplateFragmentMarkupReferenceResolver forHTMLPrefix(final String standardDialectPrefix) {<FILL_FUNCTION_BODY>} private static TemplateFragmentMarkupReferenceResolver forXMLPrefix(final String standardDialectPrefix) { if (standardDialectPrefix == null || standardDialectPrefix.length() == 0) { return XML_INSTANCE_NO_PREFIX; } final TemplateFragmentMarkupReferenceResolver resolver = XML_INSTANCES_BY_PREFIX.get(standardDialectPrefix); if (resolver != null) { return resolver; } final TemplateFragmentMarkupReferenceResolver newResolver = new TemplateFragmentMarkupReferenceResolver(false, standardDialectPrefix); XML_INSTANCES_BY_PREFIX.putIfAbsent(standardDialectPrefix, newResolver); return XML_INSTANCES_BY_PREFIX.get(standardDialectPrefix); } private TemplateFragmentMarkupReferenceResolver(final boolean html, final String standardDialectPrefix) { super(); if (standardDialectPrefix == null) { this.resolverFormat = (html? HTML_FORMAT_WITHOUT_PREFIX : XML_FORMAT_WITHOUT_PREFIX); } else { this.resolverFormat = (html? String.format(HTML_FORMAT_WITH_PREFIX, standardDialectPrefix) : String.format(XML_FORMAT_WITH_PREFIX, standardDialectPrefix)); } } public String resolveSelectorFromReference(final String reference) { Validate.notNull(reference, "Reference cannot be null"); final String selector = this.selectorsByReference.get(reference); if (selector != null) { return selector; } final String newSelector = String.format(this.resolverFormat, reference); this.selectorsByReference.put(reference, newSelector); return newSelector; } }
if (standardDialectPrefix == null || standardDialectPrefix.length() == 0) { return HTML_INSTANCE_NO_PREFIX; } final String prefix = standardDialectPrefix.toLowerCase(); final TemplateFragmentMarkupReferenceResolver resolver = HTML_INSTANCES_BY_PREFIX.get(prefix); if (resolver != null) { return resolver; } final TemplateFragmentMarkupReferenceResolver newResolver = new TemplateFragmentMarkupReferenceResolver(true, prefix); HTML_INSTANCES_BY_PREFIX.putIfAbsent(prefix, newResolver); return HTML_INSTANCES_BY_PREFIX.get(prefix);
1,241
176
1,417
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/decoupled/DecoupledInjectedAttribute.java
DecoupledInjectedAttribute
toString
class DecoupledInjectedAttribute { final char[] buffer; final int nameOffset; final int nameLen; final int operatorOffset; final int operatorLen; final int valueContentOffset; final int valueContentLen; final int valueOuterOffset; final int valueOuterLen; /* * We use a factory method here because we will not be using the same buffer specified for this method, so we * require a bit of processing before actually calling a constructor (not that this could not be done at the * constructor, but it gives us higher flexibility this way. Maybe in the future we reuse instances or something... */ public static DecoupledInjectedAttribute createAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int operatorOffset, final int operatorLen, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen) { final char[] newBuffer = new char[nameLen + operatorLen + valueOuterLen]; System.arraycopy(buffer, nameOffset, newBuffer, 0, nameLen); System.arraycopy(buffer, operatorOffset, newBuffer, nameLen, operatorLen); System.arraycopy(buffer, valueOuterOffset, newBuffer, (nameLen + operatorLen), valueOuterLen); return new DecoupledInjectedAttribute( newBuffer, 0, nameLen, (operatorOffset - nameOffset), operatorLen, (valueContentOffset - nameOffset), valueContentLen, (valueOuterOffset - nameOffset), valueOuterLen); } private DecoupledInjectedAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int operatorOffset, final int operatorLen, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen) { super(); this.buffer = buffer; this.nameOffset = nameOffset; this.nameLen = nameLen; this.operatorOffset = operatorOffset; this.operatorLen = operatorLen; this.valueContentOffset = valueContentOffset; this.valueContentLen = valueContentLen; this.valueOuterOffset = valueOuterOffset; this.valueOuterLen = valueOuterLen; } public String getName() { return new String(this.buffer, this.nameOffset, this.nameLen); } public String getOperator() { return new String(this.buffer, this.operatorOffset, this.operatorLen); } public String getValueContent() { return new String(this.buffer, this.valueContentOffset, this.valueContentLen); } public String getValueOuter() { return new String(this.buffer, this.valueOuterOffset, this.valueOuterLen); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
// The internal buffer should not be shared, it should only contain this attribute return new String(this.buffer);
754
30
784
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/decoupled/DecoupledTemplateLogic.java
DecoupledTemplateLogic
addInjectedAttribute
class DecoupledTemplateLogic { private final Map<String, List<DecoupledInjectedAttribute>> injectedAttributes = new HashMap<String, List<DecoupledInjectedAttribute>>(20); public DecoupledTemplateLogic() { super(); } public boolean hasInjectedAttributes() { return this.injectedAttributes.size() > 0; } public Set<String> getAllInjectedAttributeSelectors() { return this.injectedAttributes.keySet(); } public List<DecoupledInjectedAttribute> getInjectedAttributesForSelector(final String selector) { return this.injectedAttributes.get(selector); } public void addInjectedAttribute(final String selector, final DecoupledInjectedAttribute injectedAttribute) {<FILL_FUNCTION_BODY>} @Override public String toString() { // We will order the keys so that we can more easily debug and test based on this toString() final List<String> keys = new ArrayList<String>(this.injectedAttributes.keySet()); Collections.sort(keys); final StringBuilder strBuilder = new StringBuilder(); strBuilder.append('{'); for (int i = 0; i < keys.size(); i++) { if (i > 0) { strBuilder.append(", "); } strBuilder.append(keys.get(i)); strBuilder.append('='); strBuilder.append(this.injectedAttributes.get(keys.get(i))); } strBuilder.append('}'); return strBuilder.toString(); } }
Validate.notNull(selector, "Selector cannot be null"); Validate.notNull(injectedAttribute, "Injected Attribute cannot be null"); List<DecoupledInjectedAttribute> injectedAttributesForSelector = this.injectedAttributes.get(selector); if (injectedAttributesForSelector == null) { injectedAttributesForSelector = new ArrayList<DecoupledInjectedAttribute>(2); this.injectedAttributes.put(selector, injectedAttributesForSelector); } injectedAttributesForSelector.add(injectedAttribute);
421
140
561
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/decoupled/DecoupledTemplateLogicMarkupHandler.java
DecoupledTemplateLogicMarkupHandler
handleOpenElementEnd
class DecoupledTemplateLogicMarkupHandler extends AbstractChainedMarkupHandler { // The node-selection markup handler should be the first one in the chain, so that we make sure that any // block selection operations (like the ones performed by the block-selection markup handlers) can be // performed on attributes injected in a decoupled manner (eg: a "th:fragment"/"th:ref" injected externally) private static final int INJECTION_LEVEL = 0; private static final char[] INNER_WHITE_SPACE = " ".toCharArray(); private final DecoupledTemplateLogic decoupledTemplateLogic; private final boolean injectAttributes; private ParseSelection parseSelection; private boolean lastWasInnerWhiteSpace = false; public DecoupledTemplateLogicMarkupHandler(final DecoupledTemplateLogic decoupledTemplateLogic, final IMarkupHandler handler) { super(handler); Validate.notNull(decoupledTemplateLogic, "Decoupled Template Logic cannot be null"); this.decoupledTemplateLogic = decoupledTemplateLogic; this.injectAttributes = this.decoupledTemplateLogic.hasInjectedAttributes(); } @Override public void setParseSelection(final ParseSelection selection) { this.parseSelection = selection; super.setParseSelection(selection); } @Override public void handleStandaloneElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) throws ParseException { if (this.injectAttributes) { processInjectedAttributes(line, col); } super.handleStandaloneElementEnd(buffer, nameOffset, nameLen, minimized, line, col); } @Override public void handleOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws ParseException {<FILL_FUNCTION_BODY>} @Override public void handleInnerWhiteSpace( final char[] buffer, final int offset, final int len, final int line, final int col) throws ParseException { this.lastWasInnerWhiteSpace = true; super.handleInnerWhiteSpace(buffer, offset, len, line, col); } @Override public void handleAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) throws ParseException { this.lastWasInnerWhiteSpace = false; super.handleAttribute( buffer, nameOffset, nameLen, nameLine, nameCol, operatorOffset, operatorLen, operatorLine, operatorCol, valueContentOffset, valueContentLen, valueOuterOffset, valueOuterLen, valueLine, valueCol); } private void processInjectedAttributes(final int line, final int col) throws ParseException { if (!this.parseSelection.isMatchingAny(INJECTION_LEVEL)) { return; } final String[] selectors = this.parseSelection.getCurrentSelection(INJECTION_LEVEL); if (selectors == null || selectors.length == 0) { return; } for (final String selector : selectors) { final List<DecoupledInjectedAttribute> injectedAttributesForSelector = this.decoupledTemplateLogic.getInjectedAttributesForSelector(selector); if (injectedAttributesForSelector == null) { continue; } for (final DecoupledInjectedAttribute injectedAttribute : injectedAttributesForSelector) { if (!this.lastWasInnerWhiteSpace) { super.handleInnerWhiteSpace(INNER_WHITE_SPACE, 0, 1, line, col); } super.handleAttribute( injectedAttribute.buffer, injectedAttribute.nameOffset, injectedAttribute.nameLen, line, col, injectedAttribute.operatorOffset, injectedAttribute.operatorLen, line, col, injectedAttribute.valueContentOffset, injectedAttribute.valueContentLen, injectedAttribute.valueOuterOffset, injectedAttribute.valueOuterLen, line, col); this.lastWasInnerWhiteSpace = false; } } } }
if (this.injectAttributes) { processInjectedAttributes(line, col); } super.handleOpenElementEnd(buffer, nameOffset, nameLen, line, col);
1,209
52
1,261
<methods>public void handleAttribute(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleAutoCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoOpenElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleAutoOpenElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleCDATASection(char[], int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleComment(char[], int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleDocType(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleDocumentEnd(long, long, int, int) throws org.attoparser.ParseException,public void handleDocumentStart(long, int, int) throws org.attoparser.ParseException,public void handleInnerWhiteSpace(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleOpenElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleOpenElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleProcessingInstruction(char[], int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void handleStandaloneElementEnd(char[], int, int, boolean, int, int) throws org.attoparser.ParseException,public void handleStandaloneElementStart(char[], int, int, boolean, int, int) throws org.attoparser.ParseException,public void handleText(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleUnmatchedCloseElementEnd(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleUnmatchedCloseElementStart(char[], int, int, int, int) throws org.attoparser.ParseException,public void handleXmlDeclaration(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.attoparser.ParseException,public void setParseConfiguration(org.attoparser.config.ParseConfiguration) ,public void setParseSelection(org.attoparser.select.ParseSelection) ,public void setParseStatus(org.attoparser.ParseStatus) <variables>private final org.attoparser.IMarkupHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/decoupled/DecoupledTemplateLogicUtils.java
DecoupledTemplateLogicUtils
computeDecoupledTemplateLogic
class DecoupledTemplateLogicUtils { private static final Logger logger = LoggerFactory.getLogger(DecoupledTemplateLogicUtils.class); public static DecoupledTemplateLogic computeDecoupledTemplateLogic( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final TemplateMode templateMode, final IMarkupParser parser) throws IOException, ParseException {<FILL_FUNCTION_BODY>} private DecoupledTemplateLogicUtils() { super(); } }
Validate.notNull(configuration, "Engine Configuration cannot be null"); Validate.notNull(template, "Template cannot be null"); Validate.notNull(resource, "Template Resource cannot be null"); Validate.notNull(templateMode, "Template Mode cannot be null"); final IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver = configuration.getDecoupledTemplateLogicResolver(); final ITemplateResource decoupledResource = decoupledTemplateLogicResolver.resolveDecoupledTemplateLogic( configuration, ownerTemplate, template, templateSelectors, resource, templateMode); if (!decoupledResource.exists()) { if (logger.isTraceEnabled()) { logger.trace( "[THYMELEAF][{}] Decoupled logic for template \"{}\" could not be resolved as relative resource \"{}\". " + "This does not need to be an error, as templates may lack a corresponding decoupled logic file.", new Object[] {TemplateEngine.threadIndex(), LoggingUtils.loggifyTemplateName(template), decoupledResource.getDescription()}); } return null; } if (logger.isTraceEnabled()) { logger.trace( "[THYMELEAF][{}] Decoupled logic for template \"{}\" has been resolved as relative resource \"{}\"", new Object[] {TemplateEngine.threadIndex(), LoggingUtils.loggifyTemplateName(template), decoupledResource.getDescription()}); } /* * The decoupled template logic resource exists, so we should parse it before the template itself, in order * to obtain the logic to be injected on the "real" template during parsing. */ final DecoupledTemplateLogicBuilderMarkupHandler decoupledMarkupHandler = new DecoupledTemplateLogicBuilderMarkupHandler(template, templateMode); parser.parse(decoupledResource.reader(), decoupledMarkupHandler); return decoupledMarkupHandler.getDecoupledTemplateLogic();
155
506
661
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/markup/decoupled/StandardDecoupledTemplateLogicResolver.java
StandardDecoupledTemplateLogicResolver
resolveDecoupledTemplateLogic
class StandardDecoupledTemplateLogicResolver implements IDecoupledTemplateLogicResolver { /** * <p> * Default suffix applied to the relative resources resolved: {@value} * </p> */ public static final String DECOUPLED_TEMPLATE_LOGIC_FILE_SUFFIX = ".th.xml"; private String prefix = null; private String suffix = DECOUPLED_TEMPLATE_LOGIC_FILE_SUFFIX; public StandardDecoupledTemplateLogicResolver() { super(); } public String getSuffix() { return this.suffix; } public void setSuffix(final String suffix) { this.suffix = suffix; } public String getPrefix() { return this.prefix; } public void setPrefix(final String prefix) { this.prefix = prefix; } public ITemplateResource resolveDecoupledTemplateLogic( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final TemplateMode templateMode) {<FILL_FUNCTION_BODY>} }
String relativeLocation = resource.getBaseName(); if (this.prefix != null) { relativeLocation = this.prefix + relativeLocation; } if (this.suffix != null) { relativeLocation = relativeLocation + this.suffix; } return resource.relative(relativeLocation);
320
84
404
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/raw/RawParseException.java
RawParseException
message
class RawParseException extends Exception { private static final long serialVersionUID = -104133072151159140L; private final Integer line; private final Integer col; public RawParseException() { super(); this.line = null; this.col = null; } public RawParseException(final String message, final Throwable throwable) { super(message(message, throwable), throwable); if (throwable != null && throwable instanceof RawParseException) { this.line = ((RawParseException)throwable).getLine(); this.col = ((RawParseException)throwable).getCol(); } else { this.line = null; this.col = null; } } public RawParseException(final String message) { super(message); this.line = null; this.col = null; } public RawParseException(final Throwable throwable) { super(message(null, throwable), throwable); if (throwable != null && throwable instanceof RawParseException) { this.line = ((RawParseException)throwable).getLine(); this.col = ((RawParseException)throwable).getCol(); } else { this.line = null; this.col = null; } } public RawParseException(final int line, final int col) { super(messagePrefix(line, col)); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public RawParseException(final String message, final Throwable throwable, final int line, final int col) { super(messagePrefix(line, col) + " " + message, throwable); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public RawParseException(final String message, final int line, final int col) { super(messagePrefix(line, col) + " " + message); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public RawParseException(final Throwable throwable, final int line, final int col) { super(messagePrefix(line, col), throwable); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } private static String messagePrefix(final int line, final int col) { return "(Line = " + line + ", Column = " + col + ")"; } private static String message(final String message, final Throwable throwable) {<FILL_FUNCTION_BODY>} public Integer getLine() { return this.line; } public Integer getCol() { return this.col; } }
if (throwable != null && throwable instanceof RawParseException) { final RawParseException exception = (RawParseException)throwable; if (exception.getLine() != null && exception.getCol() != null) { return "(Line = " + exception.getLine() + ", Column = " + exception.getCol() + ")" + (message != null? (" " + message) : throwable.getMessage()); } } if (message != null) { return message; } if (throwable != null) { return throwable.getMessage(); } return null;
748
163
911
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/raw/RawParser.java
RawParser
parseDocument
class RawParser { private final BufferPool pool; RawParser(final int poolSize, final int bufferSize) { super(); this.pool = new BufferPool(poolSize, bufferSize); } public void parse(final String document, final IRawHandler handler) throws RawParseException { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } parse(new StringReader(document), handler); } public void parse( final Reader reader, final IRawHandler handler) throws RawParseException { if (reader == null) { throw new IllegalArgumentException("Reader cannot be null"); } if (handler == null) { throw new IllegalArgumentException("Handler cannot be null"); } parseDocument(reader, this.pool.poolBufferSize, handler); } /* * This method receiving the buffer size with package visibility allows * testing different buffer sizes. */ void parseDocument(final Reader reader, final int suggestedBufferSize, final IRawHandler handler) throws RawParseException {<FILL_FUNCTION_BODY>} private static int[] computeLastLineCol(final char[] buffer, final int bufferContentSize) { if (bufferContentSize == 0) { return new int[] {1, 1}; } int line = 1; int col = 1; char c; int lastLineFeed = 0; int n = bufferContentSize; int i = 0; while (n-- != 0) { c = buffer[i]; if (c == '\n') { line++; lastLineFeed = i; } i++; } col = bufferContentSize - lastLineFeed; return new int[] {line, col}; } /* * This class models a pool of buffers, used to keep the amount of * large char[] buffer objects required to operate to a minimum. * * Note this pool never blocks, so if a new buffer is needed and all * are currently allocated, a new char[] object is created and returned. * */ private static final class BufferPool { private final char[][] pool; private final boolean[] allocated; private final int poolBufferSize; private BufferPool(final int poolSize, final int poolBufferSize) { super(); this.pool = new char[poolSize][]; this.allocated = new boolean[poolSize]; this.poolBufferSize = poolBufferSize; for (int i = 0; i < this.pool.length; i++) { this.pool[i] = new char[this.poolBufferSize]; } Arrays.fill(this.allocated, false); } private synchronized char[] allocateBuffer(final int bufferSize) { if (bufferSize != this.poolBufferSize) { // We will only pool buffers of the default size. If a different size is required, we just // create it without pooling. return new char[bufferSize]; } for (int i = 0; i < this.pool.length; i++) { if (!this.allocated[i]) { this.allocated[i] = true; return this.pool[i]; } } return new char[bufferSize]; } private synchronized void releaseBuffer(final char[] buffer) { if (buffer == null) { return; } if (buffer.length != this.poolBufferSize) { // This buffer cannot be part of the pool - only buffers with a specific size are contained return; } for (int i = 0; i < this.pool.length; i++) { if (this.pool[i] == buffer) { // Found it. Mark it as non-allocated this.allocated[i] = false; return; } } // The buffer wasn't part of our pool. Just return. } } }
// We are trying to read the entire resource into the buffer. If it's not big enough, // then it will have to be grown. Note grown buffers are not maintained by the pool, // so template cache should play a more important role for this, allowing the system to // not require the creation of large buffers each time. final long parsingStartTimeNanos = System.nanoTime(); char[] buffer = null; try { handler.handleDocumentStart(parsingStartTimeNanos, 1, 1); int bufferSize = suggestedBufferSize; buffer = this.pool.allocateBuffer(bufferSize); int bufferContentSize = reader.read(buffer); boolean cont = (bufferContentSize != -1); while (cont) { if (bufferContentSize == bufferSize) { // Buffer is not big enough, double it! char[] newBuffer = null; try { bufferSize *= 2; newBuffer = this.pool.allocateBuffer(bufferSize); System.arraycopy(buffer, 0, newBuffer, 0, bufferContentSize); this.pool.releaseBuffer(buffer); buffer = newBuffer; } catch (final Exception ignored) { this.pool.releaseBuffer(newBuffer); } } final int read = reader.read(buffer, bufferContentSize, (bufferSize - bufferContentSize)); if (read != -1) { bufferContentSize += read; } else { cont = false; } } handler.handleText(buffer, 0, bufferContentSize, 1, 1); final int[] lastLineCol = computeLastLineCol(buffer, bufferContentSize); final long parsingEndTimeNanos = System.nanoTime(); handler.handleDocumentEnd(parsingEndTimeNanos, (parsingEndTimeNanos - parsingStartTimeNanos), lastLineCol[0], lastLineCol[1]); } catch (final RawParseException e) { throw e; } catch (final Exception e) { throw new RawParseException(e); } finally { this.pool.releaseBuffer(buffer); try { reader.close(); } catch (final Throwable ignored) { // This exception can be safely ignored } }
1,063
601
1,664
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/raw/RawTemplateParser.java
RawTemplateParser
parseString
class RawTemplateParser implements ITemplateParser { private final RawParser parser; public RawTemplateParser(final int bufferPoolSize, final int bufferSize) { super(); this.parser = new RawParser(bufferPoolSize, bufferSize); } /* * ------------------- * PARSE METHODS * ------------------- */ public void parseStandalone( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final TemplateMode templateMode, final boolean useDecoupledLogic, final ITemplateHandler handler) { Validate.notNull(configuration, "Engine Configuration cannot be null"); // ownerTemplate CAN be null if this is a first-level template Validate.notNull(template, "Template cannot be null"); Validate.notNull(resource, "Template Resource cannot be null"); Validate.isTrue(templateSelectors == null || templateSelectors.isEmpty(), "Template selectors cannot be specified for a template using RAW template mode: template " + "insertion operations must be always performed on whole template files, not fragments"); Validate.notNull(templateMode, "Template Mode cannot be null"); Validate.isTrue(templateMode == TemplateMode.RAW, "Template Mode has to be RAW"); Validate.isTrue(!useDecoupledLogic, "Cannot use decoupled logic in template mode " + templateMode); Validate.notNull(handler, "Template Handler cannot be null"); parse(configuration, ownerTemplate, template, templateSelectors, resource, 0, 0, templateMode, handler); } public void parseString( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final int lineOffset, final int colOffset, final TemplateMode templateMode, final ITemplateHandler handler) {<FILL_FUNCTION_BODY>} private void parse( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final int lineOffset, final int colOffset, final TemplateMode templateMode, final ITemplateHandler templateHandler) { // For a String template, we will use the ownerTemplate as templateName for its parsed events final String templateName = (resource != null? template : ownerTemplate); try { // The final step of the handler chain will be the adapter that will convert the raw parser's handler chain to thymeleaf's. final IRawHandler handler = new TemplateHandlerAdapterRawHandler( templateName, templateHandler, lineOffset, colOffset); // Obtain the resource reader final Reader templateReader = (resource != null? resource.reader() : new StringReader(template)); this.parser.parse(templateReader, handler); } catch (final IOException e) { final String message = "An error happened during template parsing"; throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e); } catch (final RawParseException e) { final String message = "An error happened during template parsing"; if (e.getLine() != null && e.getCol() != null) { throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e.getLine().intValue(), e.getCol().intValue(), e); } throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e); } } }
Validate.notNull(configuration, "Engine Configuration cannot be null"); Validate.notNull(ownerTemplate, "Owner template cannot be null"); Validate.notNull(template, "Template cannot be null"); // NOTE selectors cannot be specified when parsing a nested template Validate.notNull(templateMode, "Template mode cannot be null"); Validate.isTrue(templateMode == TemplateMode.RAW, "Template Mode has to be RAW"); Validate.notNull(handler, "Template Handler cannot be null"); parse(configuration, ownerTemplate, template, null, null, lineOffset, colOffset, templateMode, handler);
920
161
1,081
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/AbstractChainedTextHandler.java
AbstractChainedTextHandler
handleAttribute
class AbstractChainedTextHandler extends AbstractTextHandler { private final ITextHandler next; protected AbstractChainedTextHandler(final ITextHandler next) { super(); this.next = next; } protected ITextHandler getNext() { return this.next; } public void handleDocumentStart( final long startTimeNanos, final int line, final int col) throws TextParseException { this.next.handleDocumentStart(startTimeNanos, line, col); } public void handleDocumentEnd( final long endTimeNanos, final long totalTimeNanos, final int line, final int col) throws TextParseException { this.next.handleDocumentEnd(endTimeNanos, totalTimeNanos, line, col); } public void handleText( final char[] buffer, final int offset, final int len, final int line, final int col) throws TextParseException { this.next.handleText(buffer, offset, len, line, col); } public void handleComment( final char[] buffer, final int contentOffset, final int contentLen, final int outerOffset, final int outerLen, final int line, final int col) throws TextParseException { this.next.handleComment(buffer, contentOffset, contentLen, outerOffset, outerLen, line, col); } public void handleStandaloneElementStart( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) throws TextParseException { this.next.handleStandaloneElementStart(buffer, nameOffset, nameLen, minimized, line, col); } public void handleStandaloneElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) throws TextParseException { this.next.handleStandaloneElementEnd(buffer, nameOffset, nameLen, minimized, line, col); } public void handleOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { this.next.handleOpenElementStart(buffer, nameOffset, nameLen, line, col); } public void handleOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { this.next.handleOpenElementEnd(buffer, nameOffset, nameLen, line, col); } public void handleCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { this.next.handleCloseElementStart(buffer, nameOffset, nameLen, line, col); } public void handleCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { this.next.handleCloseElementEnd(buffer, nameOffset, nameLen, line, col); } public void handleAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) throws TextParseException {<FILL_FUNCTION_BODY>} }
this.next.handleAttribute( buffer, nameOffset, nameLen, nameLine, nameCol, operatorOffset, operatorLen, operatorLine, operatorCol, valueContentOffset, valueContentLen, valueOuterOffset, valueOuterLen, valueLine, valueCol);
937
78
1,015
<methods>public void handleAttribute(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleComment(char[], int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentEnd(long, long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentStart(long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementEnd(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementStart(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleText(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException<variables>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/AbstractTextHandler.java
AbstractTextHandler
handleOpenElementEnd
class AbstractTextHandler implements ITextHandler { protected AbstractTextHandler() { super(); } public void handleDocumentStart( final long startTimeNanos, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleDocumentEnd( final long endTimeNanos, final long totalTimeNanos, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleText( final char[] buffer, final int offset, final int len, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleComment( final char[] buffer, final int contentOffset, final int contentLen, final int outerOffset, final int outerLen, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleStandaloneElementStart( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleStandaloneElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException {<FILL_FUNCTION_BODY>} public void handleCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) throws TextParseException { // Nothing to be done here, meant to be overridden if required } public void handleAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) throws TextParseException { // Nothing to be done here, meant to be overridden if required } }
// Nothing to be done here, meant to be overridden if required
820
20
840
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/AbstractTextTemplateParser.java
AbstractTextTemplateParser
parse
class AbstractTextTemplateParser implements ITemplateParser { private final TextParser parser; protected AbstractTextTemplateParser( final int bufferPoolSize, final int bufferSize, final boolean processCommentsAndLiterals, final boolean standardDialectPresent) { super(); this.parser = new TextParser(bufferPoolSize, bufferSize, processCommentsAndLiterals, standardDialectPresent); } /* * ------------------- * PARSE METHODS * ------------------- */ public void parseStandalone( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final TemplateMode templateMode, final boolean useDecoupledLogic, final ITemplateHandler handler) { Validate.notNull(configuration, "Engine Configuration cannot be null"); // ownerTemplate CAN be null if this is a first-level template Validate.notNull(template, "Template cannot be null"); Validate.notNull(resource, "Template Resource cannot be null"); Validate.isTrue(templateSelectors == null || templateSelectors.isEmpty(), "Template selectors cannot be specified for a template using a TEXT template mode: template " + "insertion operations must be always performed on whole template files, not fragments"); Validate.notNull(templateMode, "Template Mode cannot be null"); Validate.isTrue(templateMode.isText(), "Template Mode has to be a text template mode"); Validate.isTrue(!useDecoupledLogic, "Cannot use decoupled logic in template mode " + templateMode); Validate.notNull(handler, "Template Handler cannot be null"); parse(configuration, ownerTemplate, template, templateSelectors, resource, 0, 0, templateMode, handler); } public void parseString( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final int lineOffset, final int colOffset, final TemplateMode templateMode, final ITemplateHandler handler) { Validate.notNull(configuration, "Engine Configuration cannot be null"); Validate.notNull(ownerTemplate, "Owner template cannot be null"); Validate.notNull(template, "Template cannot be null"); // NOTE selectors cannot be specified when parsing a nested template Validate.notNull(templateMode, "Template mode cannot be null"); Validate.isTrue(templateMode.isText(), "Template Mode has to be a text template mode"); Validate.notNull(handler, "Template Handler cannot be null"); parse(configuration, ownerTemplate, template, null, null, lineOffset, colOffset, templateMode, handler); } private void parse( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Set<String> templateSelectors, final ITemplateResource resource, final int lineOffset, final int colOffset, final TemplateMode templateMode, final ITemplateHandler templateHandler) {<FILL_FUNCTION_BODY>} }
// For a String template, we will use the ownerTemplate as templateName for its parsed events final String templateName = (resource != null? template : ownerTemplate); try { // The final step of the handler chain will be the adapter that will convert the text parser's handler chain to thymeleaf's. ITextHandler handler = new TemplateHandlerAdapterTextHandler( templateName, templateHandler, configuration.getElementDefinitions(), configuration.getAttributeDefinitions(), templateMode, lineOffset, colOffset); // Just before the adapter markup handler, we will insert the processing of inlined output expressions // but only if we are not going to disturb the execution of text processors coming from other dialects // (which might see text blocks coming as several blocks instead of just one). if (configuration instanceof EngineConfiguration && ((EngineConfiguration) configuration).isModelReshapeable(templateMode)) { handler = new InlinedOutputExpressionTextHandler( configuration, templateMode, configuration.getStandardDialectPrefix(), handler); } // Obtain the resource reader Reader templateReader = (resource != null? resource.reader() : new StringReader(template)); // Add the required reader wrappers in order to process parser-level and prototype-only comment blocks if (templateMode == TemplateMode.TEXT) { // There are no /*[+...+]*/ blocks in TEXT mode (it makes no sense) templateReader = new ParserLevelCommentTextReader(templateReader); } else { // TemplateMode.JAVASCRIPT || TemplateMode.CSS templateReader = new ParserLevelCommentTextReader(new PrototypeOnlyCommentTextReader(templateReader)); } this.parser.parse(templateReader, handler); } catch (final IOException e) { final String message = "An error happened during template parsing"; throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e); } catch (final TextParseException e) { final String message = "An error happened during template parsing"; if (e.getLine() != null && e.getCol() != null) { throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e.getLine().intValue(), e.getCol().intValue(), e); } throw new TemplateInputException(message, (resource != null? resource.getDescription() : template), e); }
775
621
1,396
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/EventProcessorTextHandler.java
StructureNamesRepository
getStructureName
class StructureNamesRepository { private static final int REPOSITORY_INITIAL_LEN = 20; private static final int REPOSITORY_INITIAL_INC = 5; private char[][] repository; private int repositorySize; StructureNamesRepository() { super(); this.repository = new char[REPOSITORY_INITIAL_LEN][]; this.repositorySize = 0; } char[] getStructureName(final char[] text, final int offset, final int len) {<FILL_FUNCTION_BODY>} private char[] storeStructureName(final int index, final char[] text, final int offset, final int len) { if (this.repositorySize == this.repository.length) { // We must grow the repository! final char[][] newRepository = new char[this.repository.length + REPOSITORY_INITIAL_INC][]; Arrays.fill(newRepository, null); System.arraycopy(this.repository, 0, newRepository, 0, this.repositorySize); this.repository = newRepository; } // binary search returned (-(insertion point) - 1) final int insertionIndex = ((index + 1) * -1); // Create the char[] for the structure name final char[] structureName = new char[len]; System.arraycopy(text, offset, structureName, 0, len); // Make room and insert the new element System.arraycopy(this.repository, insertionIndex, this.repository, insertionIndex + 1, this.repositorySize - insertionIndex); this.repository[insertionIndex] = structureName; this.repositorySize++; return structureName; } }
// We are looking for exact matches here, disregarding the TEXT_PARSING_CASE_SENSITIVE constant value final int index = TextUtils.binarySearch(true, this.repository, 0, this.repositorySize, text, offset, len); if (index >= 0) { return this.repository[index]; } /* * NOT FOUND. We need to store the text */ return storeStructureName(index, text, offset, len);
445
129
574
<methods>public void handleAttribute(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleComment(char[], int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentEnd(long, long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentStart(long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementEnd(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementStart(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleText(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException<variables>private final non-sealed org.thymeleaf.templateparser.text.ITextHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/InlinedOutputExpressionTextHandler.java
InlineTextAdapterPreProcessorHandler
handleText
class InlineTextAdapterPreProcessorHandler implements IInlinePreProcessorHandler { private ITextHandler handler; InlineTextAdapterPreProcessorHandler(final ITextHandler handler) { super(); this.handler = handler; } public void handleText( final char[] buffer, final int offset, final int len, final int line, final int col) {<FILL_FUNCTION_BODY>} public void handleStandaloneElementStart( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) { try { this.handler.handleStandaloneElementStart(buffer, nameOffset, nameLen, minimized, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleStandaloneElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final boolean minimized, final int line, final int col) { try { this.handler.handleStandaloneElementEnd(buffer, nameOffset, nameLen, minimized, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleOpenElementStart(buffer, nameOffset, nameLen, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleOpenElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoOpenElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { throw new TemplateProcessingException("Parse exception during processing of inlining: auto-open not allowed in text mode"); } public void handleAutoOpenElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { throw new TemplateProcessingException("Parse exception during processing of inlining: auto-open not allowed in text mode"); } public void handleCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleCloseElementStart(buffer, nameOffset, nameLen, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { try { this.handler.handleCloseElementEnd(buffer, nameOffset, nameLen, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } public void handleAutoCloseElementStart( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { throw new TemplateProcessingException("Parse exception during processing of inlining: auto-close not allowed in text mode"); } public void handleAutoCloseElementEnd( final char[] buffer, final int nameOffset, final int nameLen, final int line, final int col) { throw new TemplateProcessingException("Parse exception during processing of inlining: auto-close not allowed in text mode"); } public void handleAttribute( final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) { try { this.handler.handleAttribute( buffer, nameOffset, nameLen, nameLine, nameCol, operatorOffset, operatorLen, operatorLine, operatorCol, valueContentOffset, valueContentLen, valueOuterOffset, valueOuterLen, valueLine, valueCol); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); } } }
try { this.handler.handleText(buffer, offset, len, line, col); } catch (final TextParseException e) { throw new TemplateProcessingException("Parse exception during processing of inlining", e); }
1,265
61
1,326
<methods>public void handleAttribute(char[], int, int, int, int, int, int, int, int, int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleCloseElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleComment(char[], int, int, int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentEnd(long, long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleDocumentStart(long, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementEnd(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleOpenElementStart(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementEnd(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleStandaloneElementStart(char[], int, int, boolean, int, int) throws org.thymeleaf.templateparser.text.TextParseException,public void handleText(char[], int, int, int, int) throws org.thymeleaf.templateparser.text.TextParseException<variables>private final non-sealed org.thymeleaf.templateparser.text.ITextHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/ParsingLocatorUtil.java
ParsingLocatorUtil
countChar
class ParsingLocatorUtil { public static void countChar(final int[] locator, final char c) {<FILL_FUNCTION_BODY>} private ParsingLocatorUtil() { super(); } }
if (c == '\n') { locator[0]++; locator[1] = 1; return; } locator[1]++;
66
48
114
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/TextParseException.java
TextParseException
message
class TextParseException extends Exception { private static final long serialVersionUID = -104133072151159140L; private final Integer line; private final Integer col; public TextParseException() { super(); this.line = null; this.col = null; } public TextParseException(final String message, final Throwable throwable) { super(message(message, throwable), throwable); if (throwable != null && throwable instanceof TextParseException) { this.line = ((TextParseException)throwable).getLine(); this.col = ((TextParseException)throwable).getCol(); } else { this.line = null; this.col = null; } } public TextParseException(final String message) { super(message); this.line = null; this.col = null; } public TextParseException(final Throwable throwable) { super(message(null, throwable), throwable); if (throwable != null && throwable instanceof TextParseException) { this.line = ((TextParseException)throwable).getLine(); this.col = ((TextParseException)throwable).getCol(); } else { this.line = null; this.col = null; } } public TextParseException(final int line, final int col) { super(messagePrefix(line, col)); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public TextParseException(final String message, final Throwable throwable, final int line, final int col) { super(messagePrefix(line, col) + " " + message, throwable); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public TextParseException(final String message, final int line, final int col) { super(messagePrefix(line, col) + " " + message); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } public TextParseException(final Throwable throwable, final int line, final int col) { super(messagePrefix(line, col), throwable); this.line = Integer.valueOf(line); this.col = Integer.valueOf(col); } private static String messagePrefix(final int line, final int col) { return "(Line = " + line + ", Column = " + col + ")"; } private static String message(final String message, final Throwable throwable) {<FILL_FUNCTION_BODY>} public Integer getLine() { return this.line; } public Integer getCol() { return this.col; } }
if (throwable != null && throwable instanceof TextParseException) { final TextParseException exception = (TextParseException)throwable; if (exception.getLine() != null && exception.getCol() != null) { return "(Line = " + exception.getLine() + ", Column = " + exception.getCol() + ")" + (message != null? (" " + message) : throwable.getMessage()); } } if (message != null) { return message; } if (throwable != null) { return throwable.getMessage(); } return null;
748
163
911
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/TextParsingCommentUtil.java
TextParsingCommentUtil
isCommentBlockEnd
class TextParsingCommentUtil { private TextParsingCommentUtil() { super(); } public static void parseComment( final char[] buffer, final int offset, final int len, final int line, final int col, final ITextHandler handler) throws TextParseException { if (len < 4 || !isCommentBlockStart(buffer, offset, offset + len) || !isCommentBlockEnd(buffer, (offset + len) - 2, offset + len)) { throw new TextParseException( "Could not parse as a well-formed Comment: \"" + new String(buffer, offset, len) + "\"", line, col); } final int contentOffset = offset + 2; final int contentLen = len - 4; handler.handleComment( buffer, contentOffset, contentLen, offset, len, line, col); } static boolean isCommentBlockStart(final char[] buffer, final int offset, final int maxi) { return ((maxi - offset > 1) && buffer[offset] == '/' && buffer[offset + 1] == '*'); } static boolean isCommentBlockEnd(final char[] buffer, final int offset, final int maxi) {<FILL_FUNCTION_BODY>} static boolean isCommentLineStart(final char[] buffer, final int offset, final int maxi) { return ((maxi - offset > 1) && buffer[offset] == '/' && buffer[offset + 1] == '/'); } }
return ((maxi - offset > 1) && buffer[offset] == '*' && buffer[offset + 1] == '/');
405
37
442
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateparser/text/TextParsingLiteralUtil.java
TextParsingLiteralUtil
isRegexLiteralStart
class TextParsingLiteralUtil { private TextParsingLiteralUtil() { super(); } static boolean isRegexLiteralStart(final char[] buffer, final int offset, final int maxi) {<FILL_FUNCTION_BODY>} /* static boolean isRegexLiteralEnd(final char[] buffer, final int offset, final int maxi) { return ((maxi - offset > 1) && buffer[offset] == '*' && buffer[offset + 1] == '/'); } */ }
if (offset == 0 || buffer[offset] != '/') { return false; } // We will check that this is not one of the other structures starting with a slash (comments) if (TextParsingCommentUtil.isCommentBlockStart(buffer, offset, maxi)) { return false; } if (TextParsingCommentUtil.isCommentLineStart(buffer, offset, maxi)) { return false; } char c; int i = offset - 1; while (i >= 0) { c = buffer[i]; if (!Character.isWhitespace(c)) { return c == '(' || c == '=' || c == ','; } i--; } return false;
146
202
348
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresolver/DefaultTemplateResolver.java
DefaultTemplateResolver
setTemplateMode
class DefaultTemplateResolver extends AbstractTemplateResolver { /** * <p> * Default template mode: {@link TemplateMode#HTML} * </p> */ public static final TemplateMode DEFAULT_TEMPLATE_MODE = TemplateMode.HTML; private TemplateMode templateMode = DEFAULT_TEMPLATE_MODE; private String template = ""; /** * <p> * Creates a new instance of this template resolver. * </p> */ public DefaultTemplateResolver() { super(); } /** * <p> * Returns the template mode to be applied to templates resolved by * this template resolver. * </p> * * @return the template mode to be used. */ public final TemplateMode getTemplateMode() { return this.templateMode; } /** * <p> * Sets the template mode to be applied to templates resolved by this resolver. * </p> * * @param templateMode the template mode. */ public final void setTemplateMode(final TemplateMode templateMode) { Validate.notNull(templateMode, "Cannot set a null template mode value"); this.templateMode = templateMode; } /** * <p> * Sets the template mode to be applied to templates resolved by this resolver. * </p> * <p> * Allowed templates modes are defined by the {@link TemplateMode} class. * </p> * * @param templateMode the template mode. */ public final void setTemplateMode(final String templateMode) {<FILL_FUNCTION_BODY>} /** * <p> * Returns the text that will always be returned by this template resolver as the resolved template. * </p> * * @return the text to be returned as template. */ public String getTemplate() { return this.template; } /** * <p> * Set the text that will be returned as the resolved template. * </p> * * @param template the text to be returned as template. */ public void setTemplate(final String template) { this.template = template; } @Override protected ITemplateResource computeTemplateResource(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { return new StringTemplateResource(this.template); } @Override protected TemplateMode computeTemplateMode(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { return this.templateMode; } @Override protected ICacheEntryValidity computeValidity(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { return AlwaysValidCacheEntryValidity.INSTANCE; } }
// Setter overload actually goes against the JavaBeans spec, but having this one is good for legacy // compatibility reasons. Besides, given the getter returns TemplateMode, intelligent frameworks like // Spring will recognized the property as TemplateMode-typed and simply ignore this setter. Validate.notNull(templateMode, "Cannot set a null template mode value"); this.templateMode = TemplateMode.parse(templateMode);
783
102
885
<methods>public final boolean getCheckExistence() ,public final java.lang.String getName() ,public final java.lang.Integer getOrder() ,public final org.thymeleaf.util.PatternSpec getResolvablePatternSpec() ,public final Set<java.lang.String> getResolvablePatterns() ,public final boolean getUseDecoupledLogic() ,public final org.thymeleaf.templateresolver.TemplateResolution resolveTemplate(org.thymeleaf.IEngineConfiguration, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.Object>) ,public void setCheckExistence(boolean) ,public void setName(java.lang.String) ,public void setOrder(java.lang.Integer) ,public void setResolvablePatterns(Set<java.lang.String>) ,public void setUseDecoupledLogic(boolean) <variables>public static final boolean DEFAULT_EXISTENCE_CHECK,public static final boolean DEFAULT_USE_DECOUPLED_LOGIC,private boolean checkExistence,private java.lang.String name,private java.lang.Integer order,private final org.thymeleaf.util.PatternSpec resolvablePatternSpec,private boolean useDecoupledLogic
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresolver/StringTemplateResolver.java
StringTemplateResolver
setTemplateMode
class StringTemplateResolver extends AbstractTemplateResolver { /** * <p> * Default template mode: {@link TemplateMode#HTML} * </p> */ public static final TemplateMode DEFAULT_TEMPLATE_MODE = TemplateMode.HTML; /** * <p> * Default value for the <i>cacheable</i> flag: {@value} * </p> */ public static final boolean DEFAULT_CACHEABLE = false; /** * <p> * Default value for the cache TTL: null. This means the parsed template will live in * cache until removed by LRU (because of being the oldest entry). * </p> */ public static final Long DEFAULT_CACHE_TTL_MS = null; private TemplateMode templateMode = DEFAULT_TEMPLATE_MODE; private boolean cacheable = DEFAULT_CACHEABLE; private Long cacheTTLMs = DEFAULT_CACHE_TTL_MS; /** * <p> * Creates a new instance of this template resolver. * </p> */ public StringTemplateResolver() { super(); } /** * <p> * Returns the template mode to be applied to templates resolved by * this template resolver. * </p> * * @return the template mode to be used. */ public final TemplateMode getTemplateMode() { return this.templateMode; } /** * <p> * Sets the template mode to be applied to templates resolved by this resolver. * </p> * * @param templateMode the template mode. */ public final void setTemplateMode(final TemplateMode templateMode) { Validate.notNull(templateMode, "Cannot set a null template mode value"); this.templateMode = templateMode; } /** * <p> * Sets the template mode to be applied to templates resolved by this resolver. * </p> * <p> * Allowed templates modes are defined by the {@link TemplateMode} class. * </p> * * @param templateMode the template mode. */ public final void setTemplateMode(final String templateMode) {<FILL_FUNCTION_BODY>} /** * <p> * Returns whether templates resolved by this resolver have to be considered * cacheable or not. * </p> * * @return whether templates resolved are cacheable or not. */ public final boolean isCacheable() { return this.cacheable; } /** * <p> * Sets a new value for the <i>cacheable</i> flag. * </p> * * @param cacheable whether resolved patterns should be considered cacheable or not. */ public final void setCacheable(final boolean cacheable) { this.cacheable = cacheable; } /** * <p> * Returns the TTL (Time To Live) in cache of templates resolved by this * resolver. * </p> * <p> * If a template is resolved as <i>cacheable</i> but cache TTL is null, * this means the template will live in cache until evicted by LRU * (Least Recently Used) algorithm for being the oldest entry in cache. * </p> * * @return the cache TTL for resolved templates. */ public final Long getCacheTTLMs() { return this.cacheTTLMs; } /** * <p> * Sets a new value for the cache TTL for resolved templates. * </p> * <p> * If a template is resolved as <i>cacheable</i> but cache TTL is null, * this means the template will live in cache until evicted by LRU * (Least Recently Used) algorithm for being the oldest entry in cache. * </p> * * @param cacheTTLMs the new cache TTL, or null for using natural LRU eviction. */ public final void setCacheTTLMs(final Long cacheTTLMs) { this.cacheTTLMs = cacheTTLMs; } @Override public void setUseDecoupledLogic(final boolean useDecoupledLogic) { if (useDecoupledLogic) { throw new ConfigurationException("The 'useDecoupledLogic' flag is not allowed for String template resolution"); } super.setUseDecoupledLogic(useDecoupledLogic); } @Override protected ITemplateResource computeTemplateResource(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { return new StringTemplateResource(template); } @Override protected TemplateMode computeTemplateMode(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { return this.templateMode; } @Override protected ICacheEntryValidity computeValidity(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) { if (isCacheable()) { if (this.cacheTTLMs != null) { return new TTLCacheEntryValidity(this.cacheTTLMs.longValue()); } return AlwaysValidCacheEntryValidity.INSTANCE; } return NonCacheableCacheEntryValidity.INSTANCE; } }
// Setter overload actually goes against the JavaBeans spec, but having this one is good for legacy // compatibility reasons. Besides, given the getter returns TemplateMode, intelligent frameworks like // Spring will recognized the property as TemplateMode-typed and simply ignore this setter. Validate.notNull(templateMode, "Cannot set a null template mode value"); this.templateMode = TemplateMode.parse(templateMode);
1,471
102
1,573
<methods>public final boolean getCheckExistence() ,public final java.lang.String getName() ,public final java.lang.Integer getOrder() ,public final org.thymeleaf.util.PatternSpec getResolvablePatternSpec() ,public final Set<java.lang.String> getResolvablePatterns() ,public final boolean getUseDecoupledLogic() ,public final org.thymeleaf.templateresolver.TemplateResolution resolveTemplate(org.thymeleaf.IEngineConfiguration, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.Object>) ,public void setCheckExistence(boolean) ,public void setName(java.lang.String) ,public void setOrder(java.lang.Integer) ,public void setResolvablePatterns(Set<java.lang.String>) ,public void setUseDecoupledLogic(boolean) <variables>public static final boolean DEFAULT_EXISTENCE_CHECK,public static final boolean DEFAULT_USE_DECOUPLED_LOGIC,private boolean checkExistence,private java.lang.String name,private java.lang.Integer order,private final org.thymeleaf.util.PatternSpec resolvablePatternSpec,private boolean useDecoupledLogic
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresolver/UrlTemplateResolver.java
UrlTemplateResolver
computeValidity
class UrlTemplateResolver extends AbstractConfigurableTemplateResolver { private static final Pattern JSESSIONID_PATTERN = Pattern.compile("(.*?);jsessionid(.*?)"); public UrlTemplateResolver() { super(); } @Override protected ITemplateResource computeTemplateResource( final IEngineConfiguration configuration, final String ownerTemplate, final String template, final String resourceName, final String characterEncoding, final Map<String, Object> templateResolutionAttributes) { try { return new UrlTemplateResource(resourceName, characterEncoding); } catch (final MalformedURLException ignored) { return null; } } @Override protected ICacheEntryValidity computeValidity(final IEngineConfiguration configuration, final String ownerTemplate, final String template, final Map<String, Object> templateResolutionAttributes) {<FILL_FUNCTION_BODY>} }
/* * This check is made so that we don't fill the cache with entries for the same * template with different jsessionid values. */ if (JSESSIONID_PATTERN.matcher(template.toLowerCase()).matches()) { return NonCacheableCacheEntryValidity.INSTANCE; } return super.computeValidity(configuration, ownerTemplate, template, templateResolutionAttributes);
232
104
336
<methods>public void <init>() ,public final void addTemplateAlias(java.lang.String, java.lang.String) ,public final void clearTemplateAliases() ,public final org.thymeleaf.util.PatternSpec getCSSTemplateModePatternSpec() ,public final Set<java.lang.String> getCSSTemplateModePatterns() ,public final java.lang.Long getCacheTTLMs() ,public final org.thymeleaf.util.PatternSpec getCacheablePatternSpec() ,public final Set<java.lang.String> getCacheablePatterns() ,public final java.lang.String getCharacterEncoding() ,public final boolean getForceSuffix() ,public final boolean getForceTemplateMode() ,public final org.thymeleaf.util.PatternSpec getHtmlTemplateModePatternSpec() ,public final Set<java.lang.String> getHtmlTemplateModePatterns() ,public final org.thymeleaf.util.PatternSpec getJavaScriptTemplateModePatternSpec() ,public final Set<java.lang.String> getJavaScriptTemplateModePatterns() ,public final org.thymeleaf.util.PatternSpec getNonCacheablePatternSpec() ,public final Set<java.lang.String> getNonCacheablePatterns() ,public final java.lang.String getPrefix() ,public final org.thymeleaf.util.PatternSpec getRawTemplateModePatternSpec() ,public final Set<java.lang.String> getRawTemplateModePatterns() ,public final java.lang.String getSuffix() ,public final Map<java.lang.String,java.lang.String> getTemplateAliases() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() ,public final org.thymeleaf.util.PatternSpec getTextTemplateModePatternSpec() ,public final Set<java.lang.String> getTextTemplateModePatterns() ,public final org.thymeleaf.util.PatternSpec getXmlTemplateModePatternSpec() ,public final Set<java.lang.String> getXmlTemplateModePatterns() ,public final boolean isCacheable() ,public final void setCSSTemplateModePatterns(Set<java.lang.String>) ,public final void setCacheTTLMs(java.lang.Long) ,public final void setCacheable(boolean) ,public final void setCacheablePatterns(Set<java.lang.String>) ,public final void setCharacterEncoding(java.lang.String) ,public final void setForceSuffix(boolean) ,public final void setForceTemplateMode(boolean) ,public final void setHtmlTemplateModePatterns(Set<java.lang.String>) ,public final void setJavaScriptTemplateModePatterns(Set<java.lang.String>) ,public final void setNonCacheablePatterns(Set<java.lang.String>) ,public final void setPrefix(java.lang.String) ,public final void setRawTemplateModePatterns(Set<java.lang.String>) ,public final void setSuffix(java.lang.String) ,public final void setTemplateAliases(Map<java.lang.String,java.lang.String>) ,public final void setTemplateMode(org.thymeleaf.templatemode.TemplateMode) ,public final void setTemplateMode(java.lang.String) ,public final void setTextTemplateModePatterns(Set<java.lang.String>) ,public final void setXmlTemplateModePatterns(Set<java.lang.String>) <variables>public static final boolean DEFAULT_CACHEABLE,public static final java.lang.Long DEFAULT_CACHE_TTL_MS,public static final org.thymeleaf.templatemode.TemplateMode DEFAULT_TEMPLATE_MODE,private java.lang.Long cacheTTLMs,private boolean cacheable,private final org.thymeleaf.util.PatternSpec cacheablePatternSpec,private java.lang.String characterEncoding,private final org.thymeleaf.util.PatternSpec cssTemplateModePatternSpec,private boolean forceSuffix,private boolean forceTemplateMode,private final org.thymeleaf.util.PatternSpec htmlTemplateModePatternSpec,private final org.thymeleaf.util.PatternSpec javaScriptTemplateModePatternSpec,private final org.thymeleaf.util.PatternSpec nonCacheablePatternSpec,private java.lang.String prefix,private final org.thymeleaf.util.PatternSpec rawTemplateModePatternSpec,private java.lang.String suffix,private final HashMap<java.lang.String,java.lang.String> templateAliases,private org.thymeleaf.templatemode.TemplateMode templateMode,private final org.thymeleaf.util.PatternSpec textTemplateModePatternSpec,private final org.thymeleaf.util.PatternSpec xmlTemplateModePatternSpec
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresource/ClassLoaderTemplateResource.java
ClassLoaderTemplateResource
exists
class ClassLoaderTemplateResource implements ITemplateResource { private final ClassLoader optionalClassLoader; private final String path; private final String characterEncoding; /** * <p> * Create a ClassLoader-based template resource, without specifying the specific class loader * to be used for resolving the resource. * </p> * <p> * If created this way, the sequence explained in * {@link org.thymeleaf.util.ClassLoaderUtils#loadResourceAsStream(String)} will be used for resolving * the resource. * </p> * * @param path the path to the template resource. * @param characterEncoding the character encoding to be used to read the resource. * * @since 3.0.3 */ public ClassLoaderTemplateResource(final String path, final String characterEncoding) { this(null, path, characterEncoding); } /** * <p> * Create a ClassLoader-based template resource, specifying the specific class loader * to be used for resolving the resource. * </p> * * @param classLoader the class loader to be used for resource resolution. * @param path the path to the template resource. * @param characterEncoding the character encoding to be used to read the resource. * * @since 3.0.3 */ public ClassLoaderTemplateResource(final ClassLoader classLoader, final String path, final String characterEncoding) { super(); // Class Loader CAN be null (will apply the default sequence of class loaders Validate.notEmpty(path, "Resource Path cannot be null or empty"); // Character encoding CAN be null (system default will be used) this.optionalClassLoader = classLoader; final String cleanPath = TemplateResourceUtils.cleanPath(path); this.path = (cleanPath.charAt(0) == '/' ? cleanPath.substring(1) : cleanPath); this.characterEncoding = characterEncoding; } public String getDescription() { return this.path; } public String getBaseName() { return TemplateResourceUtils.computeBaseName(this.path); } public Reader reader() throws IOException { final InputStream inputStream; if (this.optionalClassLoader != null) { inputStream = this.optionalClassLoader.getResourceAsStream(this.path); } else { inputStream = ClassLoaderUtils.findResourceAsStream(this.path); } if (inputStream == null) { throw new FileNotFoundException(String.format("ClassLoader resource \"%s\" could not be resolved", this.path)); } if (!StringUtils.isEmptyOrWhitespace(this.characterEncoding)) { return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream), this.characterEncoding)); } return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream))); } public ITemplateResource relative(final String relativeLocation) { Validate.notEmpty(relativeLocation, "Relative Path cannot be null or empty"); final String fullRelativeLocation = TemplateResourceUtils.computeRelativeLocation(this.path, relativeLocation); return new ClassLoaderTemplateResource(this.optionalClassLoader, fullRelativeLocation, this.characterEncoding); } public boolean exists() {<FILL_FUNCTION_BODY>} }
if (this.optionalClassLoader != null) { return (this.optionalClassLoader.getResource(this.path) != null); } return ClassLoaderUtils.isResourcePresent(this.path);
885
56
941
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresource/FileTemplateResource.java
FileTemplateResource
relative
class FileTemplateResource implements ITemplateResource, Serializable { private final String path; private final File file; private final String characterEncoding; public FileTemplateResource(final String path, final String characterEncoding) { super(); Validate.notEmpty(path, "Resource Path cannot be null or empty"); // Character encoding CAN be null (system default will be used) this.path = TemplateResourceUtils.cleanPath(path); this.file = new File(path); this.characterEncoding = characterEncoding; } public FileTemplateResource(final File file, final String characterEncoding) { super(); Validate.notNull(file, "Resource File cannot be null"); // Character encoding CAN be null (system default will be used) this.path = TemplateResourceUtils.cleanPath(file.getPath()); this.file = file; this.characterEncoding = characterEncoding; } public String getDescription() { return this.file.getAbsolutePath(); } public String getBaseName() { return TemplateResourceUtils.computeBaseName(this.path); } public Reader reader() throws IOException { final InputStream inputStream = new FileInputStream(this.file); if (!StringUtils.isEmptyOrWhitespace(this.characterEncoding)) { return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream), this.characterEncoding)); } return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream))); } public ITemplateResource relative(final String relativeLocation) {<FILL_FUNCTION_BODY>} public boolean exists() { return this.file.exists(); } }
Validate.notEmpty(relativeLocation, "Relative Path cannot be null or empty"); final String fullRelativeLocation = TemplateResourceUtils.computeRelativeLocation(this.path, relativeLocation); return new FileTemplateResource(fullRelativeLocation, this.characterEncoding);
457
70
527
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresource/TemplateResourceUtils.java
TemplateResourceUtils
cleanPath
class TemplateResourceUtils { static String cleanPath(final String path) {<FILL_FUNCTION_BODY>} static String computeRelativeLocation(final String location, final String relativeLocation) { final int separatorPos = location.lastIndexOf('/'); if (separatorPos != -1) { final StringBuilder relativeBuilder = new StringBuilder(location.length() + relativeLocation.length()); relativeBuilder.append(location, 0, separatorPos); if (relativeLocation.charAt(0) != '/') { relativeBuilder.append('/'); } relativeBuilder.append(relativeLocation); return relativeBuilder.toString(); } return relativeLocation; } static String computeBaseName(final String path) { if (path == null || path.length() == 0) { return null; } // First remove a trailing '/' if it exists final String basePath = (path.charAt(path.length() - 1) == '/'? path.substring(0,path.length() - 1) : path); final int slashPos = basePath.lastIndexOf('/'); if (slashPos != -1) { final int dotPos = basePath.lastIndexOf('.'); if (dotPos != -1 && dotPos > slashPos + 1) { return basePath.substring(slashPos + 1, dotPos); } return basePath.substring(slashPos + 1); } else { final int dotPos = basePath.lastIndexOf('.'); if (dotPos != -1) { return basePath.substring(0, dotPos); } } return (basePath.length() > 0? basePath : null); } private TemplateResourceUtils() { super(); } }
if (path == null) { return null; } // First replace Windows folder separators with UNIX's String unixPath = StringUtils.replace(path, "\\", "/"); // Some shortcuts, just in case this is empty or simply has no '.' or '..' (and no double-/ we should simplify) if (unixPath.length() == 0 || (unixPath.indexOf("/.") < 0 && unixPath.indexOf("//") < 0)) { return unixPath; } // We make sure path starts with '/' in order to simplify the algorithm boolean rootBased = (unixPath.charAt(0) == '/'); unixPath = (rootBased? unixPath : ('/' + unixPath)); // We will traverse path in reverse order, looking for '.' and '..' tokens and processing them final StringBuilder strBuilder = new StringBuilder(unixPath.length()); int index = unixPath.lastIndexOf('/'); int pos = unixPath.length() - 1; int topCount = 0; while (index >= 0) { // will always be 0 for the last iteration, as we prefixed the path with '/' final int tokenLen = pos - index; if (tokenLen > 0) { if (tokenLen == 1 && unixPath.charAt(index + 1) == '.') { // Token is '.' -> just ignore it } else if (tokenLen == 2 && unixPath.charAt(index + 1) == '.' && unixPath.charAt(index + 2) == '.') { // Token is '..' -> count as a 'top' operation topCount++; } else if (topCount > 0){ // Whatever comes here has been removed by a 'top' operation, so ignore topCount--; } else { // Token is OK, just add (with its corresponding '/') strBuilder.insert(0, unixPath, index, (index + tokenLen + 1)); } } pos = index - 1; index = (pos >= 0? unixPath.lastIndexOf('/', pos) : -1); } // Add all 'top' tokens appeared at the very beginning of the path for (int i = 0; i < topCount; i++) { strBuilder.insert(0, "/.."); } // Perform last cleanup if (!rootBased) { strBuilder.deleteCharAt(0); } return strBuilder.toString();
475
645
1,120
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresource/UrlTemplateResource.java
UrlTemplateResource
inputStream
class UrlTemplateResource implements ITemplateResource, Serializable { private final URL url; private final String characterEncoding; public UrlTemplateResource(final String path, final String characterEncoding) throws MalformedURLException { super(); Validate.notEmpty(path, "Resource Path cannot be null or empty"); // Character encoding CAN be null (system default will be used) this.url = new URL(path); this.characterEncoding = characterEncoding; } public UrlTemplateResource(final URL url, final String characterEncoding) { super(); Validate.notNull(url, "Resource URL cannot be null"); // Character encoding CAN be null (system default will be used) this.url = url; this.characterEncoding = characterEncoding; } public String getDescription() { return this.url.toString(); } public String getBaseName() { return TemplateResourceUtils.computeBaseName(TemplateResourceUtils.cleanPath(this.url.getPath())); } public Reader reader() throws IOException { final InputStream inputStream = inputStream(); if (!StringUtils.isEmptyOrWhitespace(this.characterEncoding)) { return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream), this.characterEncoding)); } return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream))); } private InputStream inputStream() throws IOException {<FILL_FUNCTION_BODY>} public ITemplateResource relative(final String relativeLocation) { Validate.notEmpty(relativeLocation, "Relative Path cannot be null or empty"); // We will create a new URL using the current one as context, and the relative path as spec final URL relativeURL; try { relativeURL = new URL(this.url, (relativeLocation.charAt(0) == '/' ? relativeLocation.substring(1) : relativeLocation)); } catch (final MalformedURLException e) { throw new TemplateInputException( "Could not create relative URL resource for resource \"" + getDescription() + "\" and " + "relative location \"" + relativeLocation + "\"", e); } return new UrlTemplateResource(relativeURL, this.characterEncoding); } public boolean exists() { try { final String protocol = this.url.getProtocol(); if ("file".equals(protocol)) { // This is a file system resource, so we will treat it as a file File file = null; try { file = new File(toURI(this.url).getSchemeSpecificPart()); } catch (final URISyntaxException ignored) { // The URL was not a valid URI (not even after conversion) file = new File(this.url.getFile()); } return file.exists(); } // Not a 'file' URL, so we need to try other less local methods (HTTP/generic connection) final URLConnection connection = this.url.openConnection(); if (connection.getClass().getSimpleName().startsWith("JNLP")) { connection.setUseCaches(true); } if (connection instanceof HttpURLConnection) { final HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod("HEAD"); // We don't want the document, just know if it exists int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return true; } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { return false; } if (httpConnection.getContentLength() >= 0) { // No status, but at least some content length info! return true; } // At this point, there not much hope, so better even get rid of the socket httpConnection.disconnect(); return false; } // Not an HTTP URL Connection, so let's try direclty obtaining content length info if (connection.getContentLength() >= 0) { return true; } // Last attempt: open (and then immediately close) the input stream (will raise IOException if not possible) final InputStream is = inputStream(); is.close(); return true; } catch (final IOException ignored) { return false; } } private static URI toURI(final URL url) throws URISyntaxException { String location = url.toString(); if (location.indexOf(' ') == -1) { // No need to replace anything return new URI(location); } return new URI(StringUtils.replace(location, " ", "%20")); } }
final URLConnection connection = this.url.openConnection(); if (connection.getClass().getSimpleName().startsWith("JNLP")) { connection.setUseCaches(true); } final InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (final IOException e) { if (connection instanceof HttpURLConnection) { // disconnect() will probably close the underlying socket, which is fine given we had an exception ((HttpURLConnection) connection).disconnect(); } throw e; } return inputStream;
1,225
149
1,374
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/templateresource/WebApplicationTemplateResource.java
WebApplicationTemplateResource
reader
class WebApplicationTemplateResource implements ITemplateResource { private final IWebApplication webApplication; private final String path; private final String characterEncoding; public WebApplicationTemplateResource(final IWebApplication webApplication, final String path, final String characterEncoding) { super(); Validate.notNull(webApplication, "Web Application object cannot be null"); Validate.notEmpty(path, "Resource Path cannot be null or empty"); // Character encoding CAN be null (system default will be used) this.webApplication = webApplication; final String cleanPath = TemplateResourceUtils.cleanPath(path); this.path = (cleanPath.charAt(0) != '/' ? ("/" + cleanPath) : cleanPath); this.characterEncoding = characterEncoding; } public String getDescription() { return this.path; } public String getBaseName() { return TemplateResourceUtils.computeBaseName(this.path); } public Reader reader() throws IOException {<FILL_FUNCTION_BODY>} public ITemplateResource relative(final String relativeLocation) { Validate.notEmpty(relativeLocation, "Relative Path cannot be null or empty"); final String fullRelativeLocation = TemplateResourceUtils.computeRelativeLocation(this.path, relativeLocation); return new WebApplicationTemplateResource(this.webApplication, fullRelativeLocation, this.characterEncoding); } public boolean exists() { return this.webApplication.resourceExists(this.path); } }
final InputStream inputStream = this.webApplication.getResourceAsStream(this.path); if (inputStream == null) { throw new FileNotFoundException(String.format("Web Application resource \"%s\" does not exist", this.path)); } if (!StringUtils.isEmptyOrWhitespace(this.characterEncoding)) { return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream), this.characterEncoding)); } return new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream)));
402
138
540
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/AbstractLazyCharSequence.java
AbstractLazyCharSequence
write
class AbstractLazyCharSequence implements IWritableCharSequence { private String resolvedText = null; protected AbstractLazyCharSequence() { super(); } protected abstract String resolveText(); private String getText() { if (this.resolvedText == null) { this.resolvedText = resolveText(); } return this.resolvedText; } public final int length() { return getText().length(); } public final char charAt(final int index) { return getText().charAt(index); } public final CharSequence subSequence(final int beginIndex, final int endIndex) { return getText().subSequence(beginIndex, endIndex); } public final void write(final Writer writer) throws IOException {<FILL_FUNCTION_BODY>} protected abstract void writeUnresolved(final Writer writer) throws IOException; @Override public final boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final AbstractLazyCharSequence that = (AbstractLazyCharSequence) o; return this.getText().equals(that.getText()); } public final int hashCode() { return getText().hashCode(); } @Override public final String toString() { return getText(); } }
if (writer == null) { throw new IllegalArgumentException("Writer cannot be null"); } if (this.resolvedText != null) { writer.write(this.resolvedText); } else { writeUnresolved(writer); }
408
67
475
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/ArrayUtils.java
ArrayUtils
containsAll
class ArrayUtils { public static Object[] toArray(final Object target) { return toArray(null, target); } public static Object[] toStringArray(final Object target) { return toArray(String.class, target); } public static Object[] toIntegerArray(final Object target) { return toArray(Integer.class, target); } public static Object[] toLongArray(final Object target) { return toArray(Long.class, target); } public static Object[] toDoubleArray(final Object target) { return toArray(Double.class, target); } public static Object[] toFloatArray(final Object target) { return toArray(Float.class, target); } public static Object[] toBooleanArray(final Object target) { return toArray(Boolean.class, target); } public static int length(final Object[] target) { Validate.notNull(target, "Cannot get array length of null"); return target.length; } public static boolean isEmpty(final Object[] target) { return target == null || target.length <= 0; } public static boolean contains(final Object[] target, final Object element) { Validate.notNull(target, "Cannot execute array contains: target is null"); if (element == null) { for (final Object targetElement : target) { if (targetElement == null) { return true; } } return false; } for (final Object targetElement : target) { if (element.equals(targetElement)) { return true; } } return false; } public static boolean containsAll(final Object[] target, final Object[] elements) { Validate.notNull(target, "Cannot execute array containsAll: target is null"); Validate.notNull(elements, "Cannot execute array containsAll: elements is null"); return containsAll(target, Arrays.asList(elements)); } public static boolean containsAll(final Object[] target, final Collection<?> elements) {<FILL_FUNCTION_BODY>} private static Object[] toArray(final Class<?> componentClass, final Object target) { Validate.notNull(target, "Cannot convert null to array"); if (target.getClass().isArray()) { if (componentClass == null) { return (Object[]) target; } final Class<?> targetComponentClass = target.getClass().getComponentType(); if (componentClass.isAssignableFrom(targetComponentClass)) { return (Object[]) target; } throw new IllegalArgumentException( "Cannot convert object of class \"" + targetComponentClass.getName() + "[]\" to an array" + " of " + componentClass.getClass().getSimpleName()); } if (target instanceof Iterable<?>) { Class<?> computedComponentClass = null; final Iterable<?> iterableTarget = (Iterable<?>)target; final List<Object> elements = new ArrayList<Object>(5); // init capacity guessed - not know from iterable. for (final Object element : iterableTarget) { if (componentClass == null && element != null) { if (computedComponentClass == null) { computedComponentClass = element.getClass(); } else if (!computedComponentClass.equals(Object.class)) { if (!computedComponentClass.equals(element.getClass())) { computedComponentClass = Object.class; } } } elements.add(element); } if (computedComponentClass == null) { computedComponentClass = (componentClass != null? componentClass : Object.class); } final Object[] result = (Object[]) Array.newInstance(computedComponentClass, elements.size()); return elements.toArray(result); } throw new IllegalArgumentException( "Cannot convert object of class \"" + target.getClass().getName() + "\" to an array" + (componentClass == null? "" : (" of " + componentClass.getClass().getSimpleName()))); } @SuppressWarnings("unchecked") public static <T,X> X[] copyOf(final T[] original, final int newLength, final Class<? extends X[]> newType) { final X[] newArray = (newType == (Object)Object[].class)? (X[]) new Object[newLength] : (X[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, newArray, 0, Math.min(original.length, newLength)); return newArray; } @SuppressWarnings("unchecked") public static <T> T[] copyOf(final T[] original, final int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } public static char[] copyOf(final char[] original, final int newLength) { final char[] copy = new char[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } public static char[] copyOfRange(final char[] original, final int from, final int to) { final int newLength = (to - from); if (newLength < 0) { throw new IllegalArgumentException("Cannot copy array range with indexes " + from + " and " + to); } final char[] copy = new char[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } private ArrayUtils() { super(); } }
Validate.notNull(target, "Cannot execute array contains: target is null"); Validate.notNull(elements, "Cannot execute array containsAll: elements is null"); final Set<?> remainingElements = new HashSet<Object>(elements); remainingElements.removeAll(Arrays.asList(target)); return remainingElements.isEmpty();
1,539
87
1,626
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/CharArrayWrapperSequence.java
CharArrayWrapperSequence
hashCode
class CharArrayWrapperSequence implements CharSequence, Cloneable { private final char[] buffer; private final int offset; private final int len; public CharArrayWrapperSequence(final char[] array) { this(array, 0, (array != null? array.length : -1)); } public CharArrayWrapperSequence(final char[] buffer, final int offset, final int len) { super(); if (buffer == null) { throw new IllegalArgumentException("Buffer cannot be null"); } if (offset < 0 || offset >= buffer.length) { throw new IllegalArgumentException(offset + " is not a valid offset for buffer (size: " + buffer.length + ")"); } if ((offset + len) > buffer.length) { throw new IllegalArgumentException(len + " is not a valid length for buffer using offset " + offset + " (size: " + buffer.length + ")"); } this.buffer = buffer; this.offset = offset; this.len = len; } public char charAt(final int index) { if (index < 0 || index >= this.len) { throw new ArrayIndexOutOfBoundsException(index); } return this.buffer[index + this.offset]; } public int length() { return this.len; } public CharSequence subSequence(final int start, final int end) { if (start < 0 || start >= this.len) { throw new ArrayIndexOutOfBoundsException(start); } if (end > this.len) { throw new ArrayIndexOutOfBoundsException(end); } return new CharArrayWrapperSequence(this.buffer, (this.offset + start), (end - start)); } @Override protected CharArrayWrapperSequence clone() throws CloneNotSupportedException { return (CharArrayWrapperSequence) super.clone(); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public boolean equals(final Object obj) { /* * This implementation works in the same way as java.lang.String#equals(obj), * but is not compatible because java.lang.String#equals(obj) requires obj * to be an instance of String. */ if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof CharArrayWrapperSequence) { final CharArrayWrapperSequence other = (CharArrayWrapperSequence) obj; if (this.len != other.len) { return false; } for (int i = 0; i < this.len; i++) { if (this.buffer[i + this.offset] != other.buffer[i + other.offset]) { return false; } } return true; } return false; } @Override public String toString() { return new String(this.buffer, this.offset, this.len); } }
/* * This implementation is compatible with java.lang.String#hashCode(), * even if equals(obj) cannot be because java.lang.String requires * the obj to be an instance of String. */ if (this.len == 0) { return 0; } final int prime = 31; int result = 0; final int maxi = this.offset + this.len; for (int i = this.offset; i < maxi; i++) { result = prime * result + (int) this.buffer[i]; } return result;
814
152
966
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/EscapedAttributeUtils.java
EscapedAttributeUtils
escapeAttribute
class EscapedAttributeUtils { public static String escapeAttribute(final TemplateMode templateMode, final String input) {<FILL_FUNCTION_BODY>} public static String unescapeAttribute(final TemplateMode templateMode, final String input) { if (input == null) { return null; } Validate.notNull(templateMode, "Template mode cannot be null"); /* * Depending on the template mode that we are using, we might be receiving element attributes escaped in * different ways. * * HTML, XML, JAVASCRIPT and CSS have their own escaping/unescaping rules, which we can easily apply by means * of the corresponding Unbescape utility methods. * * There is no standard way to escape/unescape in TEXT modes, but given TEXT mode is many times used for * markup (HTML or XML templates or inlined fragments), we will use HTML escaping/unescaping for TEXT mode. * Besides, this is consistent with the fact that TEXT-mode escaped output will also be HTML-escaped by * processors and inlining utilities in the Standard Dialects. */ switch (templateMode) { case TEXT: // fall-through case HTML: return HtmlEscape.unescapeHtml(input); case XML: return XmlEscape.unescapeXml(input); case JAVASCRIPT: return JavaScriptEscape.unescapeJavaScript(input); case CSS: return CssEscape.unescapeCss(input); case RAW: return input; default: throw new TemplateProcessingException( "Unrecognized template mode " + templateMode + ". Cannot unescape attribute value for " + "this template mode."); } } private EscapedAttributeUtils() { super(); } }
if (input == null) { return null; } Validate.notNull(templateMode, "Template mode cannot be null"); /* * Depending on the template mode that we are using, we might be receiving element attributes escaped in * different ways. * * HTML and XML have their own escaping/unescaping rules, which we can easily apply by means * of the corresponding Unbescape utility methods. TEXT, JAVASCRIPT and CSS are left out because there are no * attributes to be output in those modes as such. * * There is no standard way to escape/unescape in TEXT modes, but given TEXT mode is many times used for * markup (HTML or XML templates or inlined fragments), we will use HTML escaping/unescaping for TEXT mode. * Besides, this is consistent with the fact that TEXT-mode escaped output will also be HTML-escaped by * processors and inlining utilities in the Standard Dialects. */ switch (templateMode) { case HTML: return HtmlEscape.escapeHtml4Xml(input); case XML: return XmlEscape.escapeXml10Attribute(input); default: throw new TemplateProcessingException( "Unrecognized template mode " + templateMode + ". Cannot produce escaped attributes for " + "this template mode."); }
477
344
821
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/FastStringWriter.java
FastStringWriter
write
class FastStringWriter extends Writer { private final StringBuilder builder; public FastStringWriter() { super(); this.builder = new StringBuilder(); } public FastStringWriter(final int initialSize) { super(); if (initialSize < 0) { throw new IllegalArgumentException("Negative buffer size"); } this.builder = new StringBuilder(initialSize); } @Override public void write(final int c) { this.builder.append((char) c); } @Override public void write(final String str) { this.builder.append(str); } @Override public void write(final String str, final int off, final int len) { this.builder.append(str, off, off + len); } @Override public void write(final char[] cbuf) { this.builder.append(cbuf, 0, cbuf.length); } @Override public void write(final char[] cbuf, final int off, final int len) {<FILL_FUNCTION_BODY>} @Override public void flush() throws IOException { // Nothing to be flushed } @Override public void close() throws IOException { // Nothing to be closed } @Override public String toString() { return this.builder.toString(); } }
if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } this.builder.append(cbuf, off, len);
376
93
469
<methods>public java.io.Writer append(java.lang.CharSequence) throws java.io.IOException,public java.io.Writer append(char) throws java.io.IOException,public java.io.Writer append(java.lang.CharSequence, int, int) throws java.io.IOException,public abstract void close() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public static java.io.Writer nullWriter() ,public void write(int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public abstract void write(char[], int, int) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException<variables>private static final int WRITE_BUFFER_SIZE,protected java.lang.Object lock,private char[] writeBuffer