index
int64
0
36.5k
proj_name
stringclasses
162 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
51
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_func_body
int64
1
5.26k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
35,397
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()); } }
223
154
185
339
35,398
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)); }
210
1,800
206
2,006
35,399
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(); }
50
308
43
351
35,400
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); }
198
492
224
716
35,401
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);
569
839
382
1,221
35,403
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); } } } } }
1,484
611
977
1,588
35,404
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.
24
508
22
530
35,405
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);
53
361
74
435
35,406
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();
35
167
41
208
35,407
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;
581
198
617
815
35,408
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); }
221
364
202
566
35,409
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());
572
117
482
599
35,410
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);
70
503
94
597
35,411
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)); }
204
1,481
195
1,676
35,412
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); }
1,513
532
997
1,529
35,413
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);
331
171
352
523
35,414
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);
46
159
55
214
35,415
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);
66
155
78
233
35,416
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);
251
200
204
404
35,417
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!"); }
430
192
291
483
35,418
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 + "\""); }
374
146
247
393
35,419
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 + "\"");
427
176
263
439
35,420
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 + "\""); }
277
148
167
315
35,421
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); }
102
135
110
245
35,422
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); }
102
118
106
224
35,423
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); }
219
118
203
321
35,424
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).
49
177
48
225
35,425
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."); } }
290
300
249
549
35,426
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); }
221
363
202
565
35,427
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));
55
337
80
417
35,428
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);
706
400
545
945
35,430
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);
51
157
77
234
35,431
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);
1,183
370
993
1,363
35,432
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); } }
706
171
562
733
35,433
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
26
187
29
216
35,434
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); }
93
400
56
456
35,436
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;
263
638
205
843
35,437
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);
853
553
801
1,354
35,438
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;
1,173
274
722
996
35,439
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); }
66
204
75
279
35,441
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); }
96
1,405
69
1,474
35,442
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);
146
1,241
176
1,417
35,443
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);
36
754
30
784
35,444
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);
97
421
140
561
35,446
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);
48
1,209
52
1,261
35,447
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();
502
155
506
661
35,448
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);
97
320
84
404
35,449
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;
215
748
163
911
35,450
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 } }
883
1,063
601
1,664
35,451
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);
119
920
161
1,081
35,453
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);
148
937
78
1,015
35,454
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
24
820
20
840
35,455
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); }
960
775
621
1,396
35,457
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);
181
445
129
574
35,458
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); }
95
1,265
61
1,326
35,459
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]++;
71
66
48
114
35,460
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;
215
748
163
911
35,463
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] == '/');
58
405
37
442
35,465
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;
263
146
202
348
35,469
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);
93
783
102
885
35,470
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);
93
1,471
102
1,573
35,471
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);
104
232
104
336
35,472
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);
49
885
56
941
35,473
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);
44
457
70
527
35,474
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();
782
475
645
1,120
35,475
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;
199
1,225
149
1,374
35,476
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)));
105
402
138
540
35,477
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); }
96
408
67
475
35,480
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();
65
1,539
87
1,626
35,481
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;
194
814
152
966
35,485
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."); }
458
477
344
821
35,488
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);
110
376
93
469
35,489
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LazyEscapingCharSequence.java
LazyEscapingCharSequence
produceEscapedOutput
class LazyEscapingCharSequence extends AbstractLazyCharSequence { private final IEngineConfiguration configuration; private final TemplateMode templateMode; private final Object input; public LazyEscapingCharSequence(final IEngineConfiguration configuration, final TemplateMode templateMode, final Object input) { super(); if (configuration == null) { throw new IllegalArgumentException("Engine Configuraion is null, which is forbidden"); } if (templateMode == null) { throw new IllegalArgumentException("Template Mode is null, which is forbidden"); } this.configuration = configuration; this.templateMode = templateMode; this.input = input; } @Override protected String resolveText() { final Writer stringWriter = new FastStringWriter(); produceEscapedOutput(stringWriter); return stringWriter.toString(); } @Override protected void writeUnresolved(final Writer writer) throws IOException { produceEscapedOutput(writer); } private void produceEscapedOutput(final Writer writer) {<FILL_FUNCTION_BODY>} }
/* * Producing ESCAPED output is somewhat simple in HTML or XML modes, as it simply consists of converting * input into a String and HTML-or-XML-escaping it. * * But for JavaScript or CSS, it becomes a bit more complicated than that. JavaScript will output a complete * literal (incl. single quotes) if input is a String or a non-recognized value type, but will print input * as an object, number, boolean, etc. if it is recognized to be of one of these types. CSS will output * quoted literals. * * Note that, when in TEXT mode, HTML escaping will be used (as TEXT is many times used for * processing HTML templates) */ try { switch (templateMode) { case TEXT: // fall-through case HTML: if (this.input != null) { HtmlEscape.escapeHtml4Xml(this.input.toString(), writer); } return; case XML: if (this.input != null) { // 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) XmlEscape.escapeXml10(this.input.toString(), writer); } return; case JAVASCRIPT: final IStandardJavaScriptSerializer javaScriptSerializer = StandardSerializers.getJavaScriptSerializer(this.configuration); javaScriptSerializer.serializeValue(this.input, writer); return; case CSS: final IStandardCSSSerializer cssSerializer = StandardSerializers.getCSSSerializer(this.configuration); cssSerializer.serializeValue(this.input, writer); return; case RAW: if (this.input != null) { writer.write(this.input.toString()); } return; default: throw new TemplateProcessingException( "Unrecognized template mode " + templateMode + ". Cannot produce escaped output for " + "this template mode."); } } catch (final IOException e) { throw new TemplateProcessingException("An error happened while trying to produce escaped output", e); }
998
288
552
840
35,490
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LazyProcessingCharSequence.java
LazyProcessingCharSequence
resolveText
class LazyProcessingCharSequence extends AbstractLazyCharSequence { private final ITemplateContext context; private final TemplateModel templateModel; public LazyProcessingCharSequence(final ITemplateContext context, final TemplateModel templateModel) { super(); if (context == null) { throw new IllegalArgumentException("Template Context is null, which is forbidden"); } if (templateModel == null) { throw new IllegalArgumentException("Template Model is null, which is forbidden"); } this.context = context; this.templateModel = templateModel; } @Override protected String resolveText() {<FILL_FUNCTION_BODY>} @Override protected void writeUnresolved(final Writer writer) throws IOException { this.context.getConfiguration().getTemplateManager().process(this.templateModel, this.context, writer); } }
final Writer stringWriter = new FastStringWriter(); this.context.getConfiguration().getTemplateManager().process(this.templateModel, this.context, stringWriter); return stringWriter.toString();
37
231
51
282
35,491
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/ListUtils.java
ListUtils
sort
class ListUtils { public static List<?> toList(final Object target) { Validate.notNull(target, "Cannot convert null to list"); if (target instanceof List<?>) { return (List<?>) target; } if (target.getClass().isArray()) { return new ArrayList<Object>(Arrays.asList((Object[])target)); } if (target instanceof Iterable<?>) { final List<Object> elements = new ArrayList<Object>(10); for (final Object element : (Iterable<?>)target) { elements.add(element); } return elements; } throw new IllegalArgumentException( "Cannot convert object of class \"" + target.getClass().getName() + "\" to a list"); } public static int size(final List<?> target) { Validate.notNull(target, "Cannot get list size of null"); return target.size(); } public static boolean isEmpty(final List<?> target) { return target == null || target.isEmpty(); } public static boolean contains(final List<?> target, final Object element) { Validate.notNull(target, "Cannot execute list contains: target is null"); return target.contains(element); } public static boolean containsAll(final List<?> target, final Object[] elements) { Validate.notNull(target, "Cannot execute list containsAll: target is null"); Validate.notNull(elements, "Cannot execute list containsAll: elements is null"); return containsAll(target, Arrays.asList(elements)); } public static boolean containsAll(final List<?> target, final Collection<?> elements) { Validate.notNull(target, "Cannot execute list contains: target is null"); Validate.notNull(elements, "Cannot execute list containsAll: elements is null"); return target.containsAll(elements); } /** * <p> * Creates an new instance of the list add the sorted list to it. * </p> * * @param list the list which content should be ordered. * @param <T> the type of the list elements. * @return a new sorted list. * @see java.util.Collections#sort(List) */ public static <T extends Comparable<? super T>> List<T> sort(final List<T> list) { Validate.notNull(list, "Cannot execute list sort: list is null"); final Object[] a = list.toArray(); Arrays.sort(a); return fillNewList(a, list.getClass()); } /** * <p> * Creates an new instance of the list add the sorted list to it. * </p> * * @param list the list which content should be ordered. * @param c the comparator. * @param <T> the type of the list elements. * @return a new sorted list. * @see java.util.Collections#sort(List, Comparator) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> List<T> sort(final List<T> list, final Comparator<? super T> c) {<FILL_FUNCTION_BODY>} @SuppressWarnings({ "rawtypes", "unchecked" }) private static <T> List<T> fillNewList( final Object[] a, final Class<? extends List> listType) { List<T> newList; try { newList = listType.getConstructor().newInstance(); } catch (final Exception e) { newList = new ArrayList<T>(a.length + 2); } for (final Object object : a) { newList.add((T)object); } return newList; } private ListUtils() { super(); } }
Validate.notNull(list, "Cannot execute list sort: list is null"); final Object[] a = list.toArray(); Arrays.sort(a, (Comparator) c); return fillNewList(a, list.getClass());
60
1,054
67
1,121
35,492
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/LoggingUtils.java
LoggingUtils
loggifyTemplateName
class LoggingUtils { public static String loggifyTemplateName(final String template) {<FILL_FUNCTION_BODY>} private LoggingUtils() { super(); } }
if (template == null) { return null; } if (template.length() <= 120) { return template.replace('\n', ' '); } final StringBuilder strBuilder = new StringBuilder(); strBuilder.append(template.substring(0, 35).replace('\n', ' ')); strBuilder.append("[...]"); strBuilder.append(template.substring(template.length() - 80).replace('\n', ' ')); return strBuilder.toString();
126
64
135
199
35,493
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/MapUtils.java
MapUtils
containsAllKeys
class MapUtils { public static int size(final Map<?,?> target) { Validate.notNull(target, "Cannot get map size of null"); return target.size(); } public static boolean isEmpty(final Map<?,?> target) { return target == null || target.isEmpty(); } public static <X> boolean containsKey(final Map<? super X,?> target, final X key) { Validate.notNull(target, "Cannot execute map containsKey: target is null"); return target.containsKey(key); } public static <X> boolean containsAllKeys(final Map<? super X,?> target, final X[] keys) { Validate.notNull(target, "Cannot execute map containsAllKeys: target is null"); Validate.notNull(keys, "Cannot execute map containsAllKeys: keys is null"); return containsAllKeys(target, Arrays.asList(keys)); } public static <X> boolean containsAllKeys(final Map<? super X,?> target, final Collection<X> keys) {<FILL_FUNCTION_BODY>} public static <X> boolean containsValue(final Map<?,? super X> target, final X value) { Validate.notNull(target, "Cannot execute map containsValue: target is null"); return target.containsValue(value); } public static <X> boolean containsAllValues(final Map<?,? super X> target, final X[] values) { Validate.notNull(target, "Cannot execute map containsAllValues: target is null"); Validate.notNull(values, "Cannot execute map containsAllValues: values is null"); return containsAllValues(target, Arrays.asList(values)); } public static <X> boolean containsAllValues(final Map<?,? super X> target, final Collection<X> values) { Validate.notNull(target, "Cannot execute map containsAllValues: target is null"); Validate.notNull(values, "Cannot execute map containsAllValues: values is null"); return target.values().containsAll(values); } private MapUtils() { super(); } }
Validate.notNull(target, "Cannot execute map containsAllKeys: target is null"); Validate.notNull(keys, "Cannot execute map containsAllKeys: keys is null"); return target.keySet().containsAll(keys);
45
569
61
630
35,495
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/PatternSpec.java
PatternSpec
matches
class PatternSpec { private static final int DEFAULT_PATTERN_SET_SIZE = 3; private LinkedHashSet<String> patternStrs; private LinkedHashSet<Pattern> patterns; public PatternSpec() { super(); } public boolean isEmpty() { return this.patterns == null || this.patterns.size() == 0; } public Set<String> getPatterns() { if (this.patternStrs == null) { return Collections.EMPTY_SET; } return Collections.unmodifiableSet(this.patternStrs); } public void setPatterns(final Set<String> newPatterns) { if (newPatterns != null) { if (this.patterns == null) { this.patternStrs = new LinkedHashSet<String>(DEFAULT_PATTERN_SET_SIZE); this.patterns = new LinkedHashSet<Pattern>(DEFAULT_PATTERN_SET_SIZE); } else { this.patternStrs.clear(); this.patterns.clear(); } this.patternStrs.addAll(newPatterns); for (final String pattern : newPatterns) { this.patterns.add(PatternUtils.strPatternToPattern(pattern)); } } else if (this.patterns != null) { this.patternStrs.clear(); this.patterns.clear(); } } public void addPattern(final String pattern) { Validate.notEmpty(pattern, "Pattern cannot be null or empty"); if (this.patterns == null) { this.patternStrs = new LinkedHashSet<String>(DEFAULT_PATTERN_SET_SIZE); this.patterns = new LinkedHashSet<Pattern>(DEFAULT_PATTERN_SET_SIZE); } this.patternStrs.add(pattern); this.patterns.add(PatternUtils.strPatternToPattern(pattern)); } public void clearPatterns() { if (this.patterns != null) { this.patternStrs.clear(); this.patterns.clear(); } } public boolean matches(final String templateName) {<FILL_FUNCTION_BODY>} }
if (this.patterns == null) { return false; } for (final Pattern p : this.patterns) { if (p.matcher(templateName).matches()) { return true; } } return false;
112
613
70
683
35,496
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/PatternUtils.java
PatternUtils
strPatternToPattern
class PatternUtils { public static Pattern strPatternToPattern(final String pattern) {<FILL_FUNCTION_BODY>} private PatternUtils() { super(); } }
final String pat = pattern.replace(".", "\\.").replace("(", "\\(").replace(")", "\\)"). replace("[","\\[").replace("]","\\]").replace("?","\\?").replace("$","\\$").replace("+","\\+"). replace("*","(?:.*?)"); return Pattern.compile('^' + pat + '$');
77
64
99
163
35,497
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/ProcessorComparators.java
PreProcessorPrecedenceComparator
compare
class PreProcessorPrecedenceComparator implements Comparator<IPreProcessor> { PreProcessorPrecedenceComparator() { super(); } public int compare(final IPreProcessor o1, final IPreProcessor o2) {<FILL_FUNCTION_BODY>} /* * Processors are wrapped and therefore we can apply dialect precedence */ private int compareWrapped(final ProcessorConfigurationUtils.PreProcessorWrapper o1w, final ProcessorConfigurationUtils.PreProcessorWrapper o2w) { final int dialectPrecedenceComp = compareInts(o1w.getDialect().getDialectProcessorPrecedence(), o2w.getDialect().getDialectProcessorPrecedence()); if (dialectPrecedenceComp != 0) { return dialectPrecedenceComp; } final IPreProcessor o1 = o1w.unwrap(); final IPreProcessor o2 = o2w.unwrap(); final int processorPrecedenceComp = compareInts(o1.getPrecedence(), o2.getPrecedence()); if (processorPrecedenceComp != 0) { return processorPrecedenceComp; } final int classNameComp = o1.getClass().getName().compareTo(o2.getClass().getName()); if (classNameComp != 0) { return classNameComp; } return compareInts(System.identityHashCode(o1), System.identityHashCode(o2)); // Cannot be 0 } private static int compareInts(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }
if (o1 == o2) { // This is the only case in which the comparison of two processors will return 0 return 0; } if (o1 instanceof ProcessorConfigurationUtils.PreProcessorWrapper && o2 instanceof ProcessorConfigurationUtils.PreProcessorWrapper) { return compareWrapped((ProcessorConfigurationUtils.PreProcessorWrapper)o1, (ProcessorConfigurationUtils.PreProcessorWrapper)o2); } final int preProcessorPrecedenceComp = compareInts(o1.getPrecedence(), o2.getPrecedence()); if (preProcessorPrecedenceComp != 0) { return preProcessorPrecedenceComp; } final int classNameComp = o1.getClass().getName().compareTo(o2.getClass().getName()); if (classNameComp != 0) { return classNameComp; } return compareInts(System.identityHashCode(o1), System.identityHashCode(o2)); // Cannot be 0
276
432
240
672
35,499
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/SetUtils.java
SetUtils
toSet
class SetUtils { public static Set<?> toSet(final Object target) {<FILL_FUNCTION_BODY>} public static int size(final Set<?> target) { Validate.notNull(target, "Cannot get set size of null"); return target.size(); } public static boolean isEmpty(final Set<?> target) { return target == null || target.isEmpty(); } public static boolean contains(final Set<?> target, final Object element) { Validate.notNull(target, "Cannot execute set contains: target is null"); return target.contains(element); } public static boolean containsAll(final Set<?> target, final Object[] elements) { Validate.notNull(target, "Cannot execute set containsAll: target is null"); Validate.notNull(elements, "Cannot execute set containsAll: elements is null"); return containsAll(target, Arrays.asList(elements)); } public static boolean containsAll(final Set<?> target, final Collection<?> elements) { Validate.notNull(target, "Cannot execute set contains: target is null"); Validate.notNull(elements, "Cannot execute set containsAll: elements is null"); return target.containsAll(elements); } public static <X> Set<X> singletonSet(final X element) { final Set<X> set = new HashSet<X>(2, 1.0f); set.add(element); return Collections.unmodifiableSet(set); } private SetUtils() { super(); } }
Validate.notNull(target, "Cannot convert null to set"); if (target instanceof Set<?>) { return (Set<?>) target; } if (target.getClass().isArray()) { return new LinkedHashSet<Object>(Arrays.asList((Object[])target)); } if (target instanceof Iterable<?>) { final Set<Object> elements = new LinkedHashSet<Object>(); for (final Object element : (Iterable<?>)target) { elements.add(element); } return elements; } throw new IllegalArgumentException( "Cannot convert object of class \"" + target.getClass().getName() + "\" to a set");
266
438
195
633
35,502
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/Validate.java
Validate
notEmpty
class Validate { public static void notNull(final Object object, final String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static void notEmpty(final String object, final String message) { if (StringUtils.isEmptyOrWhitespace(object)) { throw new IllegalArgumentException(message); } } public static void notEmpty(final Collection<?> object, final String message) {<FILL_FUNCTION_BODY>} public static void notEmpty(final Object[] object, final String message) { if (object == null || object.length == 0) { throw new IllegalArgumentException(message); } } public static void containsNoNulls(final Iterable<?> collection, final String message) { for (final Object object : collection) { notNull(object, message); } } public static void containsNoEmpties(final Iterable<String> collection, final String message) { for (final String object : collection) { notEmpty(object, message); } } public static void containsNoNulls(final Object[] array, final String message) { for (final Object object : array) { notNull(object, message); } } public static void isTrue(final boolean condition, final String message) { if (!condition) { throw new IllegalArgumentException(message); } } private Validate() { super(); } }
if (object == null || object.size() == 0) { throw new IllegalArgumentException(message); }
43
397
31
428
35,504
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalArrayUtils.java
TemporalArrayUtils
arrayFormat
class TemporalArrayUtils { private final TemporalFormattingUtils temporalFormattingUtils; public TemporalArrayUtils(final Locale locale, final ZoneId defaultZoneId) { super(); Validate.notNull(locale, "Locale cannot be null"); Validate.notNull(defaultZoneId, "ZoneId cannot be null"); temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId); } public String[] arrayFormat(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::format, String.class); } public String[] arrayFormat(final Object[] target, final Locale locale) { return arrayFormat(target, time -> temporalFormattingUtils.format(time, locale), String.class); } public String[] arrayFormat(final Object[] target, final String pattern) { return arrayFormat(target, time -> temporalFormattingUtils.format(time, pattern, null), String.class); } public String[] arrayFormat(final Object[] target, final String pattern, final Locale locale) { return arrayFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null), String.class); } public Integer[] arrayDay(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::day, Integer.class); } public Integer[] arrayMonth(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::month, Integer.class); } public String[] arrayMonthName(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::monthName, String.class); } public String[] arrayMonthNameShort(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::monthNameShort, String.class); } public Integer[] arrayYear(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::year, Integer.class); } public Integer[] arrayDayOfWeek(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::dayOfWeek, Integer.class); } public String[] arrayDayOfWeekName(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::dayOfWeekName, String.class); } public String[] arrayDayOfWeekNameShort(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::dayOfWeekNameShort, String.class); } public Integer[] arrayHour(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::hour, Integer.class); } public Integer[] arrayMinute(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::minute, Integer.class); } public Integer[] arraySecond(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::second, Integer.class); } public Integer[] arrayNanosecond(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::nanosecond, Integer.class); } public String[] arrayFormatISO(final Object[] target) { return arrayFormat(target, temporalFormattingUtils::formatISO, String.class); } private <R extends Object> R[] arrayFormat( final Object[] target, final Function<Object, R> mapFunction, final Class<R> returnType) {<FILL_FUNCTION_BODY>} }
Validate.notNull(target, "Target cannot be null"); return Stream.of(target) .map(time -> mapFunction.apply(time)) .toArray(length -> (R[]) Array.newInstance(returnType, length));
56
876
66
942
35,505
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalCreationUtils.java
TemporalCreationUtils
zoneId
class TemporalCreationUtils { public TemporalCreationUtils() { super(); } /** * * @return a instance of java.time.LocalDate * @since 2.1.0 */ public Temporal create(final Object year, final Object month, final Object day) { return LocalDate.of(integer(year), integer(month), integer(day)); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal create(final Object year, final Object month, final Object day, final Object hour, final Object minute) { return LocalDateTime.of(integer(year), integer(month), integer(day), integer(hour), integer(minute)); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal create(final Object year, final Object month, final Object day, final Object hour, final Object minute, final Object second) { return LocalDateTime.of(integer(year), integer(month), integer(day), integer(hour), integer(minute), integer(second)); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal create(final Object year, final Object month, final Object day, final Object hour, final Object minute, final Object second, final Object nanosecond) { return LocalDateTime.of(integer(year), integer(month), integer(day), integer(hour), integer(minute), integer(second), integer(nanosecond)); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal createNow() { return LocalDateTime.now(); } /** * * @return a instance of java.time.ZonedDateTime * @since 2.1.0 */ public Temporal createNowForTimeZone(final Object zoneId) { return ZonedDateTime.now(zoneId(zoneId)); } /** * * @return a instance of java.time.LocalDate * @since 2.1.0 */ public Temporal createToday() { return LocalDate.now(); } /** * * @return a instance of java.time.ZonedDateTime with 00:00:00.000 for the time part * @since 2.1.0 */ public Temporal createTodayForTimeZone(final Object zoneId) { return ZonedDateTime.now(zoneId(zoneId)) .withHour(0).withMinute(0).withSecond(0).withNano(0); } /** * * @return a instance of java.time.LocalDate * @since 2.1.0 */ public Temporal createDate(String isoDate) { return LocalDate.parse(isoDate); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal createDateTime(String isoDate) { return LocalDateTime.parse(isoDate); } /** * * @return a instance of java.time.LocalDate * @since 2.1.0 */ public Temporal createDate(String isoDate, String pattern) { return LocalDate.parse(isoDate, DateTimeFormatter.ofPattern(pattern)); } /** * * @return a instance of java.time.LocalDateTime * @since 2.1.0 */ public Temporal createDateTime(String isoDate, String pattern) { return LocalDateTime.parse(isoDate, DateTimeFormatter.ofPattern(pattern)); } private int integer(final Object number) { Validate.notNull(number, "Argument cannot be null"); return EvaluationUtils.evaluateAsNumber(number).intValue(); } private ZoneId zoneId(final Object zoneId) {<FILL_FUNCTION_BODY>} }
Validate.notNull(zoneId, "ZoneId cannot be null"); if (zoneId instanceof ZoneId) { return (ZoneId) zoneId; } else if (zoneId instanceof TimeZone) { TimeZone timeZone = (TimeZone) zoneId; return timeZone.toZoneId(); } else { return ZoneId.of(zoneId.toString()); }
117
1,088
100
1,188
35,506
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalFormattingUtils.java
TemporalFormattingUtils
formatDate
class TemporalFormattingUtils { // Even though Java comes with several patterns for ISO8601, we use the same pattern of Thymeleaf #dates utility. private static final DateTimeFormatter ISO8601_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"); private final Locale locale; private final ZoneId defaultZoneId; public TemporalFormattingUtils(final Locale locale, final ZoneId defaultZoneId) { super(); Validate.notNull(locale, "Locale cannot be null"); Validate.notNull(defaultZoneId, "ZoneId cannot be null"); this.locale = locale; this.defaultZoneId = defaultZoneId; } public String format(final Object target) { return formatDate(target); } public String format(final Object target, final Locale locale) { Validate.notNull(locale, "Locale cannot be null"); return formatDate(target, null, locale, null); } public String format(final Object target, final String pattern, final ZoneId zoneId) { return format(target, pattern, null, zoneId); } public String format(final Object target, final String pattern, final Locale locale, final ZoneId zoneId) { Validate.notEmpty(pattern, "Pattern cannot be null or empty"); return formatDate(target, pattern, locale, zoneId); } public Integer day(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.DAY_OF_MONTH)); } public Integer month(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.MONTH_OF_YEAR)); } public String monthName(final Object target) { return format(target, "MMMM", null); } public String monthNameShort(final Object target) { return format(target, "MMM", null); } public Integer year(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.YEAR)); } public Integer dayOfWeek(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.DAY_OF_WEEK)); } public String dayOfWeekName(final Object target) { return format(target, "EEEE", null); } public String dayOfWeekNameShort(final Object target) { return format(target, "EEE", null); } public Integer hour(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.HOUR_OF_DAY)); } public Integer minute(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.MINUTE_OF_HOUR)); } public Integer second(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.SECOND_OF_MINUTE)); } public Integer nanosecond(final Object target) { if (target == null) { return null; } final TemporalAccessor time = TemporalObjects.temporal(target); return Integer.valueOf(time.get(ChronoField.NANO_OF_SECOND)); } public String formatISO(final Object target) { if (target == null) { return null; } else if (target instanceof TemporalAccessor) { ChronoZonedDateTime time = TemporalObjects.zonedTime(target, defaultZoneId); return ISO8601_DATE_TIME_FORMATTER.withLocale(locale).format(time); } else { throw new IllegalArgumentException( "Cannot format object of class \"" + target.getClass().getName() + "\" as a date"); } } private String formatDate(final Object target) { return formatDate(target, null, null, null); } private String formatDate(final Object target, final String pattern, final Locale localeOverride, final ZoneId zoneId) {<FILL_FUNCTION_BODY>} private static DateTimeFormatter computeFormatter(final String pattern, final Class<?> targetClass, final Locale locale, final ZoneId zoneId) { final FormatStyle formatStyle; switch (pattern) { case "SHORT" : formatStyle = FormatStyle.SHORT; break; case "MEDIUM" : formatStyle = FormatStyle.MEDIUM; break; case "LONG" : formatStyle = FormatStyle.LONG; break; case "FULL" : formatStyle = FormatStyle.FULL; break; default : formatStyle = null; break; } if (formatStyle != null) { if (LocalDate.class.isAssignableFrom(targetClass)) { return DateTimeFormatter.ofLocalizedDate(formatStyle).withLocale(locale); } if (LocalTime.class.isAssignableFrom(targetClass)) { return DateTimeFormatter.ofLocalizedTime(formatStyle).withLocale(locale); } return DateTimeFormatter.ofLocalizedDateTime(formatStyle).withLocale(locale); } return DateTimeFormatter.ofPattern(pattern, locale).withZone(zoneId); } }
if (target == null) { return null; } Locale formattingLocale = localeOverride != null ? localeOverride : this.locale; try { DateTimeFormatter formatter; if (StringUtils.isEmptyOrWhitespace(pattern)) { formatter = TemporalObjects.formatterFor(target, formattingLocale); return formatter.format(TemporalObjects.temporal(target)); } else { formatter = computeFormatter(pattern, target.getClass(), formattingLocale, zoneId); return formatter.format(TemporalObjects.zonedTime(target, this.defaultZoneId)); } } catch (final Exception e) { throw new TemplateProcessingException( "Error formatting date for locale " + formattingLocale, e); }
251
1,627
207
1,834
35,507
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalListUtils.java
TemporalListUtils
listFormat
class TemporalListUtils { private final TemporalFormattingUtils temporalFormattingUtils; public TemporalListUtils(final Locale locale, final ZoneId defaultZoneId) { super(); Validate.notNull(locale, "Locale cannot be null"); Validate.notNull(defaultZoneId, "ZoneId cannot be null"); temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId); } public List<String> listFormat(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::format); } public <T extends Temporal> List<String> listFormat(final List<T> target, final Locale locale) { return listFormat(target, time -> temporalFormattingUtils.format(time, locale)); } public <T extends Temporal> List<String> listFormat(final List<T> target, final String pattern) { return listFormat(target, time -> temporalFormattingUtils.format(time, pattern, null)); } public <T extends Temporal> List<String> listFormat(final List<T> target, final String pattern, final Locale locale) { return listFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null)); } public List<Integer> listDay(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::day); } public List<Integer> listMonth(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::month); } public List<String> listMonthName(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::monthName); } public List<String> listMonthNameShort(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::monthNameShort); } public List<Integer> listYear(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::year); } public List<Integer> listDayOfWeek(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::dayOfWeek); } public List<String> listDayOfWeekName(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::dayOfWeekName); } public List<String> listDayOfWeekNameShort(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::dayOfWeekNameShort); } public List<Integer> listHour(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::hour); } public List<Integer> listMinute(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::minute); } public List<Integer> listSecond(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::second); } public List<Integer> listNanosecond(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::nanosecond); } public List<String> listFormatISO(final List<? extends Temporal> target) { return listFormat(target, temporalFormattingUtils::formatISO); } private <R extends Object, T extends Temporal> List<R> listFormat( final List<T> target, final Function<T, R> mapFunction) {<FILL_FUNCTION_BODY>} }
Validate.notNull(target, "Target cannot be null"); return target.stream() .map(time -> mapFunction.apply(time)) .collect(toList());
52
961
49
1,010
35,508
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalObjects.java
TemporalObjects
formatterFor
class TemporalObjects { public TemporalObjects() { super(); } public static DateTimeFormatter formatterFor(final Object target, final Locale locale) {<FILL_FUNCTION_BODY>} /** * Creates a Temporal object filling the missing fields of the provided time with default values. * @param target the temporal object to be converted * @param defaultZoneId the default value for ZoneId * @return a Temporal object */ public static ChronoZonedDateTime zonedTime(final Object target, final ZoneId defaultZoneId) { Validate.notNull(target, "Target cannot be null"); Validate.notNull(defaultZoneId, "ZoneId cannot be null"); if (target instanceof Instant) { return ZonedDateTime.ofInstant((Instant) target, defaultZoneId); } else if (target instanceof LocalDate) { return ZonedDateTime.of((LocalDate) target, LocalTime.MIDNIGHT, defaultZoneId); } else if (target instanceof LocalDateTime) { return ZonedDateTime.of((LocalDateTime) target, defaultZoneId); } else if (target instanceof LocalTime) { return ZonedDateTime.of(LocalDate.now(), (LocalTime) target, defaultZoneId); } else if (target instanceof OffsetDateTime) { return ((OffsetDateTime) target).toZonedDateTime(); } else if (target instanceof OffsetTime) { LocalTime localTime = ((OffsetTime) target).toLocalTime(); return ZonedDateTime.of(LocalDate.now(), localTime, defaultZoneId); } else if (target instanceof Year) { LocalDate localDate = ((Year) target).atDay(1); return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId); } else if (target instanceof YearMonth) { LocalDate localDate = ((YearMonth) target).atDay(1); return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId); } else if (target instanceof ZonedDateTime) { return (ChronoZonedDateTime) target; } else { throw new IllegalArgumentException( "Cannot format object of class \"" + target.getClass().getName() + "\" as a date"); } } public static TemporalAccessor temporal(final Object target) { Validate.notNull(target, "Target cannot be null"); if (target instanceof TemporalAccessor) { return (TemporalAccessor) target; } else { throw new IllegalArgumentException( "Cannot normalize class \"" + target.getClass().getName() + "\" as a date"); } } private static DateTimeFormatter yearMonthFormatter(final Locale locale) { if (shouldDisplayYearBeforeMonth(locale)) { return new DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR) .appendLiteral(' ') .appendText(ChronoField.MONTH_OF_YEAR) .toFormatter() .withLocale(locale); } else { return new DateTimeFormatterBuilder() .appendText(ChronoField.MONTH_OF_YEAR) .appendLiteral(' ') .appendValue(ChronoField.YEAR) .toFormatter() .withLocale(locale); } } private static boolean shouldDisplayYearBeforeMonth(final Locale locale) { // We use "Month Year" or "Year Month" depending on the locale according to https://en.wikipedia.org/wiki/Date_format_by_country String country = locale.getCountry(); switch (country) { case "BT" : case "CA" : case "CN" : case "KP" : case "KR" : case "TW" : case "HU" : case "IR" : case "JP" : case "LT" : case "MN" : return true; default: return false; } } }
Validate.notNull(target, "Target cannot be null"); Validate.notNull(locale, "Locale cannot be null"); if (target instanceof Instant) { return new DateTimeFormatterBuilder().appendInstant().toFormatter(); } else if (target instanceof LocalDate) { return DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale); } else if (target instanceof LocalDateTime) { return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.MEDIUM).withLocale(locale); } else if (target instanceof LocalTime) { return DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).withLocale(locale); } else if (target instanceof OffsetDateTime) { return new DateTimeFormatterBuilder() .appendLocalized(FormatStyle.LONG, FormatStyle.MEDIUM) .appendLocalizedOffset(TextStyle.FULL) .toFormatter() .withLocale(locale); } else if (target instanceof OffsetTime) { return new DateTimeFormatterBuilder() .appendValue(ChronoField.HOUR_OF_DAY) .appendLiteral(':') .appendValue(ChronoField.MINUTE_OF_HOUR) .appendLiteral(':') .appendValue(ChronoField.SECOND_OF_MINUTE) .appendLocalizedOffset(TextStyle.FULL) .toFormatter() .withLocale(locale); } else if (target instanceof Year) { return new DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR) .toFormatter(); } else if (target instanceof YearMonth) { return yearMonthFormatter(locale); } else if (target instanceof ZonedDateTime) { return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withLocale(locale); } else { throw new IllegalArgumentException( "Cannot format object of class \"" + target.getClass().getName() + "\" as a date"); }
560
1,032
521
1,553
35,509
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/temporal/TemporalSetUtils.java
TemporalSetUtils
setFormat
class TemporalSetUtils { private final TemporalFormattingUtils temporalFormattingUtils; public TemporalSetUtils(final Locale locale, final ZoneId defaultZoneId) { super(); Validate.notNull(locale, "Locale cannot be null"); Validate.notNull(defaultZoneId, "ZoneId cannot be null"); temporalFormattingUtils = new TemporalFormattingUtils(locale, defaultZoneId); } public Set<String> setFormat(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::format); } public <T extends Temporal> Set<String> setFormat(final Set<T> target, final Locale locale) { return setFormat(target, time -> temporalFormattingUtils.format(time, locale)); } public <T extends Temporal> Set<String> setFormat(final Set<T> target, final String pattern) { return setFormat(target, time -> temporalFormattingUtils.format(time, pattern, null)); } public <T extends Temporal> Set<String> setFormat(final Set<T> target, final String pattern, final Locale locale) { return setFormat(target, time -> temporalFormattingUtils.format(time, pattern, locale, null)); } public Set<Integer> setDay(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::day); } public Set<Integer> setMonth(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::month); } public Set<String> setMonthName(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::monthName); } public Set<String> setMonthNameShort(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::monthNameShort); } public Set<Integer> setYear(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::year); } public Set<Integer> setDayOfWeek(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::dayOfWeek); } public Set<String> setDayOfWeekName(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::dayOfWeekName); } public Set<String> setDayOfWeekNameShort(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::dayOfWeekNameShort); } public Set<Integer> setHour(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::hour); } public Set<Integer> setMinute(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::minute); } public Set<Integer> setSecond(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::second); } public Set<Integer> setNanosecond(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::nanosecond); } public Set<String> setFormatISO(final Set<? extends Temporal> target) { return setFormat(target, temporalFormattingUtils::formatISO); } private <R extends Object, T extends Temporal> Set<R> setFormat( final Set<T> target, final Function<T, R> mapFunction) {<FILL_FUNCTION_BODY>} }
Validate.notNull(target, "Target cannot be null"); return target.stream() .map(time -> mapFunction.apply(time)) .collect(toSet());
52
959
49
1,008
35,510
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebApplication.java
JakartaServletWebApplication
buildExchange
class JakartaServletWebApplication implements IServletWebApplication { // This class is made NOT final so that it can be proxied by Dependency Injection frameworks private final ServletContext servletContext; JakartaServletWebApplication(final ServletContext servletContext) { super(); Validate.notNull(servletContext, "Servlet context cannot be null"); this.servletContext = servletContext; } public static JakartaServletWebApplication buildApplication(final ServletContext servletContext) { return new JakartaServletWebApplication(servletContext); } public IServletWebExchange buildExchange(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getAttributeNames() { return this.servletContext.getAttributeNames(); } @Override public Object getAttributeValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.servletContext.getAttribute(name); } @Override public void setAttributeValue(final String name, final Object value) { Validate.notNull(name, "Name cannot be null"); this.servletContext.setAttribute(name, value); } @Override public InputStream getResourceAsStream(final String path) { Validate.notNull(path, "Path cannot be null"); return this.servletContext.getResourceAsStream(path); } @Override public URL getResource(final String path) throws MalformedURLException { Validate.notNull(path, "Path cannot be null"); return this.servletContext.getResource(path); } @Override public Object getNativeServletContextObject() { return this.servletContext; } private boolean servletContextMatches(final HttpServletRequest httpServletRequest) { // We should not be directly matching servletContext objects because a wrapper might have been applied final String servletContextPath = this.servletContext.getContextPath(); final String requestServletContextPath = httpServletRequest.getServletContext().getContextPath(); return Objects.equals(servletContextPath, requestServletContextPath); } }
Validate.notNull(httpServletRequest, "Request cannot be null"); Validate.notNull(httpServletResponse, "Response cannot be null"); Validate.isTrue(servletContextMatches(httpServletRequest), "Cannot build an application for a request which servlet context does not match with " + "the application that it is being built for."); final JakartaServletWebRequest request = new JakartaServletWebRequest(httpServletRequest); final JakartaServletWebSession session = new JakartaServletWebSession(httpServletRequest); return new JakartaServletWebExchange(request, session, this, httpServletResponse);
130
588
166
754
35,511
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebRequest.java
JakartaServletWebRequest
getCookieMap
class JakartaServletWebRequest implements IServletWebRequest { private final HttpServletRequest request; JakartaServletWebRequest(final HttpServletRequest request) { super(); Validate.notNull(request, "Request cannot be null"); this.request = request; } @Override public String getMethod() { return this.request.getMethod(); } @Override public String getScheme() { return this.request.getScheme(); } @Override public String getServerName() { return this.request.getServerName(); } @Override public Integer getServerPort() { return Integer.valueOf(this.request.getServerPort()); } @Override public String getContextPath() { final String contextPath = this.request.getContextPath(); // This protects against a redirection behaviour in Jetty return (contextPath != null && contextPath.length() == 1 && contextPath.charAt(0) == '/')? "" : contextPath; } @Override public String getRequestURI() { return this.request.getRequestURI(); } @Override public String getQueryString() { return this.request.getQueryString(); } @Override public Enumeration<String> getHeaderNames() { return this.request.getHeaderNames(); } @Override public Enumeration<String> getHeaders(final String name) { return this.request.getHeaders(name); } @Override public String getHeaderValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getHeader(name); } @Override public Map<String, String[]> getParameterMap() { return this.request.getParameterMap(); } @Override public String getParameterValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getParameter(name); } @Override public String[] getParameterValues(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getParameterValues(name); } @Override public boolean containsCookie(final String name) { Validate.notNull(name, "Name cannot be null"); final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return false; } for (int i = 0; i < cookies.length; i++) { if (name.equals(cookies[i].getName())) { return true; } } return false; } @Override public int getCookieCount() { final Cookie[] cookies = this.request.getCookies(); return (cookies == null? 0 : cookies.length); } @Override public Set<String> getAllCookieNames() { final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return Collections.emptySet(); } final Set<String> cookieNames = new LinkedHashSet<String>(3); for (int i = 0; i < cookies.length; i++) { cookieNames.add(cookies[i].getName()); } return Collections.unmodifiableSet(cookieNames); } @Override public Map<String, String[]> getCookieMap() {<FILL_FUNCTION_BODY>} @Override public String[] getCookieValues(final String name) { Validate.notNull(name, "Name cannot be null"); final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return null; } String[] cookieValues = null; for (int i = 0; i < cookies.length; i++) { final String cookieName = cookies[i].getName(); if (name.equals(cookieName)) { final String cookieValue = cookies[i].getValue(); if (cookieValues != null) { final String[] newCookieValues = Arrays.copyOf(cookieValues, cookieValues.length + 1); newCookieValues[cookieValues.length] = cookieValue; cookieValues = newCookieValues; } else { cookieValues = new String[]{cookieValue}; } } } return cookieValues; } @Override public Object getNativeRequestObject() { return this.request; } }
final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return Collections.emptyMap(); } final Map<String,String[]> cookieMap = new LinkedHashMap<String,String[]>(3); for (int i = 0; i < cookies.length; i++) { final String cookieName = cookies[i].getName(); final String cookieValue = cookies[i].getValue(); if (cookieMap.containsKey(cookieName)) { final String[] currentCookieValues = cookieMap.get(cookieName); final String[] newCookieValues = Arrays.copyOf(currentCookieValues, currentCookieValues.length + 1); newCookieValues[currentCookieValues.length] = cookieValue; cookieMap.put(cookieName, newCookieValues); } else { cookieMap.put(cookieName, new String[]{cookieValue}); } } return Collections.unmodifiableMap(cookieMap);
265
1,189
255
1,444
35,512
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JakartaServletWebSession.java
JakartaServletWebSession
getAttributeValue
class JakartaServletWebSession implements IServletWebSession { private final HttpServletRequest request; private HttpSession session; JakartaServletWebSession(final HttpServletRequest request) { super(); Validate.notNull(request, "Request cannot be null"); this.request = request; this.session = this.request.getSession(false); // Might initialize property as null } @Override public boolean exists() { return this.session != null; } @Override public Enumeration<String> getAttributeNames() { if (this.session == null) { return Collections.emptyEnumeration(); } return this.session.getAttributeNames(); } @Override public Object getAttributeValue(final String name) {<FILL_FUNCTION_BODY>} @Override public void setAttributeValue(final String name, final Object value) { Validate.notNull(name, "Name cannot be null"); if (this.session == null) { // Setting an attribute will actually create a new session this.session = this.request.getSession(true); } this.session.setAttribute(name, value); } @Override public Object getNativeSessionObject() { return this.session; } }
Validate.notNull(name, "Name cannot be null"); if (this.session == null) { return null; } return this.session.getAttribute(name);
59
343
50
393
35,513
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebApplication.java
JavaxServletWebApplication
buildExchange
class JavaxServletWebApplication implements IServletWebApplication { // This class is made NOT final so that it can be proxied by Dependency Injection frameworks private final ServletContext servletContext; JavaxServletWebApplication(final ServletContext servletContext) { super(); Validate.notNull(servletContext, "Servlet context cannot be null"); this.servletContext = servletContext; } public static JavaxServletWebApplication buildApplication(final ServletContext servletContext) { return new JavaxServletWebApplication(servletContext); } public IServletWebExchange buildExchange(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getAttributeNames() { return this.servletContext.getAttributeNames(); } @Override public Object getAttributeValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.servletContext.getAttribute(name); } @Override public void setAttributeValue(final String name, final Object value) { Validate.notNull(name, "Name cannot be null"); this.servletContext.setAttribute(name, value); } @Override public InputStream getResourceAsStream(final String path) { Validate.notNull(path, "Path cannot be null"); return this.servletContext.getResourceAsStream(path); } @Override public URL getResource(final String path) throws MalformedURLException { Validate.notNull(path, "Path cannot be null"); return this.servletContext.getResource(path); } @Override public Object getNativeServletContextObject() { return this.servletContext; } private boolean servletContextMatches(final HttpServletRequest httpServletRequest) { // We should not be directly matching servletContext objects because a wrapper might have been applied final String servletContextPath = this.servletContext.getContextPath(); final String requestServletContextPath = httpServletRequest.getServletContext().getContextPath(); return Objects.equals(servletContextPath, requestServletContextPath); } }
Validate.notNull(httpServletRequest, "Request cannot be null"); Validate.notNull(httpServletResponse, "Response cannot be null"); Validate.isTrue(servletContextMatches(httpServletRequest), "Cannot build an application for a request which servlet context does not match with " + "the application that it is being built for."); final JavaxServletWebRequest request = new JavaxServletWebRequest(httpServletRequest); final JavaxServletWebSession session = new JavaxServletWebSession(httpServletRequest); return new JavaxServletWebExchange(request, session, this, httpServletResponse);
130
584
161
745
35,514
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebRequest.java
JavaxServletWebRequest
getCookieValues
class JavaxServletWebRequest implements IServletWebRequest { private final HttpServletRequest request; JavaxServletWebRequest(final HttpServletRequest request) { super(); Validate.notNull(request, "Request cannot be null"); this.request = request; } @Override public String getMethod() { return this.request.getMethod(); } @Override public String getScheme() { return this.request.getScheme(); } @Override public String getServerName() { return this.request.getServerName(); } @Override public Integer getServerPort() { return Integer.valueOf(this.request.getServerPort()); } @Override public String getContextPath() { final String contextPath = this.request.getContextPath(); // This protects against a redirection behaviour in Jetty return (contextPath != null && contextPath.length() == 1 && contextPath.charAt(0) == '/')? "" : contextPath; } @Override public String getRequestURI() { return this.request.getRequestURI(); } @Override public String getQueryString() { return this.request.getQueryString(); } @Override public Enumeration<String> getHeaderNames() { return this.request.getHeaderNames(); } @Override public Enumeration<String> getHeaders(final String name) { return this.request.getHeaders(name); } @Override public String getHeaderValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getHeader(name); } @Override public Map<String, String[]> getParameterMap() { return this.request.getParameterMap(); } @Override public String getParameterValue(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getParameter(name); } @Override public String[] getParameterValues(final String name) { Validate.notNull(name, "Name cannot be null"); return this.request.getParameterValues(name); } @Override public boolean containsCookie(final String name) { Validate.notNull(name, "Name cannot be null"); final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return false; } for (int i = 0; i < cookies.length; i++) { if (name.equals(cookies[i].getName())) { return true; } } return false; } @Override public int getCookieCount() { final Cookie[] cookies = this.request.getCookies(); return (cookies == null? 0 : cookies.length); } @Override public Set<String> getAllCookieNames() { final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return Collections.emptySet(); } final Set<String> cookieNames = new LinkedHashSet<String>(3); for (int i = 0; i < cookies.length; i++) { cookieNames.add(cookies[i].getName()); } return Collections.unmodifiableSet(cookieNames); } @Override public Map<String, String[]> getCookieMap() { final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return Collections.emptyMap(); } final Map<String,String[]> cookieMap = new LinkedHashMap<String,String[]>(3); for (int i = 0; i < cookies.length; i++) { final String cookieName = cookies[i].getName(); final String cookieValue = cookies[i].getValue(); if (cookieMap.containsKey(cookieName)) { final String[] currentCookieValues = cookieMap.get(cookieName); final String[] newCookieValues = Arrays.copyOf(currentCookieValues, currentCookieValues.length + 1); newCookieValues[currentCookieValues.length] = cookieValue; cookieMap.put(cookieName, newCookieValues); } else { cookieMap.put(cookieName, new String[]{cookieValue}); } } return Collections.unmodifiableMap(cookieMap); } @Override public String[] getCookieValues(final String name) {<FILL_FUNCTION_BODY>} @Override public Object getNativeRequestObject() { return this.request; } }
Validate.notNull(name, "Name cannot be null"); final Cookie[] cookies = this.request.getCookies(); if (cookies == null) { return null; } String[] cookieValues = null; for (int i = 0; i < cookies.length; i++) { final String cookieName = cookies[i].getName(); if (name.equals(cookieName)) { final String cookieValue = cookies[i].getValue(); if (cookieValues != null) { final String[] newCookieValues = Arrays.copyOf(cookieValues, cookieValues.length + 1); newCookieValues[cookieValues.length] = cookieValue; cookieValues = newCookieValues; } else { cookieValues = new String[]{cookieValue}; } } } return cookieValues;
317
1,224
218
1,442
35,515
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/web/servlet/JavaxServletWebSession.java
JavaxServletWebSession
getAttributeValue
class JavaxServletWebSession implements IServletWebSession { private final HttpServletRequest request; private HttpSession session; JavaxServletWebSession(final HttpServletRequest request) { super(); Validate.notNull(request, "Request cannot be null"); this.request = request; this.session = this.request.getSession(false); // Might initialize property as null } @Override public boolean exists() { return this.session != null; } @Override public Enumeration<String> getAttributeNames() { if (this.session == null) { return Collections.emptyEnumeration(); } return this.session.getAttributeNames(); } @Override public Object getAttributeValue(final String name) {<FILL_FUNCTION_BODY>} @Override public void setAttributeValue(final String name, final Object value) { Validate.notNull(name, "Name cannot be null"); if (this.session == null) { // Setting an attribute will actually create a new session this.session = this.request.getSession(true); } this.session.setAttribute(name, value); } @Override public Object getNativeSessionObject() { return this.session; } }
Validate.notNull(name, "Name cannot be null"); if (this.session == null) { return null; } return this.session.getAttribute(name);
59
341
50
391
35,516
google_truth
truth/core/src/main/java/com/google/common/truth/AbstractArraySubject.java
AbstractArraySubject
isEmpty
class AbstractArraySubject extends Subject { private final @Nullable Object actual; AbstractArraySubject( FailureMetadata metadata, @Nullable Object actual, @Nullable String typeDescription) { super(metadata, actual, typeDescription); this.actual = actual; } /** Fails if the array is not empty (i.e. {@code array.length > 0}). */ public final void isEmpty() {<FILL_FUNCTION_BODY>} /** Fails if the array is empty (i.e. {@code array.length == 0}). */ public final void isNotEmpty() { if (length() == 0) { failWithoutActual(simpleFact("expected not to be empty")); } } /** * Fails if the array does not have the given length. * * @throws IllegalArgumentException if {@code length < 0} */ public final void hasLength(int length) { checkArgument(length >= 0, "length (%s) must be >= 0", length); check("length").that(length()).isEqualTo(length); } private int length() { return Array.getLength(checkNotNull(actual)); } }
if (length() > 0) { failWithActual(simpleFact("expected to be empty")); }
24
298
30
328
35,518
google_truth
truth/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
BigDecimalSubject
compareValues
class BigDecimalSubject extends ComparableSubject<BigDecimal> { private final @Nullable BigDecimal actual; BigDecimalSubject(FailureMetadata metadata, @Nullable BigDecimal actual) { super(metadata, actual); this.actual = actual; } /** * Fails if the subject's value is not equal to the value of the given {@link BigDecimal}. (i.e., * fails if {@code actual.comparesTo(expected) != 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(BigDecimal expected) { compareValues(expected); } /** * Fails if the subject's value is not equal to the value of the {@link BigDecimal} created from * the expected string (i.e., fails if {@code actual.comparesTo(new BigDecimal(expected)) != 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(String expected) { compareValues(new BigDecimal(expected)); } /** * Fails if the subject's value is not equal to the value of the {@link BigDecimal} created from * the expected {@code long} (i.e., fails if {@code actual.comparesTo(new BigDecimal(expected)) != * 0}). * * <p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and * the scales, use {@link #isEqualTo(Object)}. */ public void isEqualToIgnoringScale(long expected) { compareValues(new BigDecimal(expected)); } /** * Fails if the subject's value and scale is not equal to the given {@link BigDecimal}. * * <p><b>Note:</b> If you only want to compare the values of the BigDecimals and not their scales, * use {@link #isEqualToIgnoringScale(BigDecimal)} instead. */ @Override // To express more specific javadoc public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); } /** * Fails if the subject is not equivalent to the given value according to {@link * Comparable#compareTo}, (i.e., fails if {@code a.comparesTo(b) != 0}). This method behaves * identically to (the more clearly named) {@link #isEqualToIgnoringScale(BigDecimal)}. * * <p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link * #isEqualTo(Object)}. */ @Override public void isEquivalentAccordingToCompareTo(@Nullable BigDecimal expected) { compareValues(expected); } private void compareValues(@Nullable BigDecimal expected) {<FILL_FUNCTION_BODY>} }
if (checkNotNull(actual).compareTo(checkNotNull(expected)) != 0) { failWithoutActual(fact("expected", expected), butWas(), simpleFact("(scale is ignored)")); }
26
819
52
871
35,519
google_truth
truth/core/src/main/java/com/google/common/truth/BooleanSubject.java
BooleanSubject
isTrue
class BooleanSubject extends Subject { private final @Nullable Boolean actual; BooleanSubject(FailureMetadata metadata, @Nullable Boolean actual) { super(metadata, actual); this.actual = actual; } /** Fails if the subject is false or {@code null}. */ public void isTrue() {<FILL_FUNCTION_BODY>} /** Fails if the subject is true or {@code null}. */ public void isFalse() { if (actual == null) { isEqualTo(false); // fails } else if (actual) { failWithoutActual(simpleFact("expected to be false")); } } }
if (actual == null) { isEqualTo(true); // fails } else if (!actual) { failWithoutActual(simpleFact("expected to be true")); }
40
164
48
212
35,520
google_truth
truth/core/src/main/java/com/google/common/truth/ClassSubject.java
ClassSubject
isAssignableTo
class ClassSubject extends Subject { private final @Nullable Class<?> actual; ClassSubject(FailureMetadata metadata, @Nullable Class<?> o) { super(metadata, o); this.actual = o; } /** * Fails if this class or interface is not the same as or a subclass or subinterface of, the given * class or interface. */ public void isAssignableTo(Class<?> clazz) {<FILL_FUNCTION_BODY>} }
if (!clazz.isAssignableFrom(checkNotNull(actual))) { failWithActual("expected to be assignable to", clazz.getName()); }
24
130
43
173
35,521
google_truth
truth/core/src/main/java/com/google/common/truth/ComparableSubject.java
ComparableSubject
isLessThan
class ComparableSubject<T extends Comparable<?>> extends Subject { /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call * {@link Subject#check(String, Object...) check(...)}{@code .that(actual)}. */ private final @Nullable T actual; protected ComparableSubject(FailureMetadata metadata, @Nullable T actual) { super(metadata, actual); this.actual = actual; } /** Checks that the subject is in {@code range}. */ public final void isIn(Range<T> range) { if (!range.contains(checkNotNull(actual))) { failWithActual("expected to be in range", range); } } /** Checks that the subject is <i>not</i> in {@code range}. */ public final void isNotIn(Range<T> range) { if (range.contains(checkNotNull(actual))) { failWithActual("expected not to be in range", range); } } /** * Checks that the subject is equivalent to {@code other} according to {@link * Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}). * * <p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link * #isEqualTo(Object)}. */ @SuppressWarnings("unchecked") public void isEquivalentAccordingToCompareTo(@Nullable T expected) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(expected)) != 0) { failWithActual("expected value that sorts equal to", expected); } } /** * Checks that the subject is greater than {@code other}. * * <p>To check that the subject is greater than <i>or equal to</i> {@code other}, use {@link * #isAtLeast}. */ @SuppressWarnings("unchecked") public final void isGreaterThan(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) <= 0) { failWithActual("expected to be greater than", other); } } /** * Checks that the subject is less than {@code other}. * * <p>To check that the subject is less than <i>or equal to</i> {@code other}, use {@link * #isAtMost}. */ @SuppressWarnings("unchecked") public final void isLessThan(@Nullable T other) {<FILL_FUNCTION_BODY>} /** * Checks that the subject is less than or equal to {@code other}. * * <p>To check that the subject is <i>strictly</i> less than {@code other}, use {@link * #isLessThan}. */ @SuppressWarnings("unchecked") public final void isAtMost(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) > 0) { failWithActual("expected to be at most", other); } } /** * Checks that the subject is greater than or equal to {@code other}. * * <p>To check that the subject is <i>strictly</i> greater than {@code other}, use {@link * #isGreaterThan}. */ @SuppressWarnings("unchecked") public final void isAtLeast(@Nullable T other) { if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) < 0) { failWithActual("expected to be at least", other); } } }
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) >= 0) { failWithActual("expected to be less than", other); }
27
970
48
1,018
35,522
google_truth
truth/core/src/main/java/com/google/common/truth/ComparisonFailures.java
ComparisonFailures
removeCommonPrefixAndSuffix
class ComparisonFailures { static ImmutableList<Fact> makeComparisonFailureFacts( ImmutableList<Fact> headFacts, ImmutableList<Fact> tailFacts, String expected, String actual) { return concat(headFacts, formatExpectedAndActual(expected, actual), tailFacts); } /** * Returns one or more facts describing the difference between the given expected and actual * values. * * <p>Currently, that means either 2 facts (one each for expected and actual) or 1 fact with a * diff-like (but much simpler) view. * * <p>In the case of 2 facts, the facts contain either the full expected and actual values or, if * the values have a long prefix or suffix in common, abbreviated values with "…" at the beginning * or end. */ @VisibleForTesting static ImmutableList<Fact> formatExpectedAndActual(String expected, String actual) { ImmutableList<Fact> result; // TODO(cpovirk): Call attention to differences in trailing whitespace. // TODO(cpovirk): And changes in the *kind* of whitespace characters in the middle of the line. result = Platform.makeDiff(expected, actual); if (result != null) { return result; } result = removeCommonPrefixAndSuffix(expected, actual); if (result != null) { return result; } return ImmutableList.of(fact("expected", expected), fact("but was", actual)); } private static @Nullable ImmutableList<Fact> removeCommonPrefixAndSuffix( String expected, String actual) {<FILL_FUNCTION_BODY>} private static final int CONTEXT = 20; private static final int WORTH_HIDING = 60; // From c.g.c.base.Strings. private static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && isHighSurrogate(string.charAt(index)) && isLowSurrogate(string.charAt(index + 1)); } private ComparisonFailures() {} }
int originalExpectedLength = expected.length(); // TODO(cpovirk): Use something like BreakIterator where available. /* * TODO(cpovirk): If the abbreviated values contain newlines, maybe expand them to contain a * newline on each end so that we don't start mid-line? That way, horizontally aligned text will * remain horizontally aligned. But of course, for many multi-line strings, we won't enter this * method at all because we'll generate diff-style output instead. So we might not need to worry * too much about newlines here. */ // TODO(cpovirk): Avoid splitting in the middle of "\r\n." int prefix = commonPrefix(expected, actual).length(); prefix = max(0, prefix - CONTEXT); while (prefix > 0 && validSurrogatePairAt(expected, prefix - 1)) { prefix--; } // No need to hide the prefix unless it's long. if (prefix > 3) { expected = "…" + expected.substring(prefix); actual = "…" + actual.substring(prefix); } int suffix = commonSuffix(expected, actual).length(); suffix = max(0, suffix - CONTEXT); while (suffix > 0 && validSurrogatePairAt(expected, expected.length() - suffix - 1)) { suffix--; } // No need to hide the suffix unless it's long. if (suffix > 3) { expected = expected.substring(0, expected.length() - suffix) + "…"; actual = actual.substring(0, actual.length() - suffix) + "…"; } if (originalExpectedLength - expected.length() < WORTH_HIDING) { return null; } return ImmutableList.of(fact("expected", expected), fact("but was", actual));
339
572
481
1,053