proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringActionTagProcessor.java
|
SpringActionTagProcessor
|
doProcess
|
class SpringActionTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String TARGET_ATTR_NAME = "action";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String METHOD_ATTR_NAME = "method";
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private static final String VALUE_ATTR_NAME = "value";
private static final String METHOD_ATTR_DEFAULT_VALUE = "GET";
private AttributeDefinition targetAttributeDefinition;
private AttributeDefinition methodAttributeDefinition;
public SpringActionTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions 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);
this.methodAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, METHOD_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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// But before setting the 'action' attribute, we need to verify the 'method' attribute and let the
// RequestDataValueProcessor act on it.
final String methodAttributeValue = tag.getAttributeValue(this.methodAttributeDefinition.getAttributeName());
final String httpMethod = methodAttributeValue == null ? METHOD_ATTR_DEFAULT_VALUE : methodAttributeValue;
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processAction(context, newAttributeValue, httpMethod);
// Set the 'action' attribute
StandardProcessorUtils.replaceAttribute(
structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
// If this th:action is in a <form> tag, we might need to add a hidden field (depending on Spring configuration)
if ("form".equalsIgnoreCase(tag.getElementCompleteName())) {
final Map<String,String> extraHiddenFields =
RequestDataValueProcessorUtils.getExtraHiddenFields(context);
if (extraHiddenFields != null && extraHiddenFields.size() > 0) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel extraHiddenElementTags = modelFactory.createModel();
for (final Map.Entry<String,String> extraHiddenField : extraHiddenFields.entrySet()) {
final Map<String,String> extraHiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
extraHiddenAttributes.put(TYPE_ATTR_NAME, "hidden");
extraHiddenAttributes.put(NAME_ATTR_NAME, extraHiddenField.getKey());
extraHiddenAttributes.put(VALUE_ATTR_NAME, extraHiddenField.getValue()); // no need to re-apply the processor here
final IStandaloneElementTag extraHiddenElementTag =
modelFactory.createStandaloneElementTag("input", extraHiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
extraHiddenElementTags.add(extraHiddenElementTag);
}
structureHandler.insertImmediatelyAfter(extraHiddenElementTags, false);
}
}
| 477
| 579
| 1,056
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringErrorClassTagProcessor.java
|
SpringErrorClassTagProcessor
|
doProcess
|
class SpringErrorClassTagProcessor
extends AbstractAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1800;
public static final String ATTR_NAME = "errorclass";
public static final String TARGET_ATTR_NAME = "class";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringErrorClassTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, null, false, ATTR_NAME, true,ATTR_PRECEDENCE, true);
}
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 IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
/*
* There are two scenarios for a th:errorclass to appear in: one is in an element for which a th:field has already
* been executed, in which case we already have a BindStatus to check for errors; and the other one is an element
* for which a th:field has not been executed, but which should have a "name" attribute (either directly or as
* the result of executing a th:name) -- in this case, we'll have to build the BuildStatus ourselves.
*/
private static IThymeleafBindStatus computeBindStatus(final IExpressionContext context, final IProcessableElementTag tag) {
/*
* First, try to obtain an already-existing BindStatus resulting from the execution of a th:field attribute
* in the same element.
*/
final IThymeleafBindStatus bindStatus =
(IThymeleafBindStatus) context.getVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS);
if (bindStatus != null) {
return bindStatus;
}
/*
* It seems no th:field was executed on the same element, so we must rely on the "name" attribute (probably
* specified by hand or by a th:name). No th:field was executed, so no BindStatus available -- we'll have to
* build it ourselves.
*/
final String fieldName = tag.getAttributeValue("name");
if (StringUtils.isEmptyOrWhitespace(fieldName)) {
return null;
}
final VariableExpression boundExpression =
(VariableExpression) context.getVariable(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION);
if (boundExpression == null) {
// No bound expression, so just use the field name
return FieldUtils.getBindStatusFromParsedExpression(context, false, fieldName);
}
// Bound object and field object names might intersect (e.g. th:object="a.b", name="b.c"), and we must compute
// the real 'bindable' name ("a.b.c") by only using the first token in the bound object name, appending the
// rest of the field name: "a" + "b.c" -> "a.b.c"
final String boundExpressionStr = boundExpression.getExpression();
final String computedFieldName;
if (boundExpressionStr.indexOf('.') == -1) {
computedFieldName = boundExpressionStr + '.' + fieldName; // we append because we will use no form root afterwards
} else {
computedFieldName = boundExpressionStr.substring(0, boundExpressionStr.indexOf('.')) + '.' + fieldName;
}
// We set "useRoot" to false because we have already computed that part
return FieldUtils.getBindStatusFromParsedExpression(context, false, computedFieldName);
}
}
|
final IThymeleafBindStatus bindStatus = computeBindStatus(context, tag);
if (bindStatus == null) {
final AttributeName fieldAttributeName =
AttributeNames.forHTMLName(attributeName.getPrefix(), AbstractSpringFieldTagProcessor.ATTR_NAME);
throw new TemplateProcessingException(
"Cannot apply \"" + attributeName + "\": this attribute requires the existence of " +
"a \"name\" (or " + Arrays.asList(fieldAttributeName.getCompleteAttributeNames()) + ") attribute " +
"with non-empty value in the same host tag.");
}
if (bindStatus.isError()) {
final IEngineConfiguration configuration = context.getConfiguration();
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);
final Object expressionResult = expression.execute(context);
String newAttributeValue = HtmlEscape.escapeHtml4Xml(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);
}
}
| 1,075
| 429
| 1,504
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringErrorsTagProcessor.java
|
SpringErrorsTagProcessor
|
doProcess
|
class SpringErrorsTagProcessor extends AbstractAttributeTagProcessor {
private static final String ERROR_DELIMITER = "<br />";
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "errors";
public SpringErrorsTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, ATTR_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 IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus.isError()) {
final StringBuilder strBuilder = new StringBuilder();
final String[] errorMsgs = bindStatus.getErrorMessages();
for (int i = 0; i < errorMsgs.length; i++) {
if (i > 0) {
strBuilder.append(ERROR_DELIMITER);
}
final String displayString = SpringValueFormatter.getDisplayString(errorMsgs[i], false);
strBuilder.append(HtmlEscape.escapeHtml4Xml(displayString));
}
structureHandler.setBody(strBuilder.toString(), false);
// Just in case we also have a th:errorclass in this tag
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
} else {
structureHandler.removeElement();
}
| 199
| 249
| 448
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringHrefTagProcessor.java
|
SpringHrefTagProcessor
|
doProcess
|
class SpringHrefTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String ATTR_NAME = "href";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringHrefTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE, false, true);
}
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, 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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processUrl(context, newAttributeValue);
// Set the real, non prefixed attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, ATTR_NAME, (newAttributeValue == null ? "" : newAttributeValue));
| 349
| 121
| 470
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringInputCheckboxFieldTagProcessor.java
|
SpringInputCheckboxFieldTagProcessor
|
doProcess
|
class SpringInputCheckboxFieldTagProcessor
extends AbstractSpringFieldTagProcessor {
public static final String CHECKBOX_INPUT_TYPE_ATTR_VALUE = "checkbox";
private final boolean renderHiddenMarkersBeforeCheckboxes;
public SpringInputCheckboxFieldTagProcessor(final String dialectPrefix) {
this(dialectPrefix, SpringStandardDialect.DEFAULT_RENDER_HIDDEN_MARKERS_BEFORE_CHECKBOXES);
}
public SpringInputCheckboxFieldTagProcessor(final String dialectPrefix, final boolean renderHiddenMarkersBeforeCheckboxes) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { CHECKBOX_INPUT_TYPE_ATTR_VALUE }, true);
this.renderHiddenMarkersBeforeCheckboxes = renderHiddenMarkersBeforeCheckboxes;
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private final boolean isDisabled(final IProcessableElementTag tag) {
// Disabled = attribute "disabled" exists
return tag.hasAttribute(this.disabledAttributeDefinition.getAttributeName());
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, true);
String value = null;
boolean checked = false;
Object boundValue = bindStatus.getValue();
final Class<?> valueType = bindStatus.getValueType();
if (Boolean.class.equals(valueType) || boolean.class.equals(valueType)) {
if (boundValue instanceof String) {
boundValue = Boolean.valueOf((String) boundValue);
}
final Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE);
value = "true";
checked = booleanValue.booleanValue();
} else {
value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"input(checkbox)\" tags " +
"when binding to non-boolean values");
}
checked = SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
}
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "checkbox"));
if (checked) {
StandardProcessorUtils.setAttribute(structureHandler, this.checkedAttributeDefinition, CHECKED_ATTR_NAME, CHECKED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.checkedAttributeDefinition.getAttributeName());
}
if (!isDisabled(tag)) {
/*
* Non-disabled checkboxes need an additional <input type="hidden"> in order to note their presence in
* the HTML document. Given unchecked checkboxes are not sent by browsers as a result of form submission,
* this is the only way to differentiate between a checkbox that is unchecked and a checkbox that was
* never displayed or is disabled.
*/
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenTagModel = modelFactory.createModel();
final String hiddenName = WebDataBinder.DEFAULT_FIELD_MARKER_PREFIX + name;
final String hiddenValue = "on";
final Map<String,String> hiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, "hidden");
hiddenAttributes.put(NAME_ATTR_NAME, hiddenName);
hiddenAttributes.put(VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, hiddenName, hiddenValue, "hidden"));
final IStandaloneElementTag hiddenTag =
modelFactory.createStandaloneElementTag(INPUT_TAG_NAME, hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenTagModel.add(hiddenTag);
if (this.renderHiddenMarkersBeforeCheckboxes) {
structureHandler.insertBefore(hiddenTagModel);
} else {
structureHandler.insertImmediatelyAfter(hiddenTagModel, false);
}
}
| 359
| 881
| 1,240
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringInputFileFieldTagProcessor.java
|
SpringInputFileFieldTagProcessor
|
doProcess
|
class SpringInputFileFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String FILE_INPUT_TYPE_ATTR_VALUE = "file";
public SpringInputFileFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { FILE_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
| 186
| 131
| 317
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringInputGeneralFieldTagProcessor.java
|
SpringInputGeneralFieldTagProcessor
|
doProcess
|
class SpringInputGeneralFieldTagProcessor
extends AbstractSpringFieldTagProcessor {
// HTML4 input types
public static final String TEXT_INPUT_TYPE_ATTR_VALUE = "text";
public static final String HIDDEN_INPUT_TYPE_ATTR_VALUE = "hidden";
// HTML5-specific input types
public static final String DATETIME_INPUT_TYPE_ATTR_VALUE = "datetime";
public static final String DATETIMELOCAL_INPUT_TYPE_ATTR_VALUE = "datetime-local";
public static final String DATE_INPUT_TYPE_ATTR_VALUE = "date";
public static final String MONTH_INPUT_TYPE_ATTR_VALUE = "month";
public static final String TIME_INPUT_TYPE_ATTR_VALUE = "time";
public static final String WEEK_INPUT_TYPE_ATTR_VALUE = "week";
public static final String NUMBER_INPUT_TYPE_ATTR_VALUE = "number";
public static final String RANGE_INPUT_TYPE_ATTR_VALUE = "range";
public static final String EMAIL_INPUT_TYPE_ATTR_VALUE = "email";
public static final String URL_INPUT_TYPE_ATTR_VALUE = "url";
public static final String SEARCH_INPUT_TYPE_ATTR_VALUE = "search";
public static final String TEL_INPUT_TYPE_ATTR_VALUE = "tel";
public static final String COLOR_INPUT_TYPE_ATTR_VALUE = "color";
private static final String[] ALL_TYPE_ATTR_VALUES =
new String[] {
null,
TEXT_INPUT_TYPE_ATTR_VALUE,
HIDDEN_INPUT_TYPE_ATTR_VALUE,
DATETIME_INPUT_TYPE_ATTR_VALUE,
DATETIMELOCAL_INPUT_TYPE_ATTR_VALUE,
DATE_INPUT_TYPE_ATTR_VALUE,
MONTH_INPUT_TYPE_ATTR_VALUE,
TIME_INPUT_TYPE_ATTR_VALUE,
WEEK_INPUT_TYPE_ATTR_VALUE,
NUMBER_INPUT_TYPE_ATTR_VALUE,
RANGE_INPUT_TYPE_ATTR_VALUE,
EMAIL_INPUT_TYPE_ATTR_VALUE,
URL_INPUT_TYPE_ATTR_VALUE,
SEARCH_INPUT_TYPE_ATTR_VALUE,
TEL_INPUT_TYPE_ATTR_VALUE,
COLOR_INPUT_TYPE_ATTR_VALUE
};
public SpringInputGeneralFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, ALL_TYPE_ATTR_VALUES, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private static boolean applyConversion(final String type) {
return !(type != null && ("number".equalsIgnoreCase(type) || "range".equalsIgnoreCase(type)));
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
// Thanks to precedence, this should have already been computed
final String type = tag.getAttributeValue(this.typeAttributeDefinition.getAttributeName());
// Apply the conversions (editor), depending on type (no conversion for "number" and "range"
// Also, no escaping needed as attribute values are always escaped by default
final String value =
applyConversion(type)?
SpringValueFormatter.getDisplayString(bindStatus.getValue(), bindStatus.getEditor(), true) :
SpringValueFormatter.getDisplayString(bindStatus.getActualValue(), true);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, type));
| 806
| 316
| 1,122
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringInputPasswordFieldTagProcessor.java
|
SpringInputPasswordFieldTagProcessor
|
doProcess
|
class SpringInputPasswordFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String PASSWORD_INPUT_TYPE_ATTR_VALUE = "password";
public SpringInputPasswordFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { PASSWORD_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, "", "password"));
| 192
| 178
| 370
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringInputRadioFieldTagProcessor.java
|
SpringInputRadioFieldTagProcessor
|
doProcess
|
class SpringInputRadioFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String RADIO_INPUT_TYPE_ATTR_VALUE = "radio";
public SpringInputRadioFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { RADIO_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, true);
final String value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"input(radio)\" tags");
}
final boolean checked =
SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "radio"));
if (checked) {
StandardProcessorUtils.setAttribute(structureHandler, this.checkedAttributeDefinition, CHECKED_ATTR_NAME, CHECKED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.checkedAttributeDefinition.getAttributeName());
}
| 196
| 340
| 536
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringMethodTagProcessor.java
|
SpringMethodTagProcessor
|
doProcess
|
class SpringMethodTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 990;
public static final String TARGET_ATTR_NAME = "method";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private static final String VALUE_ATTR_NAME = "value";
private AttributeDefinition targetAttributeDefinition;
public SpringMethodTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions 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>}
/*
* Determine if the HTTP method is supported by browsers (i.e. GET or POST).
*/
protected boolean isMethodBrowserSupported(final String method) {
return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method));
}
}
|
final String newAttributeValue = HtmlEscape.escapeHtml4Xml(expressionResult == null ? null : expressionResult.toString());
// Set the 'method' attribute, or remove it if evaluated to null
if (newAttributeValue == null || newAttributeValue.length() == 0) {
structureHandler.removeAttribute(this.targetAttributeDefinition.getAttributeName());
structureHandler.removeAttribute(attributeName);
} else {
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, newAttributeValue);
}
// If this th:action is in a <form> tag, we might need to add a hidden field for non-supported HTTP methods
if (newAttributeValue != null && "form".equalsIgnoreCase(tag.getElementCompleteName())) {
if (!isMethodBrowserSupported(newAttributeValue)) {
// Browsers only support HTTP GET and POST. If a different method
// has been specified, then Spring MVC allows us to specify it
// using a hidden input with name '_method' and set 'post' for the
// <form> tag.
StandardProcessorUtils.setAttribute(structureHandler, this.targetAttributeDefinition, TARGET_ATTR_NAME, "post");
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenMethodModel = modelFactory.createModel();
final String type = "hidden";
final String name = "_method";
final String value = RequestDataValueProcessorUtils.processFormFieldValue(context, name, newAttributeValue, type);
final Map<String,String> hiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, type);
hiddenAttributes.put(NAME_ATTR_NAME, name);
hiddenAttributes.put(VALUE_ATTR_NAME, value); // no need to escape
final IStandaloneElementTag hiddenMethodElementTag =
modelFactory.createStandaloneElementTag("input", hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenMethodModel.add(hiddenMethodElementTag);
structureHandler.insertImmediatelyAfter(hiddenMethodModel, false);
}
}
| 471
| 547
| 1,018
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringObjectTagProcessor.java
|
SpringObjectTagProcessor
|
validateSelectionValue
|
class SpringObjectTagProcessor extends AbstractStandardTargetSelectionTagProcessor {
public static final int ATTR_PRECEDENCE = 500;
public static final String ATTR_NAME = "object";
public SpringObjectTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected void validateSelectionValue(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IStandardExpression expression) {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> computeAdditionalLocalVariables(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IStandardExpression expression) {
// We set the (parsed) expression itself as a local variable because we might use it at the expression evaluator
return Collections.singletonMap(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION, (Object)expression);
}
}
|
if (expression == null || !(expression instanceof VariableExpression)) {
throw new TemplateProcessingException(
"The expression used for object selection is " + expression + ", which is not valid: " +
"only variable expressions (${...}) are allowed in '" + attributeName + "' attributes in " +
"Spring-enabled environments.");
}
| 311
| 92
| 403
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringOptionFieldTagProcessor.java
|
SpringOptionFieldTagProcessor
|
doProcess
|
class SpringOptionFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public SpringOptionFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, OPTION_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"option\" tags");
}
final boolean selected =
SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
StandardProcessorUtils.setAttribute(
structureHandler,
this.valueAttributeDefinition, VALUE_ATTR_NAME,
RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "option"));
if (selected) {
StandardProcessorUtils.setAttribute(structureHandler, this.selectedAttributeDefinition, SELECTED_ATTR_NAME, SELECTED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.selectedAttributeDefinition.getAttributeName());
}
| 144
| 239
| 383
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringOptionInSelectFieldTagProcessor.java
|
SpringOptionInSelectFieldTagProcessor
|
doProcess
|
class SpringOptionInSelectFieldTagProcessor extends AbstractElementTagProcessor {
// This is 1005 in order to make sure it is executed just before "value" (Spring's version) and especially "th:field"
public static final int ATTR_PRECEDENCE = 1005;
public static final String OPTION_TAG_NAME = "option";
public SpringOptionInSelectFieldTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, OPTION_TAG_NAME, false, null, false, ATTR_PRECEDENCE);
}
@Override
protected void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
final AttributeName selectAttrNameToAdd =
(AttributeName) context.getVariable(SpringSelectFieldTagProcessor.OPTION_IN_SELECT_ATTR_NAME);
if (selectAttrNameToAdd == null) {
// Nothing to do
return;
}
// It seems this <option> is inside a <select th:field="...">, and the processor for that "th:field" has left
// as a local variable the name and value of the attribute to be added
final String selectAttrValueToAdd =
(String) context.getVariable(SpringSelectFieldTagProcessor.OPTION_IN_SELECT_ATTR_VALUE);
if (tag.hasAttribute(selectAttrNameToAdd)) {
if (!selectAttrValueToAdd.equals(tag.getAttributeValue(selectAttrNameToAdd))) {
throw new TemplateProcessingException(
"If specified (which is not required), attribute \"" + selectAttrNameToAdd + "\" in " +
"\"option\" tag must have exactly the same value as in its containing \"select\" tag");
}
}
// This attribute value does not need to be escaped, because we are just "transporting" the th:field in the
// container <select> to its <option>'s, without any modifications. It will be executed (and its results
// escaped) later...
structureHandler.setAttribute(selectAttrNameToAdd.getCompleteAttributeNames()[0], selectAttrValueToAdd);
| 210
| 358
| 568
|
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringSelectFieldTagProcessor.java
|
SpringSelectFieldTagProcessor
|
doProcess
|
class SpringSelectFieldTagProcessor extends AbstractSpringFieldTagProcessor {
static final String OPTION_IN_SELECT_ATTR_NAME = "%%OPTION_IN_SELECT_ATTR_NAME%%";
static final String OPTION_IN_SELECT_ATTR_VALUE = "%%OPTION_IN_SELECT_ATTR_VALUE%%";
public SpringSelectFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, SELECT_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private final boolean isDisabled(final IProcessableElementTag tag) {
// Disabled = attribute "disabled" exists
return tag.hasAttribute(this.disabledAttributeDefinition.getAttributeName());
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
final boolean multiple = tag.hasAttribute(this.multipleAttributeDefinition.getAttributeName());
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
structureHandler.setLocalVariable(OPTION_IN_SELECT_ATTR_NAME, attributeName);
structureHandler.setLocalVariable(OPTION_IN_SELECT_ATTR_VALUE, attributeValue);
if (multiple && !isDisabled(tag)) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenMethodElementModel = modelFactory.createModel();
final String hiddenName = WebDataBinder.DEFAULT_FIELD_MARKER_PREFIX + name;
final String type = "hidden";
final String value =
RequestDataValueProcessorUtils.processFormFieldValue(context, hiddenName, "1", type);
final Map<String,String> hiddenAttributes = new LinkedHashMap<String, String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, type);
hiddenAttributes.put(NAME_ATTR_NAME, hiddenName);
hiddenAttributes.put(VALUE_ATTR_NAME, value);
final IStandaloneElementTag hiddenElementTag =
modelFactory.createStandaloneElementTag("input", hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenMethodElementModel.add(hiddenElementTag);
// We insert this hidden before because <select>'s are open element (with body), and if we insert it
// after the element, we would be inserting the <input type="hidden"> inside the <select>, which would
// incorrect...
structureHandler.insertBefore(hiddenMethodElementModel);
}
| 258
| 525
| 783
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringSrcTagProcessor.java
|
SpringSrcTagProcessor
|
doProcess
|
class SpringSrcTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String ATTR_NAME = "src";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringSrcTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE, false, true);
}
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, 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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processUrl(context, newAttributeValue);
// Set the real, non prefixed attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
| 341
| 121
| 462
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringTextareaFieldTagProcessor.java
|
SpringTextareaFieldTagProcessor
|
doProcess
|
class SpringTextareaFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public SpringTextareaFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, TEXTAREA_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
final String value = SpringValueFormatter.getDisplayString(bindStatus.getValue(), bindStatus.getEditor(), true);
String processedValue =
RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "textarea");
if (!StringUtils.isEmpty(processedValue)) {
final char c0 = processedValue.charAt(0);
if (c0 == '\n') {
processedValue = '\n' + processedValue;
} else if (c0 == '\r' && processedValue.length() > 1 && processedValue.charAt(1) == '\n') {
processedValue = "\r\n" + processedValue;
} else if (c0 == '\r') {
processedValue = '\r' + processedValue;
}
}
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
structureHandler.setBody((processedValue == null? "" : processedValue), false);
| 147
| 344
| 491
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringUErrorsTagProcessor.java
|
SpringUErrorsTagProcessor
|
doProcess
|
class SpringUErrorsTagProcessor extends AbstractAttributeTagProcessor {
private static final String ERROR_DELIMITER = "<br />";
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "uerrors";
public SpringUErrorsTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, ATTR_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 IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus.isError()) {
final StringBuilder strBuilder = new StringBuilder();
final String[] errorMsgs = bindStatus.getErrorMessages();
for (int i = 0; i < errorMsgs.length; i++) {
if (i > 0) {
strBuilder.append(ERROR_DELIMITER);
}
final String displayString = SpringValueFormatter.getDisplayString(errorMsgs[i], false);
strBuilder.append(displayString);
}
structureHandler.setBody(strBuilder.toString(), false);
// Just in case we also have a th:errorclass in this tag
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
} else {
structureHandler.removeElement();
}
| 200
| 240
| 440
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/processor/SpringValueTagProcessor.java
|
SpringValueTagProcessor
|
doProcess
|
class SpringValueTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
// This is 1010 in order to make sure it is executed after "name" and "type"
public static final int ATTR_PRECEDENCE = 1010;
public static final String TARGET_ATTR_NAME = "value";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private AttributeDefinition targetAttributeDefinition;
private AttributeDefinition fieldAttributeDefinition;
private AttributeDefinition typeAttributeDefinition;
private AttributeDefinition nameAttributeDefinition;
public SpringValueTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions in order to being able to use much
// faster methods for setting/replacing attributes on the ElementAttributes implementation
final String dialectPrefix = getMatchingAttributeName().getMatchingAttributeName().getPrefix();
this.targetAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TARGET_ATTR_NAME);
this.fieldAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, dialectPrefix, AbstractSpringFieldTagProcessor.ATTR_NAME);
this.typeAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TYPE_ATTR_NAME);
this.nameAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, NAME_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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed, but only in the case we don't also have
// a 'th:field' - in such case, we will let th:field do its job
if (!tag.hasAttribute(this.fieldAttributeDefinition.getAttributeName())) {
// We will need to know the 'name' and 'type' attribute values in order to (potentially) modify the 'value'
final String nameValue = tag.getAttributeValue(this.nameAttributeDefinition.getAttributeName());
final String typeValue = tag.getAttributeValue(this.typeAttributeDefinition.getAttributeName());
newAttributeValue =
RequestDataValueProcessorUtils.processFormFieldValue(context, nameValue, newAttributeValue, typeValue);
}
// Set the 'value' attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
| 557
| 269
| 826
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/requestdata/RequestDataValueProcessorUtils.java
|
RequestDataValueProcessorUtils
|
getExtraHiddenFields
|
class RequestDataValueProcessorUtils {
public static String processAction(
final ITemplateContext context, final String action, final String httpMethod) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return action;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processAction(action, httpMethod);
}
public static String processFormFieldValue(
final ITemplateContext context, final String name, final String value, final String type) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return value;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processFormFieldValue(name, value, type);
}
public static Map<String, String> getExtraHiddenFields(final ITemplateContext context) {<FILL_FUNCTION_BODY>}
public static String processUrl(final ITemplateContext context, final String url) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return url;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processUrl(url);
}
private RequestDataValueProcessorUtils() {
super();
}
}
|
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return null;
}
return thymeleafRequestContext.getRequestDataValueProcessor().getExtraHiddenFields();
| 394
| 77
| 471
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/templateresource/SpringResourceTemplateResource.java
|
SpringResourceTemplateResource
|
relative
|
class SpringResourceTemplateResource implements ITemplateResource {
private final Resource resource;
private final String characterEncoding;
public SpringResourceTemplateResource(
final ApplicationContext applicationContext, final String location, final String characterEncoding) {
super();
Validate.notNull(applicationContext, "Application Context cannot be null");
Validate.notEmpty(location, "Resource Location cannot be null or empty");
// Character encoding CAN be null (system default will be used)
this.resource = applicationContext.getResource(location);
this.characterEncoding = characterEncoding;
}
public SpringResourceTemplateResource(
final Resource resource, final String characterEncoding) {
super();
Validate.notNull(resource, "Resource cannot be null");
// Character encoding CAN be null (system default will be used)
this.resource = resource;
this.characterEncoding = characterEncoding;
}
public String getDescription() {
return this.resource.getDescription();
}
public String getBaseName() {
return computeBaseName(this.resource.getFilename());
}
public boolean exists() {
return this.resource.exists();
}
public Reader reader() throws IOException {
// Will never return null, but an IOException if not found
final InputStream inputStream = this.resource.getInputStream();
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>}
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 static final class SpringResourceInvalidRelativeTemplateResource implements ITemplateResource {
private final String originalResourceDescription;
private final String relativeLocation;
private final IOException ioException;
SpringResourceInvalidRelativeTemplateResource(
final String originalResourceDescription,
final String relativeLocation,
final IOException ioException) {
super();
this.originalResourceDescription = originalResourceDescription;
this.relativeLocation = relativeLocation;
this.ioException = ioException;
}
@Override
public String getDescription() {
return "Invalid relative resource for relative location \"" + this.relativeLocation +
"\" and original resource " + this.originalResourceDescription + ": " + this.ioException.getMessage();
}
@Override
public String getBaseName() {
return "Invalid relative resource for relative location \"" + this.relativeLocation +
"\" and original resource " + this.originalResourceDescription + ": " + this.ioException.getMessage();
}
@Override
public boolean exists() {
return false;
}
@Override
public Reader reader() throws IOException {
throw new IOException("Invalid relative resource", this.ioException);
}
@Override
public ITemplateResource relative(final String relativeLocation) {
return this;
}
@Override
public String toString() {
return getDescription();
}
}
}
|
final Resource relativeResource;
try {
relativeResource = this.resource.createRelative(relativeLocation);
} catch (final IOException e) {
// Given we have delegated the createRelative(...) mechanism to Spring, it's better if we don't do
// any assumptions on what this IOException means and simply return a resource object that returns
// no reader and exists() == false.
return new SpringResourceInvalidRelativeTemplateResource(getDescription(), relativeLocation, e);
}
return new SpringResourceTemplateResource(relativeResource, this.characterEncoding);
| 1,063
| 137
| 1,200
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/DetailedError.java
|
DetailedError
|
toString
|
class DetailedError {
private static final String GLOBAL_FIELD_NAME = "[global]";
private final String fieldName;
private final String code;
private final Object[] arguments;
private final String message;
public DetailedError(final String code, final Object[] arguments, final String message) {
this(GLOBAL_FIELD_NAME, code, arguments, message);
}
public DetailedError(
final String fieldName, final String code, final Object[] arguments, final String message) {
super();
Validate.notNull(fieldName, "Field name cannot be null");
Validate.notNull(message, "Message cannot be null");
this.fieldName = fieldName;
this.code = code;
this.arguments = arguments;
this.message = message;
}
public String getFieldName() {
return fieldName;
}
public String getCode() {
return code;
}
public Object[] getArguments() {
return arguments;
}
public String getMessage() {
return message;
}
public boolean isGlobal() {
return GLOBAL_FIELD_NAME.equalsIgnoreCase(this.fieldName);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(this.fieldName);
strBuilder.append(":");
strBuilder.append(this.message);
return strBuilder.toString();
| 337
| 55
| 392
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringContentTypeUtils.java
|
SpringContentTypeUtils
|
computeViewContentType
|
class SpringContentTypeUtils {
public static String computeViewContentType(
final IWebExchange webExchange, final String defaultContentType, final Charset defaultCharset) {<FILL_FUNCTION_BODY>}
private SpringContentTypeUtils() {
super();
}
}
|
if (webExchange == null) {
throw new IllegalArgumentException("Request cannot be null");
}
// First we will check if there is a content type already resolved by Spring's own content negotiation
// mechanism (see ContentNegotiatingViewResolver, which is autoconfigured in Spring Boot)
final MediaType negotiatedMediaType = (MediaType) webExchange.getAttributeValue(View.SELECTED_CONTENT_TYPE);
if (negotiatedMediaType != null && negotiatedMediaType.isConcrete()) {
final Charset negotiatedCharset = negotiatedMediaType.getCharset();
if (negotiatedCharset != null) {
return negotiatedMediaType.toString();
} else {
return ContentTypeUtils.combineContentTypeAndCharset(negotiatedMediaType.toString(), defaultCharset);
}
}
// We will apply the default charset here because, after all, we are in an HTTP environment, and
// the way charset is specified in HTTP is as a parameter in the same Content-Type HTTP header.
final String combinedContentType =
ContentTypeUtils.combineContentTypeAndCharset(defaultContentType, defaultCharset);
// Maybe there is no value for 'defaultValue', but anyway we might want to preserve the charset
// from the defaultContentType into the viewName-computed one
final Charset combinedCharset =
ContentTypeUtils.computeCharsetFromContentType(combinedContentType);
// If the request path offers clues on the content type that would be more appropriate (because it
// ends in ".html", ".xml", ".js", etc.), just use it
final String requestPathContentType =
ContentTypeUtils.computeContentTypeForRequestPath(webExchange.getRequest().getRequestPath(), combinedCharset);
if (requestPathContentType != null) {
return requestPathContentType;
}
// No way to determine a better/more specific content-type, so just return the (adequately combined) defaults
return combinedContentType;
| 81
| 497
| 578
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringReactiveModelAdditionsUtils.java
|
SpringReactiveModelAdditionsUtils
|
toReactiveModelAdditionName
|
class SpringReactiveModelAdditionsUtils {
private static final String REACTIVE_MODEL_ADDITIONS_PREFIX = "ThymeleafReactiveModelAdditions:";
public static boolean isReactiveModelAdditionName(final String name) {
return name != null && name.startsWith(REACTIVE_MODEL_ADDITIONS_PREFIX);
}
public static String fromReactiveModelAdditionName(final String name) {
if (!isReactiveModelAdditionName(name)) {
return name;
}
return name.substring(REACTIVE_MODEL_ADDITIONS_PREFIX.length());
}
public static String toReactiveModelAdditionName(final String name) {<FILL_FUNCTION_BODY>}
private SpringReactiveModelAdditionsUtils() {
super();
}
}
|
if (name == null) {
return null;
}
return REACTIVE_MODEL_ADDITIONS_PREFIX + name;
| 219
| 39
| 258
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringRequestUtils.java
|
SpringRequestUtils
|
checkViewNameNotInRequest
|
class SpringRequestUtils {
public static void checkViewNameNotInRequest(final String viewName, final IWebRequest request) {<FILL_FUNCTION_BODY>}
private static boolean containsExpression(final String text) {
final int textLen = text.length();
char c;
boolean expInit = false;
for (int i = 0; i < textLen; i++) {
c = text.charAt(i);
if (!expInit) {
if (c == '$' || c == '*' || c == '#' || c == '@' || c == '~') {
expInit = true;
}
} else {
if (c == '{') {
return true;
} else if (!Character.isWhitespace(c)) {
expInit = false;
}
}
}
return false;
}
private SpringRequestUtils() {
super();
}
}
|
final String vn = StringUtils.pack(viewName);
if (!containsExpression(vn)) {
// We are only worried about expressions coming from user input, so if the view name contains no
// expression at all, we should be safe at this stage.
return;
}
boolean found = false;
final String pathWithinApplication =
StringUtils.pack(UriEscape.unescapeUriPath(request.getPathWithinApplication()));
if (pathWithinApplication != null && containsExpression(pathWithinApplication)) {
// View name contains an expression, and it seems the path does too. This is too dangerous.
found = true;
}
if (!found) {
final Map<String,String[]> parameterMap = request.getParameterMap();
if (parameterMap != null && !parameterMap.isEmpty()) {
for (final String[] parameterValues : parameterMap.values()) {
for (int i = 0; !found && i < parameterValues.length; i++) {
final String parameterValue = StringUtils.pack(parameterValues[i]);
if (parameterValue != null && containsExpression(parameterValue) && vn.contains(parameterValue)) {
// Request parameter contains an expression, and it is contained in the view name. Too dangerous.
found = true;
}
}
if (found) {
break;
}
}
}
}
if (found) {
throw new TemplateProcessingException(
"View name contains an expression and so does either the URL path or one of the request " +
"parameters. This is forbidden in order to reduce the possibilities that direct user input " +
"is executed as a part of the view name.");
}
| 248
| 427
| 675
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringSelectedValueComparator.java
|
SpringSelectedValueComparator
|
exhaustiveCollectionCompare
|
class SpringSelectedValueComparator {
/*
* NOTE This code is based on org.springframework.web.servlet.tags.form.SelectedValueComparator as of Spring 5.0.0
* Original license is Apache License 2.0, which is the same as the license for this file.
* Original copyright notice is "Copyright 2002-2016 the original author or authors".
* Original authors are Rob Harrop and Juergen Hoeller.
*
* NOTE The code in this class has been adapted to use Thymeleaf's own BindStatus interfaces.
*/
public static boolean isSelected(final IThymeleafBindStatus bindStatus, final Object candidateValue) {
if (bindStatus == null) {
return (candidateValue == null);
}
// Check obvious equality matches with the candidate first,
// both with the rendered value and with the original value.
Object boundValue = bindStatus.getValue();
if (ObjectUtils.nullSafeEquals(boundValue, candidateValue)) {
return true;
}
Object actualValue = bindStatus.getActualValue();
if (actualValue != null && actualValue != boundValue &&
ObjectUtils.nullSafeEquals(actualValue, candidateValue)) {
return true;
}
if (actualValue != null) {
boundValue = actualValue;
} else if (boundValue == null) {
return false;
}
// Non-null value but no obvious equality with the candidate value:
// go into more exhaustive comparisons.
boolean selected = false;
if (boundValue.getClass().isArray()) {
selected = collectionCompare(CollectionUtils.arrayToList(boundValue), candidateValue, bindStatus);
} else if (boundValue instanceof Collection) {
selected = collectionCompare((Collection<?>) boundValue, candidateValue, bindStatus);
} else if (boundValue instanceof Map) {
selected = mapCompare((Map<?, ?>) boundValue, candidateValue, bindStatus);
}
if (!selected) {
selected = exhaustiveCompare(boundValue, candidateValue, bindStatus.getEditor(), null);
}
return selected;
}
private static boolean collectionCompare(
final Collection<?> boundCollection, final Object candidateValue, final IThymeleafBindStatus bindStatus) {
try {
if (boundCollection.contains(candidateValue)) {
return true;
}
} catch (ClassCastException ex) {
// Probably from a TreeSet - ignore.
}
return exhaustiveCollectionCompare(boundCollection, candidateValue, bindStatus);
}
private static boolean mapCompare(
final Map<?, ?> boundMap, final Object candidateValue, final IThymeleafBindStatus bindStatus) {
try {
if (boundMap.containsKey(candidateValue)) {
return true;
}
} catch (ClassCastException ex) {
// Probably from a TreeMap - ignore.
}
return exhaustiveCollectionCompare(boundMap.keySet(), candidateValue, bindStatus);
}
private static boolean exhaustiveCollectionCompare(
final Collection<?> collection, final Object candidateValue, final IThymeleafBindStatus bindStatus) {<FILL_FUNCTION_BODY>}
private static boolean exhaustiveCompare(
final Object boundValue, final Object candidate,
final PropertyEditor editor, final Map<PropertyEditor, Object> convertedValueCache) {
final String candidateDisplayString = SpringValueFormatter.getDisplayString(candidate, editor, false);
if (boundValue != null && boundValue.getClass().isEnum()) {
final Enum<?> boundEnum = (Enum<?>) boundValue;
final String enumCodeAsString = ObjectUtils.getDisplayString(boundEnum.name());
if (enumCodeAsString.equals(candidateDisplayString)) {
return true;
}
final String enumLabelAsString = ObjectUtils.getDisplayString(boundEnum.toString());
if (enumLabelAsString.equals(candidateDisplayString)) {
return true;
}
} else if (ObjectUtils.getDisplayString(boundValue).equals(candidateDisplayString)) {
return true;
} else if (editor != null && candidate instanceof String) {
// Try PE-based comparison (PE should *not* be allowed to escape creating thread)
final String candidateAsString = (String) candidate;
final Object candidateAsValue;
if (convertedValueCache != null && convertedValueCache.containsKey(editor)) {
candidateAsValue = convertedValueCache.get(editor);
} else {
editor.setAsText(candidateAsString);
candidateAsValue = editor.getValue();
if (convertedValueCache != null) {
convertedValueCache.put(editor, candidateAsValue);
}
}
if (ObjectUtils.nullSafeEquals(boundValue, candidateAsValue)) {
return true;
}
}
return false;
}
private SpringSelectedValueComparator() {
super();
}
}
|
final Map<PropertyEditor, Object> convertedValueCache = new HashMap<>(1);
PropertyEditor editor = null;
boolean candidateIsString = (candidateValue instanceof String);
if (!candidateIsString) {
editor = bindStatus.findEditor(candidateValue.getClass());
}
for (Object element : collection) {
if (editor == null && element != null && candidateIsString) {
editor = bindStatus.findEditor(element.getClass());
}
if (exhaustiveCompare(element, candidateValue, editor, convertedValueCache)) {
return true;
}
}
return false;
| 1,264
| 162
| 1,426
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringStandardExpressionUtils.java
|
SpringStandardExpressionUtils
|
containsSpELInstantiationOrStaticOrParam
|
class SpringStandardExpressionUtils {
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 containsSpELInstantiationOrStaticOrParam(final String expression) {<FILL_FUNCTION_BODY>}
private static boolean isPreviousStaticMarker(final String expression, final int idx) {
char c,c1;
int n = idx;
while (n-- != 0) {
c = expression.charAt(n);
if (c == 'T') {
if (n == 0) {
return true;
}
c1 = expression.charAt(n - 1);
return !isSafeIdentifierChar(c1);
} else if (!Character.isWhitespace(c)) {
return false;
}
}
return false;
}
private static boolean isSafeIdentifierChar(final char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
}
private SpringStandardExpressionUtils() {
super();
}
}
|
/*
* Checks whether the expression contains instantiation of objects ("new SomeClass") or makes use of
* static methods ("T(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
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;
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 == '(' && ((n - 1 >= 0) && isPreviousStaticMarker(exp, n))) {
return true;
}
}
return false;
| 370
| 641
| 1,011
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/util/SpringValueFormatter.java
|
SpringValueFormatter
|
getDisplayString
|
class SpringValueFormatter {
/*
* NOTE This code is based on org.springframework.web.servlet.tags.form.ValueFormatter as of Spring 5.0.0
* Original license is Apache License 2.0, which is the same as the license for this file.
* Original copyright notice is "Copyright 2002-2012 the original author or authors".
* Original authors are Rob Harrop and Juergen Hoeller.
*/
public static String getDisplayString(final Object value, final boolean htmlEscape) {
final String displayValue = ObjectUtils.getDisplayString(value);
return (htmlEscape ? HtmlUtils.htmlEscape(displayValue) : displayValue);
}
public static String getDisplayString(final Object value, final PropertyEditor propertyEditor, final boolean htmlEscape) {<FILL_FUNCTION_BODY>}
private SpringValueFormatter() {
super();
}
}
|
if (propertyEditor != null && !(value instanceof String)) {
try {
propertyEditor.setValue(value);
final String text = propertyEditor.getAsText();
if (text != null) {
return getDisplayString(text, htmlEscape);
}
} catch (final Throwable ex) {
// The PropertyEditor might not support this value... pass through.
}
}
return getDisplayString(value, htmlEscape);
| 244
| 119
| 363
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/web/webflux/MultiValueMapUtil.java
|
MultiValueMapUtil
|
cookieToStringArrayMultiMap
|
class MultiValueMapUtil {
static String[] EMPTY_VALUES = new String[0];
static Map<String,String[]> stringToStringArrayMultiMap(final MultiValueMap<String,String> multiValueMap) {
if (multiValueMap == null) {
return null;
}
final Map<String,String[]> stringArrayMap =
new LinkedHashMap<String,String[]>(multiValueMap.size() + 1, 1.0f);
for (final Map.Entry<String, List<String>> multiValueMapEntry : multiValueMap.entrySet()) {
final List<String> multiValueMapEntryValue = multiValueMapEntry.getValue();
stringArrayMap.put(
multiValueMapEntry.getKey(),
multiValueMapEntry.getValue().toArray(new String[multiValueMapEntryValue.size()]));
}
return Collections.unmodifiableMap(stringArrayMap);
}
static Map<String,String[]> cookieToStringArrayMultiMap(final MultiValueMap<String, HttpCookie> multiValueMap) {<FILL_FUNCTION_BODY>}
private MultiValueMapUtil() {
super();
}
}
|
if (multiValueMap == null) {
return null;
}
final Map<String,String[]> stringArrayMap =
new LinkedHashMap<String,String[]>(multiValueMap.size() + 1, 1.0f);
for (final Map.Entry<String, List<HttpCookie>> multiValueMapEntry : multiValueMap.entrySet()) {
stringArrayMap.put(
multiValueMapEntry.getKey(),
multiValueMapEntry.getValue().stream().map(HttpCookie::getValue).toArray(String[]::new));
}
return Collections.unmodifiableMap(stringArrayMap);
| 297
| 157
| 454
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/web/webflux/SpringWebFluxWebApplication.java
|
SpringWebFluxWebApplication
|
removeAttribute
|
class SpringWebFluxWebApplication implements ISpringWebFluxWebApplication {
// This class is made NOT final so that it can be proxied by Dependency Injection frameworks
/*
* There is no equivalent in Spring WebFlux to an application-level attribute container (e.g. ServletContext).
* So for the attribute part of this interface, this implementation will simply keep an empty attribute map.
*/
private final ReactiveAdapterRegistry reactiveAdapterRegistry;
SpringWebFluxWebApplication(final ReactiveAdapterRegistry reactiveAdapterRegistry) {
super();
// reactiveAdapterRegistry can be null
this.reactiveAdapterRegistry = reactiveAdapterRegistry;
}
public static SpringWebFluxWebApplication buildApplication(final ReactiveAdapterRegistry reactiveAdapterRegistry) {
// reactiveAdapterRegistry can be null
return new SpringWebFluxWebApplication(reactiveAdapterRegistry);
}
public ISpringWebFluxWebExchange buildExchange(
final ServerWebExchange exchange, final Locale locale, final MediaType mediaType, final Charset charset) {
Validate.notNull(exchange, "ServerWebExchange cannot be null");
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(mediaType, "Media Type cannot be null");
Validate.notNull(charset, "Charset cannot be null");
final SpringWebFluxWebRequest request = new SpringWebFluxWebRequest(exchange.getRequest());
return new SpringWebFluxWebExchange(request, this, exchange, locale, mediaType, charset);
}
@Override
public ReactiveAdapterRegistry getReactiveAdapterRegistry() {
return this.reactiveAdapterRegistry;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
throw new UnsupportedOperationException("No support for application-level attributes in Spring WebFlux");
}
@Override
public void removeAttribute(final String name) {<FILL_FUNCTION_BODY>}
@Override
public boolean resourceExists(final String path) {
Validate.notNull(path, "Path cannot be null");
throw new UnsupportedOperationException("No support for webapplication-based resource resolution in Spring WebFlux");
}
@Override
public InputStream getResourceAsStream(final String path) {
Validate.notNull(path, "Path cannot be null");
throw new UnsupportedOperationException("No support for webapplication-based resource resolution in Spring WebFlux");
}
}
|
Validate.notNull(name, "Name cannot be null");
throw new UnsupportedOperationException("No support for application-level attributes in Spring WebFlux");
| 676
| 41
| 717
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/web/webflux/SpringWebFluxWebExchange.java
|
SpringWebFluxWebExchange
|
getSession
|
class SpringWebFluxWebExchange implements ISpringWebFluxWebExchange {
private final SpringWebFluxWebRequest webRequest;
private final SpringWebFluxWebApplication webApplication;
private SpringWebFluxWebSession webSession; // can be null, and is always lazily initialized
private boolean webSessionInitialized;
private final ServerWebExchange exchange;
private final Locale locale;
private final MediaType mediaType;
private final Charset charset;
SpringWebFluxWebExchange(final SpringWebFluxWebRequest webRequest,
final SpringWebFluxWebApplication webApplication,
final ServerWebExchange exchange,
final Locale locale,
final MediaType mediaType,
final Charset charset) {
super();
Validate.notNull(webRequest, "Request cannot be null");
Validate.notNull(webApplication, "Application cannot be null");
Validate.notNull(exchange, "Server Web Exchange cannot be null");
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(mediaType, "Media Type cannot be null");
Validate.notNull(charset, "Charset cannot be null");
this.webRequest = webRequest;
this.webApplication = webApplication;
this.exchange = exchange;
this.locale = locale;
this.mediaType = mediaType;
this.charset = charset;
// Session is lazily initialized because it requires the model to have been resolved (from Mono<Session>)
this.webSession = null;
this.webSessionInitialized = false;
}
@Override
public ISpringWebFluxWebRequest getRequest() {
return this.webRequest;
}
@Override
public ISpringWebFluxWebSession getSession() {<FILL_FUNCTION_BODY>}
@Override
public ISpringWebFluxWebApplication getApplication() {
return this.webApplication;
}
@Override
public Principal getPrincipal() {
// ServerWebExchange returns a Mono<Principal>, which SpringStandardDialect makes sure to ask reactor to
// resolve before the view gets executed.
// NOTE this will not be available until just before the view starts executing
return this.exchange.getAttribute(SpringContextUtils.WEB_EXCHANGE_PRINCIPAL_ATTRIBUTE_NAME);
}
@Override
public Locale getLocale() {
// We prefer this to the one established in ServerWebExchange, as the in Spring WebFlux environments
// the view that is being processed might establish its own value for the locale.
return this.locale;
}
@Override
public String getContentType() {
return this.mediaType.toString();
}
@Override
public String getCharacterEncoding() {
return this.charset.name();
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(this.exchange.getAttributes());
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.exchange.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
if (value == null) {
this.exchange.getAttributes().remove(name);
} else {
this.exchange.getAttributes().put(name, value);
}
}
@Override
public void removeAttribute(final String name) {
Validate.notNull(name, "Name cannot be null");
this.exchange.getAttributes().remove(name);
}
@Override
public Object getNativeExchangeObject() {
return this.exchange;
}
@Override
public String transformURL(final String url) {
return this.exchange.transformUrl(url);
}
}
|
// ServerWebExchange returns a Mono<WebSession>, which SpringStandardDialect makes sure to ask reactor to
// resolve before the view gets executed.
// NOTE this will not be available until just before the view starts executing
if (!this.webSessionInitialized) {
final WebSession session = this.exchange.getAttribute(SpringContextUtils.WEB_SESSION_ATTRIBUTE_NAME);
if (session != null) {
this.webSession = new SpringWebFluxWebSession(session);
this.webSessionInitialized = true;
}
}
return this.webSession;
| 1,018
| 154
| 1,172
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/web/webflux/SpringWebFluxWebSession.java
|
SpringWebFluxWebSession
|
setAttributeValue
|
class SpringWebFluxWebSession implements ISpringWebFluxWebSession {
private final WebSession session;
SpringWebFluxWebSession(final WebSession session) {
super();
Validate.notNull(session, "Session cannot be null");
this.session = session;
}
@Override
public boolean exists() {
return this.session.isStarted();
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(this.session.getAttributes());
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.session.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {<FILL_FUNCTION_BODY>}
@Override
public void removeAttribute(final String name) {
Validate.notNull(name, "Name cannot be null");
this.session.getAttributes().remove(name);
}
@Override
public Object getNativeSessionObject() {
return this.session;
}
}
|
Validate.notNull(name, "Name cannot be null");
if (value == null) {
this.session.getAttributes().remove(name);
} else {
this.session.getAttributes().put(name, value);
}
| 300
| 64
| 364
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/webflow/view/AjaxThymeleafView.java
|
AjaxThymeleafView
|
getRenderFragments
|
class AjaxThymeleafView extends ThymeleafView implements AjaxEnabledView {
private static final Logger vlogger = LoggerFactory.getLogger(AjaxThymeleafView.class);
private static final String FRAGMENTS_PARAM = "fragments";
private AjaxHandler ajaxHandler = null;
public AjaxThymeleafView() {
super();
}
public AjaxHandler getAjaxHandler() {
return this.ajaxHandler;
}
public void setAjaxHandler(final AjaxHandler ajaxHandler) {
this.ajaxHandler = ajaxHandler;
}
@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AjaxHandler templateAjaxHandler = getAjaxHandler();
if (templateAjaxHandler == null) {
throw new ConfigurationException("[THYMELEAF] AJAX Handler set into " +
AjaxThymeleafView.class.getSimpleName() + " instance for template " +
getTemplateName() + " is null.");
}
if (templateAjaxHandler.isAjaxRequest(request, response)) {
final Set<String> fragmentsToRender = getRenderFragments(model, request, response);
if (fragmentsToRender == null || fragmentsToRender.size() == 0) {
vlogger.warn("[THYMELEAF] An Ajax request was detected, but no fragments were specified to be re-rendered. "
+ "Falling back to full page render. This can cause unpredictable results when processing "
+ "the ajax response on the client.");
super.render(model, request, response);
return;
}
super.renderFragment(fragmentsToRender, model, request, response);
} else {
super.render(model, request, response);
}
}
@SuppressWarnings({ "rawtypes", "unused" })
protected Set<String> getRenderFragments(
final Map model, final HttpServletRequest request, final HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
final String fragmentsParam = request.getParameter(FRAGMENTS_PARAM);
final String[] renderFragments = StringUtils.commaDelimitedListToStringArray(fragmentsParam);
if (renderFragments.length == 0) {
return null;
}
if (renderFragments.length == 1) {
return Collections.singleton(renderFragments[0]);
}
return new HashSet<String>(Arrays.asList(renderFragments));
| 565
| 124
| 689
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public java.lang.String getMarkupSelector() ,public void render(Map<java.lang.String,?>, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) throws java.lang.Exception,public void setMarkupSelector(java.lang.String) <variables>private Set<java.lang.String> markupSelectors,private static final non-sealed java.lang.String pathVariablesSelector
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/webflow/view/AjaxThymeleafViewResolver.java
|
AjaxThymeleafViewResolver
|
createView
|
class AjaxThymeleafViewResolver
extends ThymeleafViewResolver {
private static final Logger vrlogger = LoggerFactory.getLogger(AjaxThymeleafViewResolver.class);
private AjaxHandler ajaxHandler = new DefaultAjaxHandler();
public AjaxThymeleafViewResolver() {
super();
}
/**
* <p>
* Return the AJAX handler (from Spring Javascript) used
* to determine whether a request is an AJAX request or not
* in views resolved by this resolver.
* </p>
* <p>
* An instance of {@link DefaultAjaxHandler} is set by default.
* </p>
*
* @return the AJAX handler.
*/
public AjaxHandler getAjaxHandler() {
return this.ajaxHandler;
}
/**
* <p>
* Sets the AJAX handler (from Spring Javascript) used
* to determine whether a request is an AJAX request or not
* in views resolved by this resolver.
* </p>
* <p>
* An instance of {@link DefaultAjaxHandler} is set by default.
* </p>
*
* @param ajaxHandler the AJAX handler.
*/
public void setAjaxHandler(final AjaxHandler ajaxHandler) {
this.ajaxHandler = ajaxHandler;
}
@Override
protected View createView(final String viewName, final Locale locale) throws Exception {<FILL_FUNCTION_BODY>}
private static class AjaxRedirectView extends RedirectView {
private static final Logger vlogger = LoggerFactory.getLogger(AjaxRedirectView.class);
private AjaxHandler ajaxHandler = new DefaultAjaxHandler();
AjaxRedirectView(final AjaxHandler ajaxHandler, final String redirectUrl,
final boolean redirectContextRelative, final boolean redirectHttp10Compatible) {
super(redirectUrl, redirectContextRelative, redirectHttp10Compatible);
this.ajaxHandler = ajaxHandler;
}
@Override
protected void sendRedirect(final HttpServletRequest request, final HttpServletResponse response,
final String targetUrl, final boolean http10Compatible)
throws IOException {
if (this.ajaxHandler == null) {
throw new ConfigurationException("[THYMELEAF] AJAX Handler set into " +
AjaxThymeleafViewResolver.class.getSimpleName() + " instance is null.");
}
if (this.ajaxHandler.isAjaxRequest(request, response)) {
if (vlogger.isTraceEnabled()) {
vlogger.trace(
"[THYMELEAF] RedirectView for URL \"{}\" is an AJAX request. AjaxHandler of class {} " +
"will be in charge of processing the request.", targetUrl, this.ajaxHandler.getClass().getName());
}
this.ajaxHandler.sendAjaxRedirect(targetUrl, request, response, false);
} else {
vlogger.trace(
"[THYMELEAF] RedirectView for URL \"{}\" is not an AJAX request. Request will be handled " +
"as a normal redirect", targetUrl);
super.sendRedirect(request, response, targetUrl, http10Compatible);
}
}
}
}
|
if (!canHandle(viewName, locale)) {
return null;
}
if (this.ajaxHandler == null) {
throw new ConfigurationException("[THYMELEAF] AJAX Handler set into " +
AjaxThymeleafViewResolver.class.getSimpleName() + " instance is null.");
}
// Check for special "redirect:" prefix.
if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
vrlogger.trace(
"[THYMELEAF] View {} is a redirect. An AJAX-enabled RedirectView implementation will " +
"be handling the request.", viewName);
final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());
return new AjaxRedirectView(
this.ajaxHandler, redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
}
final View view = super.createView(viewName, locale);
if (view instanceof AjaxEnabledView) {
// Set the AJAX handler into view, if it is an AjaxThymeleafView.
final AjaxEnabledView ajaxEnabledView = (AjaxEnabledView) view;
if (ajaxEnabledView.getAjaxHandler() == null && getAjaxHandler() != null) {
ajaxEnabledView.setAjaxHandler(getAjaxHandler());
}
}
return view;
| 896
| 372
| 1,268
|
<methods>public void <init>() ,public void addStaticVariable(java.lang.String, java.lang.Object) ,public boolean getAlwaysProcessRedirectAndForward() ,public java.lang.String getCharacterEncoding() ,public java.lang.String getContentType() ,public java.lang.String[] getExcludedViewNames() ,public boolean getForceContentType() ,public int getOrder() ,public boolean getProducePartialOutputWhileProcessing() ,public Map<java.lang.String,java.lang.Object> getStaticVariables() ,public org.thymeleaf.spring5.ISpringTemplateEngine getTemplateEngine() ,public java.lang.String[] getViewNames() ,public boolean isRedirectContextRelative() ,public boolean isRedirectHttp10Compatible() ,public void setAlwaysProcessRedirectAndForward(boolean) ,public void setCharacterEncoding(java.lang.String) ,public void setContentType(java.lang.String) ,public void setExcludedViewNames(java.lang.String[]) ,public void setForceContentType(boolean) ,public void setOrder(int) ,public void setProducePartialOutputWhileProcessing(boolean) ,public void setRedirectContextRelative(boolean) ,public void setRedirectHttp10Compatible(boolean) ,public void setStaticVariables(Map<java.lang.String,?>) ,public void setTemplateEngine(org.thymeleaf.spring5.ISpringTemplateEngine) ,public void setViewClass(Class<? extends org.thymeleaf.spring5.view.AbstractThymeleafView>) ,public void setViewNames(java.lang.String[]) <variables>public static final java.lang.String FORWARD_URL_PREFIX,public static final java.lang.String REDIRECT_URL_PREFIX,private boolean alwaysProcessRedirectAndForward,private java.lang.String characterEncoding,private java.lang.String contentType,private java.lang.String[] excludedViewNames,private boolean forceContentType,private int order,private boolean producePartialOutputWhileProcessing,private boolean redirectContextRelative,private boolean redirectHttp10Compatible,private final Map<java.lang.String,java.lang.Object> staticVariables,private org.thymeleaf.spring5.ISpringTemplateEngine templateEngine,private Class<? extends org.thymeleaf.spring5.view.AbstractThymeleafView> viewClass,private java.lang.String[] viewNames,private static final org.slf4j.Logger vrlogger
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/webflow/view/FlowAjaxThymeleafView.java
|
FlowAjaxThymeleafView
|
getRenderFragments
|
class FlowAjaxThymeleafView extends AjaxThymeleafView {
public FlowAjaxThymeleafView() {
super();
}
@Override
@SuppressWarnings("rawtypes")
protected Set<String> getRenderFragments(
final Map model, final HttpServletRequest request, final HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
final RequestContext context = RequestContextHolder.getRequestContext();
if (context == null) {
return super.getRenderFragments(model, request, response);
}
final String[] fragments = (String[]) context.getFlashScope().get(View.RENDER_FRAGMENTS_ATTRIBUTE);
if (fragments == null || fragments.length == 0) {
return super.getRenderFragments(model, request, response);
}
if (fragments.length == 1) {
return Collections.singleton(fragments[0]);
}
return new HashSet<String>(Arrays.asList(fragments));
| 119
| 172
| 291
|
<methods>public void <init>() ,public org.springframework.webflow.context.servlet.AjaxHandler getAjaxHandler() ,public void render(Map<java.lang.String,?>, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) throws java.lang.Exception,public void setAjaxHandler(org.springframework.webflow.context.servlet.AjaxHandler) <variables>private static final java.lang.String FRAGMENTS_PARAM,private org.springframework.webflow.context.servlet.AjaxHandler ajaxHandler,private static final org.slf4j.Logger vlogger
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/context/SpringContextUtils.java
|
SpringContextUtils
|
getRequestContext
|
class SpringContextUtils {
/**
* <p>
* This is the name of the model attribute that will hold the (asychronously resolved)
* {@code WebSession} object in order to be used whenever needed, avoiding the need to block
* for obtaining it from the {@code ServerWebExchange}.
* </p>
* <p>
* Note resolving the {@code WebSession} from the reactive {@code Mono<WebSession>} stream does
* mean the creation of a {@code WebSession} instance, but not the real creation of a persisted session
* sent to the browser.
* </p>
* <p>
* Value: {@code "thymeleafWebSession"}
* </p>
*
* @see org.springframework.web.server.WebSession
*/
public static final String WEB_SESSION_ATTRIBUTE_NAME = "thymeleafWebSession";
/**
* <p>
* This is the name of the model attribute that will hold the (asychronously resolved)
* {@code Principal} object in order to be used whenever needed, avoiding the need to block
* for obtaining it from the {@code ServerWebExchange}.
* </p>
* <p>
* Value: {@code "thymeleafWebExchangePrincipal"}
* </p>
*
* @see org.springframework.web.server.ServerWebExchange
* @see java.security.Principal
*
* @since 3.1.0
*/
public static final String WEB_EXCHANGE_PRINCIPAL_ATTRIBUTE_NAME = "thymeleafWebExchangePrincipal";
/**
* <p>
* Get the {@link ApplicationContext} from the Thymeleaf template context.
* </p>
* <p>
* Note that the application context might not be always accessible (and thus this method
* can return {@code null}). Application Context will be accessible when the template is being executed
* as a Spring View, or else when an object of class {@link ThymeleafEvaluationContext} has been
* explicitly set into the {@link ITemplateContext} {@code context} with variable name
* {@link ThymeleafEvaluationContext#THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME}.
* </p>
*
* @param context the template context.
* @return the application context, or {@code null} if it could not be accessed.
*/
public static ApplicationContext getApplicationContext(final ITemplateContext context) {
if (context == null) {
return null;
}
// The ThymeleafEvaluationContext is set into the model by ThymeleafView (or wrapped by the SPEL evaluator)
final IThymeleafEvaluationContext evaluationContext =
(IThymeleafEvaluationContext) context.getVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME);
if (evaluationContext == null || !(evaluationContext instanceof ThymeleafEvaluationContext)) {
return null;
}
// Only when the evaluation context is a ThymeleafEvaluationContext we can access the ApplicationContext.
// The reason is it could also be a wrapper on another EvaluationContext implementation, created at the
// SPELVariableExpressionEvaluator on-the-fly (where ApplicationContext is not available because there might
// even not exist one), instead of at ThymeleafView (where we are sure we are executing a Spring View and
// have an ApplicationContext available).
return ((ThymeleafEvaluationContext)evaluationContext).getApplicationContext();
}
/**
* <p>
* Get the {@link IThymeleafRequestContext} from the Thymeleaf context.
* </p>
* <p>
* The returned object is a wrapper on the Spring request context that hides the fact of this request
* context corresponding to a Spring WebMVC or Spring WebFlux application.
* </p>
* <p>
* This will be done by looking for a context variable called
* {@link SpringContextVariableNames#THYMELEAF_REQUEST_CONTEXT}.
* </p>
*
* @param context the context
* @return the thymeleaf request context
*/
public static IThymeleafRequestContext getRequestContext(final IExpressionContext context) {<FILL_FUNCTION_BODY>}
private SpringContextUtils() {
super();
}
}
|
if (context == null) {
return null;
}
return (IThymeleafRequestContext) context.getVariable(SpringContextVariableNames.THYMELEAF_REQUEST_CONTEXT);
| 1,170
| 54
| 1,224
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/context/webflux/ReactiveContextVariableUtils.java
|
ReactiveContextVariableUtils
|
computePublisherValue
|
class ReactiveContextVariableUtils {
/**
* <p>
* Lazily resolve the reactive asynchronous object into a {@link Publisher}.
* </p>
* <p>
* The main aim of this method is to mirror the mechanism used by Spring for resolving
* asynchronous variables at the model of views (see Spring's
* {@link org.springframework.web.reactive.result.view.ViewResolutionResultHandler}):
* </p>
* <ul>
* <li>{@code Flux<T>} or other <em>multi-valued</em> streams are resolved as
* {@code List<T>} so that they are <em>iterable</em>.</li>
* <li>{@code Mono<T>} or other <em>single-valued</em> streams are resolved as
* {@code T} so that they are directly referenceable just like any other object.</li>
* </ul>
*
* @param asyncObj the asynchronous object being wrapped by this lazy variable.
* @param reactiveAdapterRegistry the Spring {@link ReactiveAdapterRegistry}.
* @return the resolved {@link Publisher}.
*/
static Publisher<Object> computePublisherValue(
final Object asyncObj, final ReactiveAdapterRegistry reactiveAdapterRegistry) {<FILL_FUNCTION_BODY>}
private ReactiveContextVariableUtils() {
super();
}
}
|
if (asyncObj instanceof Flux<?> || asyncObj instanceof Mono<?>) {
// If the async object is a Flux or a Mono, we don't need the ReactiveAdapterRegistry (and we allow
// initialization to happen without the registry, which is not possible with other Publisher<?>
// implementations.
return (Publisher<Object>) asyncObj;
}
if (reactiveAdapterRegistry == null) {
throw new IllegalArgumentException(
"Could not initialize lazy reactive context variable (data driver or explicitly-set " +
"reactive wrapper): Value is of class " + asyncObj.getClass().getName() +", but no " +
"ReactiveAdapterRegistry has been set. This can happen if this context variable is used " +
"for rendering a template without going through a " +
ThymeleafReactiveView.class.getSimpleName() + " or if there is no " +
"ReactiveAdapterRegistry bean registered at the application context. In such cases, it is " +
"required that the wrapped lazy variable values are instances of either " +
Flux.class.getName() + " or " + Mono.class.getName() + ".");
}
final ReactiveAdapter adapter = reactiveAdapterRegistry.getAdapter(null, asyncObj);
if (adapter != null) {
final Publisher<Object> publisher = adapter.toPublisher(asyncObj);
if (adapter.isMultiValue()) {
return Flux.from(publisher);
} else {
return Mono.from(publisher);
}
}
throw new IllegalArgumentException(
"Reactive context variable (data driver or explicitly-set reactive wrapper) is of " +
"class " + asyncObj.getClass().getName() +", but the ReactiveAdapterRegistry " +
"does not contain a valid adapter able to convert it into a supported reactive data stream.");
| 375
| 467
| 842
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/context/webflux/SpringWebFluxThymeleafRequestDataValueProcessor.java
|
SpringWebFluxThymeleafRequestDataValueProcessor
|
processFormFieldValue
|
class SpringWebFluxThymeleafRequestDataValueProcessor implements IThymeleafRequestDataValueProcessor {
private final RequestDataValueProcessor requestDataValueProcessor;
private final ServerWebExchange exchange;
SpringWebFluxThymeleafRequestDataValueProcessor(
final RequestDataValueProcessor requestDataValueProcessor, final ServerWebExchange exchange) {
super();
this.requestDataValueProcessor = requestDataValueProcessor;
this.exchange = exchange;
}
@Override
public String processAction(final String action, final String httpMethod) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return action;
}
return this.requestDataValueProcessor.processAction(this.exchange, action, httpMethod);
}
@Override
public String processFormFieldValue(final String name, final String value, final String type) {<FILL_FUNCTION_BODY>}
@Override
public Map<String, String> getExtraHiddenFields() {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return null;
}
return this.requestDataValueProcessor.getExtraHiddenFields(this.exchange);
}
@Override
public String processUrl(final String url) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return url;
}
return this.requestDataValueProcessor.processUrl(this.exchange, url);
}
}
|
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return value;
}
return this.requestDataValueProcessor.processFormFieldValue(this.exchange, name, value, type);
| 398
| 65
| 463
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/context/webmvc/SpringWebMvcThymeleafRequestDataValueProcessor.java
|
SpringWebMvcThymeleafRequestDataValueProcessor
|
processFormFieldValue
|
class SpringWebMvcThymeleafRequestDataValueProcessor implements IThymeleafRequestDataValueProcessor {
private final RequestDataValueProcessor requestDataValueProcessor;
private final HttpServletRequest httpServletRequest;
SpringWebMvcThymeleafRequestDataValueProcessor(
final RequestDataValueProcessor requestDataValueProcessor, final HttpServletRequest httpServletRequest) {
super();
this.requestDataValueProcessor = requestDataValueProcessor;
this.httpServletRequest = httpServletRequest;
}
@Override
public String processAction(final String action, final String httpMethod) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return action;
}
return this.requestDataValueProcessor.processAction(this.httpServletRequest, action, httpMethod);
}
@Override
public String processFormFieldValue(final String name, final String value, final String type) {<FILL_FUNCTION_BODY>}
@Override
public Map<String, String> getExtraHiddenFields() {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return null;
}
return this.requestDataValueProcessor.getExtraHiddenFields(this.httpServletRequest);
}
@Override
public String processUrl(final String url) {
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return url;
}
return this.requestDataValueProcessor.processUrl(this.httpServletRequest, url);
}
}
|
if (this.requestDataValueProcessor == null) {
// The presence of a Request Data Value Processor is optional
return value;
}
return this.requestDataValueProcessor.processFormFieldValue(this.httpServletRequest, name, value, type);
| 408
| 66
| 474
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/Mvc.java
|
Spring41MethodArgumentBuilderWrapper
|
encode
|
class Spring41MethodArgumentBuilderWrapper implements MethodArgumentBuilderWrapper {
private final org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodArgumentBuilder builder;
private Spring41MethodArgumentBuilderWrapper(
final org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodArgumentBuilder builder) {
super();
this.builder = builder;
}
public MethodArgumentBuilderWrapper arg(final int index, final Object value) {
return new Spring41MethodArgumentBuilderWrapper(this.builder.arg(index, value));
}
public MethodArgumentBuilderWrapper encode() {<FILL_FUNCTION_BODY>}
public String build() {
return this.builder.build();
}
public String buildAndExpand(final Object... uriVariables) {
return this.builder.buildAndExpand(uriVariables);
}
}
|
if (!SpringVersionUtils.isSpringAtLeast(5,0,8)) {
throw new IllegalStateException(String.format(
"At least Spring version 5.0.8.RELEASE is needed for executing " +
"MvcUriComponentsBuilder#encode() but detected Spring version is %s.",
SpringVersionUtils.getSpringVersion()));
}
return new Spring41MethodArgumentBuilderWrapper(this.builder.encode());
| 236
| 112
| 348
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/SPELContextMapWrapper.java
|
SPELContextMapWrapper
|
entrySet
|
class SPELContextMapWrapper implements Map {
private static final String REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME = "param";
private final IContext context;
private final IThymeleafEvaluationContext evaluationContext;
SPELContextMapWrapper(final IContext context, final IThymeleafEvaluationContext evaluationContext) {
super();
this.context = context;
this.evaluationContext = evaluationContext;
}
public int size() {
throw new TemplateProcessingException(
"Cannot call #size() on an " + IContext.class.getSimpleName() + " implementation");
}
public boolean isEmpty() {
throw new TemplateProcessingException(
"Cannot call #isEmpty() on an " + IContext.class.getSimpleName() + " implementation");
}
public boolean containsKey(final Object key) {
if (this.evaluationContext.isVariableAccessRestricted()) {
if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(key)) {
throw new TemplateProcessingException(
"Access to variable \"" + key + "\" is forbidden in this context. Note some restrictions apply to " +
"variable access. For example, direct access to request parameters is forbidden in preprocessing and " +
"unescaped expressions, in TEXT template mode, in fragment insertion specifications and " +
"in some specific attribute processors.");
}
}
// We will be NOT calling this.context.containsVariable(key) as it could be very inefficient in web
// environments (based on HttpServletRequest#getAttributeName()), so we will just consider that every possible
// element exists in an IContext, and simply return null for those not found
return this.context != null;
}
public boolean containsValue(final Object value) {
throw new TemplateProcessingException(
"Cannot call #containsValue(value) on an " + IContext.class.getSimpleName() + " implementation");
}
public Object get(final Object key) {
if (this.context == null) {
throw new TemplateProcessingException("Cannot read property on null target");
}
return this.context.getVariable(key == null? null : key.toString());
}
public Object put(final Object key, final Object value) {
throw new TemplateProcessingException(
"Cannot call #put(key,value) on an " + IContext.class.getSimpleName() + " implementation");
}
public Object remove(final Object key) {
throw new TemplateProcessingException(
"Cannot call #remove(key) on an " + IContext.class.getSimpleName() + " implementation");
}
public void putAll(final Map m) {
throw new TemplateProcessingException(
"Cannot call #putAll(m) on an " + IContext.class.getSimpleName() + " implementation");
}
public void clear() {
throw new TemplateProcessingException(
"Cannot call #clear() on an " + IContext.class.getSimpleName() + " implementation");
}
public Set keySet() {
throw new TemplateProcessingException(
"Cannot call #keySet() on an " + IContext.class.getSimpleName() + " implementation");
}
public Collection values() {
throw new TemplateProcessingException(
"Cannot call #values() on an " + IContext.class.getSimpleName() + " implementation");
}
public Set<Entry> entrySet() {<FILL_FUNCTION_BODY>}
}
|
throw new TemplateProcessingException(
"Cannot call #entrySet() on an " + IContext.class.getSimpleName() + " implementation");
| 935
| 38
| 973
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/SPELContextPropertyAccessor.java
|
SPELContextPropertyAccessor
|
read
|
class SPELContextPropertyAccessor implements PropertyAccessor {
private static final Logger LOGGER = LoggerFactory.getLogger(SPELContextPropertyAccessor.class);
static final SPELContextPropertyAccessor INSTANCE = new SPELContextPropertyAccessor();
private static final String REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME = "param";
private static final Class<?>[] TARGET_CLASSES = new Class<?>[] { IContext.class };
SPELContextPropertyAccessor() {
super();
}
public Class<?>[] getSpecificTargetClasses() {
return TARGET_CLASSES;
}
public boolean canRead(final EvaluationContext context, final Object target, final String name)
throws AccessException {
if (context instanceof IThymeleafEvaluationContext) {
if (((IThymeleafEvaluationContext) context).isVariableAccessRestricted()) {
if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(name)) {
throw new AccessException(
"Access to variable \"" + name + "\" is forbidden in this context. Note some restrictions apply to " +
"variable access. For example, direct access to request parameters is forbidden in preprocessing and " +
"unescaped expressions, in TEXT template mode, in fragment insertion specifications and " +
"in some specific attribute processors.");
}
}
}
return target != null;
}
public TypedValue read(final EvaluationContext evaluationContext, final Object target, final String name)
throws AccessException {<FILL_FUNCTION_BODY>}
public boolean canWrite(
final EvaluationContext context, final Object target, final String name)
throws AccessException {
// There should never be a need to write on an IContext during a template execution
return false;
}
public void write(
final EvaluationContext context, final Object target, final String name, final Object newValue)
throws AccessException {
// There should never be a need to write on an IContext during a template execution
throw new AccessException("Cannot write to " + IContext.class.getName());
}
}
|
if (target == null) {
throw new AccessException("Cannot read property of null target");
}
try {
final IContext context = (IContext) target;
return new TypedValue(context.getVariable(name));
} catch (final ClassCastException e) {
// This can happen simply because we're applying the same
// AST tree on a different class (Spring internally caches property accessors).
// So this exception might be considered "normal" by Spring AST evaluator and
// just use it to refresh the property accessor cache.
throw new AccessException("Cannot read target of class " + target.getClass().getName());
}
| 572
| 170
| 742
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/SpringStandardConversionService.java
|
SpringStandardConversionService
|
convertToString
|
class SpringStandardConversionService extends AbstractStandardConversionService {
private static final TypeDescriptor TYPE_STRING = TypeDescriptor.valueOf(String.class);
public SpringStandardConversionService() {
// Should only be instanced from SpringStandardDialect
super();
}
@Override
protected String convertToString(
final IExpressionContext context,
final Object object) {<FILL_FUNCTION_BODY>}
@Override
protected <T> T convertOther(
final IExpressionContext context,
final Object object, final Class<T> targetClass) {
if (object == null) {
return null;
}
final TypeDescriptor objectTypeDescriptor = TypeDescriptor.forObject(object);
final TypeDescriptor targetTypeDescriptor = TypeDescriptor.valueOf(targetClass);
final TypeConverter typeConverter = getSpringConversionService(context);
if (typeConverter == null || !typeConverter.canConvert(objectTypeDescriptor, targetTypeDescriptor)) {
return super.convertOther(context, object, targetClass);
}
return (T) typeConverter.convertValue(object, objectTypeDescriptor, targetTypeDescriptor);
}
private static TypeConverter getSpringConversionService(final IExpressionContext context) {
final EvaluationContext evaluationContext =
(EvaluationContext) context.getVariable(
ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME);
if (evaluationContext != null) {
return evaluationContext.getTypeConverter();
}
return null;
}
}
|
if (object == null) {
return null;
}
final TypeDescriptor objectTypeDescriptor = TypeDescriptor.forObject(object);
final TypeConverter typeConverter = getSpringConversionService(context);
if (typeConverter == null || !typeConverter.canConvert(objectTypeDescriptor, TYPE_STRING)) {
return super.convertToString(context, object);
}
return (String) typeConverter.convertValue(object, objectTypeDescriptor, TYPE_STRING);
| 413
| 118
| 531
|
<methods>public final T convert(org.thymeleaf.context.IExpressionContext, java.lang.Object, Class<T>) <variables>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/SpringStandardExpressionObjectFactory.java
|
SpringStandardExpressionObjectFactory
|
buildObject
|
class SpringStandardExpressionObjectFactory extends StandardExpressionObjectFactory {
/*
* Any new objects added here should also be added to the "ALL_EXPRESSION_OBJECT_NAMES" See below.
*/
public static final String FIELDS_EXPRESSION_OBJECT_NAME = "fields";
public static final String THEMES_EXPRESSION_OBJECT_NAME = "themes";
public static final String MVC_EXPRESSION_OBJECT_NAME = "mvc";
public static final String REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME = "requestdatavalues";
public static final Set<String> ALL_EXPRESSION_OBJECT_NAMES;
private static final Mvc MVC_EXPRESSION_OBJECT = new Mvc();
static {
final Set<String> allExpressionObjectNames = new LinkedHashSet<String>();
allExpressionObjectNames.addAll(StandardExpressionObjectFactory.ALL_EXPRESSION_OBJECT_NAMES);
allExpressionObjectNames.add(FIELDS_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(THEMES_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(MVC_EXPRESSION_OBJECT_NAME);
allExpressionObjectNames.add(REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME);
ALL_EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(allExpressionObjectNames);
}
public SpringStandardExpressionObjectFactory() {
super();
}
public Set<String> getAllExpressionObjectNames() {
return ALL_EXPRESSION_OBJECT_NAMES;
}
@SuppressWarnings("deprecation")
public Object buildObject(final IExpressionContext context, final String expressionObjectName) {<FILL_FUNCTION_BODY>}
}
|
if (MVC_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
return MVC_EXPRESSION_OBJECT;
}
if (THEMES_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
// Themes was deprecated in 3.1.0 because Spring 6 dropped support for themes.
// This expression object will be removed when Spring removes support.
return new Themes(context);
}
if (FIELDS_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
return new Fields(context);
}
if (REQUESTDATAVALUES_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (context instanceof ITemplateContext) {
return new RequestDataValues((ITemplateContext)context);
}
return null;
}
return super.buildObject(context, expressionObjectName);
| 479
| 233
| 712
|
<methods>public void <init>() ,public java.lang.Object buildObject(org.thymeleaf.context.IExpressionContext, java.lang.String) ,public Set<java.lang.String> getAllExpressionObjectNames() ,public boolean isCacheable(java.lang.String) <variables>private static final org.thymeleaf.expression.Aggregates AGGREGATES_EXPRESSION_OBJECT,public static final java.lang.String AGGREGATES_EXPRESSION_OBJECT_NAME,protected static final Set<java.lang.String> ALL_EXPRESSION_OBJECT_NAMES,private static final org.thymeleaf.expression.Arrays ARRAYS_EXPRESSION_OBJECT,public static final java.lang.String ARRAYS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Bools BOOLS_EXPRESSION_OBJECT,public static final java.lang.String BOOLS_EXPRESSION_OBJECT_NAME,public static final java.lang.String CALENDARS_EXPRESSION_OBJECT_NAME,public static final java.lang.String CONTEXT_EXPRESSION_OBJECT_NAME,public static final java.lang.String CONVERSIONS_EXPRESSION_OBJECT_NAME,public static final java.lang.String DATES_EXPRESSION_OBJECT_NAME,public static final java.lang.String EXECUTION_INFO_OBJECT_NAME,public static final java.lang.String IDS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Lists LISTS_EXPRESSION_OBJECT,public static final java.lang.String LISTS_EXPRESSION_OBJECT_NAME,public static final java.lang.String LOCALE_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Maps MAPS_EXPRESSION_OBJECT,public static final java.lang.String MAPS_EXPRESSION_OBJECT_NAME,public static final java.lang.String MESSAGES_EXPRESSION_OBJECT_NAME,public static final java.lang.String NUMBERS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Objects OBJECTS_EXPRESSION_OBJECT,public static final java.lang.String OBJECTS_EXPRESSION_OBJECT_NAME,public static final java.lang.String REQUEST_EXPRESSION_OBJECT_NAME,public static final java.lang.String RESPONSE_EXPRESSION_OBJECT_NAME,public static final java.lang.String ROOT_EXPRESSION_OBJECT_NAME,public static final java.lang.String SELECTION_TARGET_EXPRESSION_OBJECT_NAME,public static final java.lang.String SERVLET_CONTEXT_EXPRESSION_OBJECT_NAME,public static final java.lang.String SESSION_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Sets SETS_EXPRESSION_OBJECT,public static final java.lang.String SETS_EXPRESSION_OBJECT_NAME,public static final java.lang.String STRINGS_EXPRESSION_OBJECT_NAME,public static final java.lang.String TEMPORALS_EXPRESSION_OBJECT_NAME,private static final org.thymeleaf.expression.Uris URIS_EXPRESSION_OBJECT,public static final java.lang.String URIS_EXPRESSION_OBJECT_NAME,public static final java.lang.String VARIABLES_EXPRESSION_OBJECT_NAME
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/SpringStandardExpressions.java
|
SpringStandardExpressions
|
isSpringELCompilerEnabled
|
class SpringStandardExpressions {
/**
* Name used for registering whether <i>Spring EL compilation</i> should be enabled if available or not.
*/
public static final String ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME = "EnableSpringELCompiler";
private SpringStandardExpressions() {
super();
}
/**
* <p>
* Check whether compilation of Spring EL expressions should be enabled or not.
* </p>
* <p>
* This is done through configuration methods at the {@link SpringStandardDialect}
* instance being used, and its value is offered to the engine as an <em>execution attribute</em>.
* </p>
*
* @param configuration the configuration object for the current template execution environment.
* @return {@code true} if the SpEL compiler should be enabled if available, {@code false} if not.
*/
public static boolean isSpringELCompilerEnabled(final IEngineConfiguration configuration) {<FILL_FUNCTION_BODY>}
}
|
final Object enableSpringELCompiler =
configuration.getExecutionAttributes().get(ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME);
if (enableSpringELCompiler == null) {
return false;
}
if (!(enableSpringELCompiler instanceof Boolean)) {
throw new TemplateProcessingException(
"A value for the \"" + ENABLE_SPRING_EL_COMPILER_ATTRIBUTE_NAME + "\" execution attribute " +
"has been specified, but it is not of the required type Boolean. " +
"(" + enableSpringELCompiler.getClass().getName() + ")");
}
return ((Boolean) enableSpringELCompiler).booleanValue();
| 280
| 178
| 458
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/Themes.java
|
Themes
|
code
|
class Themes {
private final Theme theme;
private final Locale locale;
/**
* Constructor, obtains the current theme and locale from the processing
* context for code lookups later.
*
* @param context the processing context being used
*/
public Themes(final IExpressionContext context) {
super();
this.locale = context.getLocale();
final IThymeleafRequestContext requestContext = SpringContextUtils.getRequestContext(context);
this.theme = requestContext != null ? requestContext.getTheme() : null;
}
/**
* Looks up and returns the value of the given key in the properties file of
* the currently-selected theme.
*
* @param code Key to look up in the theme properties file.
* @return The value of the code in the current theme properties file, or an
* empty string if the code could not be resolved.
*/
public String code(final String code) {<FILL_FUNCTION_BODY>}
}
|
if (this.theme == null) {
throw new TemplateProcessingException("Theme cannot be resolved because RequestContext was not found. "
+ "Are you using a Context object without a RequestContext variable?");
}
return this.theme.getMessageSource().getMessage(code, null, "", this.locale);
| 262
| 76
| 338
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/ThymeleafEvaluationContext.java
|
ThymeleafEvaluationContext
|
lookupVariable
|
class ThymeleafEvaluationContext
extends StandardEvaluationContext
implements IThymeleafEvaluationContext {
public static final String THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME = "thymeleaf::EvaluationContext";
private static final ReflectivePropertyAccessor REFLECTIVE_PROPERTY_ACCESSOR_INSTANCE =
new ThymeleafEvaluationContextACLPropertyAccessor();
private static final MapAccessor MAP_ACCESSOR_INSTANCE = new MapAccessor();
private static final TypeLocator TYPE_LOCATOR = new ThymeleafEvaluationContextACLTypeLocator();
private static final List<MethodResolver> METHOD_RESOLVERS =
Collections.singletonList(new ThymeleafEvaluationContextACLMethodResolver());
private final ApplicationContext applicationContext;
private IExpressionObjects expressionObjects = null;
private boolean variableAccessRestricted = false;
public ThymeleafEvaluationContext(final ApplicationContext applicationContext, final ConversionService conversionService) {
super();
Validate.notNull(applicationContext, "Application Context cannot be null");
// ConversionService CAN be null
this.applicationContext = applicationContext;
this.setBeanResolver(new BeanFactoryResolver(applicationContext));
if (conversionService != null) {
this.setTypeConverter(new StandardTypeConverter(conversionService));
}
final List<PropertyAccessor> propertyAccessors = new ArrayList<>(5);
propertyAccessors.add(SPELContextPropertyAccessor.INSTANCE);
propertyAccessors.add(MAP_ACCESSOR_INSTANCE);
propertyAccessors.add(REFLECTIVE_PROPERTY_ACCESSOR_INSTANCE);
this.setPropertyAccessors(propertyAccessors);
// We need to establish a custom type locator in order to forbid access to certain dangerous classes in expressions
this.setTypeLocator(TYPE_LOCATOR);
// We need to establish a custom method resolver in order to forbid calling methods on any of the blocked classes
this.setMethodResolvers(METHOD_RESOLVERS);
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
@Override
public Object lookupVariable(final String name) {<FILL_FUNCTION_BODY>}
public boolean isVariableAccessRestricted() {
return this.variableAccessRestricted;
}
public void setVariableAccessRestricted(final boolean restricted) {
this.variableAccessRestricted = restricted;
}
public IExpressionObjects getExpressionObjects() {
return this.expressionObjects;
}
public void setExpressionObjects(final IExpressionObjects expressionObjects) {
this.expressionObjects = expressionObjects;
}
static final class ThymeleafEvaluationContextACLTypeLocator implements TypeLocator {
private final TypeLocator typeLocator;
ThymeleafEvaluationContextACLTypeLocator() {
this(new StandardTypeLocator());
}
ThymeleafEvaluationContextACLTypeLocator(final TypeLocator typeLocator) {
super();
// typeLocator CAN be null
this.typeLocator = typeLocator;
if (this.typeLocator instanceof StandardTypeLocator) {
// A default prefix on "java.lang" is added by default, but we will remove it in order to avoid
// the filter forbidding all "java.lang.*" classes to be bypassed.
((StandardTypeLocator)this.typeLocator).removeImport("java.lang");
}
}
@Override
public Class<?> findType(final String typeName) throws EvaluationException {
if (this.typeLocator == null) {
throw new EvaluationException("Type could not be located (no type locator configured): " + typeName);
}
if (!ExpressionUtils.isTypeAllowed(typeName)) {
throw new EvaluationException(
String.format("Access is forbidden for type '%s' in this expression context.", typeName));
}
return this.typeLocator.findType(typeName);
}
}
static final class ThymeleafEvaluationContextACLPropertyAccessor extends ReflectivePropertyAccessor {
private final ReflectivePropertyAccessor propertyAccessor;
ThymeleafEvaluationContextACLPropertyAccessor() {
this(null);
}
ThymeleafEvaluationContextACLPropertyAccessor(final ReflectivePropertyAccessor propertyAccessor) {
super(false); // allowWrite = false
// propertyAccessor CAN be null
this.propertyAccessor = propertyAccessor;
}
@Override
public boolean canRead(final EvaluationContext context, final Object targetObject, final String name) throws AccessException {
final boolean canRead;
if (this.propertyAccessor != null) {
canRead = this.propertyAccessor.canRead(context, targetObject, name);
} else {
canRead = super.canRead(context, targetObject, name);
}
if (canRead) {
// We need to perform the check on the getter equivalent to the member being called
final String methodEquiv =
("empty".equals(name) || "blank".equals(name)) ?
"is" + Character.toUpperCase(name.charAt(0)) + name.substring(1) :
"get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
if (!ExpressionUtils.isMemberAllowed(targetObject, methodEquiv)) {
throw new EvaluationException(
String.format(
"Accessing member '%s' is forbidden for type '%s' in this expression context.",
name, targetObject.getClass()));
}
}
return canRead;
}
}
static final class ThymeleafEvaluationContextACLMethodResolver extends ReflectiveMethodResolver {
private final ReflectiveMethodResolver methodResolver;
ThymeleafEvaluationContextACLMethodResolver() {
this(null);
}
ThymeleafEvaluationContextACLMethodResolver(final ReflectiveMethodResolver methodResolver) {
super();
// methodResolver CAN be null
this.methodResolver = methodResolver;
}
@Override
public MethodExecutor resolve(
final EvaluationContext context, final Object targetObject,
final String name, final List<TypeDescriptor> argumentTypes) throws AccessException {
final MethodExecutor methodExecutor;
if (this.methodResolver != null) {
methodExecutor = this.methodResolver.resolve(context, targetObject, name, argumentTypes);
} else {
methodExecutor = super.resolve(context, targetObject, name, argumentTypes);
}
if (methodExecutor != null) {
if (!ExpressionUtils.isMemberAllowed(targetObject, name)) {
throw new EvaluationException(
String.format(
"Calling method '%s' is forbidden for type '%s' in this expression context.",
name, targetObject.getClass()));
}
}
return methodExecutor;
}
}
}
|
if (this.expressionObjects != null && this.expressionObjects.containsObject(name)) {
final Object result = this.expressionObjects.getObject(name);
if (result != null) {
return result;
}
}
// fall back to superclass
return super.lookupVariable(name);
| 1,809
| 82
| 1,891
|
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public void addConstructorResolver(org.springframework.expression.ConstructorResolver) ,public void addMethodResolver(org.springframework.expression.MethodResolver) ,public void addPropertyAccessor(org.springframework.expression.PropertyAccessor) ,public org.springframework.expression.BeanResolver getBeanResolver() ,public List<org.springframework.expression.ConstructorResolver> getConstructorResolvers() ,public List<org.springframework.expression.MethodResolver> getMethodResolvers() ,public org.springframework.expression.OperatorOverloader getOperatorOverloader() ,public List<org.springframework.expression.PropertyAccessor> getPropertyAccessors() ,public org.springframework.expression.TypedValue getRootObject() ,public org.springframework.expression.TypeComparator getTypeComparator() ,public org.springframework.expression.TypeConverter getTypeConverter() ,public org.springframework.expression.TypeLocator getTypeLocator() ,public java.lang.Object lookupVariable(java.lang.String) ,public void registerFunction(java.lang.String, java.lang.reflect.Method) ,public void registerMethodFilter(Class<?>, org.springframework.expression.MethodFilter) throws java.lang.IllegalStateException,public boolean removeConstructorResolver(org.springframework.expression.ConstructorResolver) ,public boolean removeMethodResolver(org.springframework.expression.MethodResolver) ,public boolean removePropertyAccessor(org.springframework.expression.PropertyAccessor) ,public void setBeanResolver(org.springframework.expression.BeanResolver) ,public void setConstructorResolvers(List<org.springframework.expression.ConstructorResolver>) ,public void setMethodResolvers(List<org.springframework.expression.MethodResolver>) ,public void setOperatorOverloader(org.springframework.expression.OperatorOverloader) ,public void setPropertyAccessors(List<org.springframework.expression.PropertyAccessor>) ,public void setRootObject(java.lang.Object) ,public void setRootObject(java.lang.Object, org.springframework.core.convert.TypeDescriptor) ,public void setTypeComparator(org.springframework.expression.TypeComparator) ,public void setTypeConverter(org.springframework.expression.TypeConverter) ,public void setTypeLocator(org.springframework.expression.TypeLocator) ,public void setVariable(java.lang.String, java.lang.Object) ,public void setVariables(Map<java.lang.String,java.lang.Object>) <variables>private org.springframework.expression.BeanResolver beanResolver,private volatile List<org.springframework.expression.ConstructorResolver> constructorResolvers,private volatile List<org.springframework.expression.MethodResolver> methodResolvers,private org.springframework.expression.OperatorOverloader operatorOverloader,private volatile List<org.springframework.expression.PropertyAccessor> propertyAccessors,private volatile org.springframework.expression.spel.support.ReflectiveMethodResolver reflectiveMethodResolver,private org.springframework.expression.TypedValue rootObject,private org.springframework.expression.TypeComparator typeComparator,private org.springframework.expression.TypeConverter typeConverter,private org.springframework.expression.TypeLocator typeLocator,private final Map<java.lang.String,java.lang.Object> variables
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/expression/ThymeleafEvaluationContextWrapper.java
|
ThymeleafEvaluationContextWrapper
|
setVariable
|
class ThymeleafEvaluationContextWrapper implements IThymeleafEvaluationContext {
private static final MapAccessor MAP_ACCESSOR_INSTANCE = new MapAccessor();
private final EvaluationContext delegate;
private final List<PropertyAccessor> propertyAccessors; // can be initialized to null if we can delegate
private final TypeLocator typeLocator; // can be initialized to null if we can delegate
private final List<MethodResolver> methodResolvers; // can be initialized to null if we can delegate
private IExpressionObjects expressionObjects = null;
private boolean requestParametersRestricted = false;
private Map<String,Object> additionalVariables = null;
public ThymeleafEvaluationContextWrapper(final EvaluationContext delegate) {
super();
Validate.notNull(delegate, "Evaluation context delegate cannot be null");
this.delegate = delegate;
if (this.delegate instanceof ThymeleafEvaluationContext) {
this.propertyAccessors = null; // No need to initialize our own property accessors
this.typeLocator = null; // No need to initialize our own type locator
this.methodResolvers = null; // No need to initialize our own method resolvers
} else {
// We need to wrap any reflective method resolvers in order to forbid calling methods on any of the blocked classes
this.propertyAccessors =
Stream.concat(
Stream.of(SPELContextPropertyAccessor.INSTANCE, MAP_ACCESSOR_INSTANCE),
this.delegate.getPropertyAccessors().stream()
.map(pa -> (pa instanceof ReflectivePropertyAccessor) ?
new ThymeleafEvaluationContextACLPropertyAccessor((ReflectivePropertyAccessor) pa) : pa))
.collect(Collectors.toList());
// We need to establish a custom type locator in order to forbid access to certain dangerous classes in expressions
this.typeLocator =
new ThymeleafEvaluationContextACLTypeLocator(this.delegate.getTypeLocator());
// We need to wrap any reflective method resolvers in order to forbid calling methods on any of the blocked classes
this.methodResolvers =
this.delegate.getMethodResolvers().stream()
.map(mr -> (mr instanceof ReflectiveMethodResolver) ?
new ThymeleafEvaluationContextACLMethodResolver((ReflectiveMethodResolver) mr) : mr)
.collect(Collectors.toList());
}
}
public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
public List<MethodResolver> getMethodResolvers() {
return this.methodResolvers == null ? this.delegate.getMethodResolvers() : this.methodResolvers;
}
public List<PropertyAccessor> getPropertyAccessors() {
return this.propertyAccessors == null ? this.delegate.getPropertyAccessors() : this.propertyAccessors;
}
public TypeLocator getTypeLocator() {
return this.typeLocator == null ? this.delegate.getTypeLocator() : this.typeLocator;
}
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
public BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
public void setVariable(final String name, final Object value) {<FILL_FUNCTION_BODY>}
public Object lookupVariable(final String name) {
if (this.expressionObjects != null && this.expressionObjects.containsObject(name)) {
final Object result = this.expressionObjects.getObject(name);
if (result != null) {
return result;
}
}
if (this.additionalVariables != null && this.additionalVariables.containsKey(name)) {
final Object result = this.additionalVariables.get(name);
if (result != null) {
return result;
}
}
// fall back to delegate
return this.delegate.lookupVariable(name);
}
public boolean isVariableAccessRestricted() {
return this.requestParametersRestricted;
}
public void setVariableAccessRestricted(final boolean restricted) {
this.requestParametersRestricted = restricted;
}
public IExpressionObjects getExpressionObjects() {
return this.expressionObjects;
}
public void setExpressionObjects(final IExpressionObjects expressionObjects) {
this.expressionObjects = expressionObjects;
}
}
|
if (this.additionalVariables == null) {
this.additionalVariables = new HashMap<String, Object>(5, 1.0f);
}
this.additionalVariables.put(name, value);
| 1,264
| 61
| 1,325
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/messageresolver/SpringMessageResolver.java
|
SpringMessageResolver
|
resolveMessage
|
class SpringMessageResolver
extends AbstractMessageResolver
implements MessageSourceAware {
private static final Logger logger = LoggerFactory.getLogger(SpringMessageResolver.class);
private final StandardMessageResolver standardMessageResolver;
private MessageSource messageSource;
public SpringMessageResolver() {
super();
this.standardMessageResolver = new StandardMessageResolver();
}
/*
* Check the message source has been set.
*/
private void checkMessageSourceInitialized() {
if (this.messageSource == null) {
throw new ConfigurationException(
"Cannot initialize " + SpringMessageResolver.class.getSimpleName() +
": MessageSource has not been set. Either define this object as " +
"a Spring bean (which will automatically set the MessageSource) or, " +
"if you instance it directly, set the MessageSource manually using its "+
"corresponding setter method.");
}
}
/**
* <p>
* Returns the message source ({@link MessageSource}) to be
* used for message resolution.
* </p>
*
* @return the message source
*/
public final MessageSource getMessageSource() {
return this.messageSource;
}
/**
* <p>
* Sets the message source to be used for message resolution
* </p>
*
* @param messageSource the message source
*/
public final void setMessageSource(final MessageSource messageSource) {
this.messageSource = messageSource;
}
public final String resolveMessage(
final ITemplateContext context, final Class<?> origin, final String key, final Object[] messageParameters) {<FILL_FUNCTION_BODY>}
public String createAbsentMessageRepresentation(
final ITemplateContext context, final Class<?> origin, final String key, final Object[] messageParameters) {
return this.standardMessageResolver.createAbsentMessageRepresentation(context, origin, key, messageParameters);
}
}
|
Validate.notNull(context.getLocale(), "Locale in context cannot be null");
Validate.notNull(key, "Message key cannot be null");
/*
* FIRST STEP: Look for the message using template-based resolution
*/
if (context != null) {
checkMessageSourceInitialized();
if (logger.isTraceEnabled()) {
logger.trace(
"[THYMELEAF][{}] Resolving message with key \"{}\" for template \"{}\" and locale \"{}\". " +
"Messages will be retrieved from Spring's MessageSource infrastructure.",
new Object[]{TemplateEngine.threadIndex(), key, context.getTemplateData().getTemplate(), context.getLocale()});
}
try {
return this.messageSource.getMessage(key, messageParameters, context.getLocale());
} catch (NoSuchMessageException e) {
// Try other methods
}
}
/*
* SECOND STEP: Look for the message using origin-based resolution, delegated to the StandardMessageResolver
*/
if (origin != null) {
// We will be disabling template-based resolution when delegating in order to use only origin-based
final String message =
this.standardMessageResolver.resolveMessage(context, origin, key, messageParameters, false, true, true);
if (message != null) {
return message;
}
}
/*
* NOT FOUND, return null
*/
return null;
| 520
| 382
| 902
|
<methods>public final java.lang.String getName() ,public final java.lang.Integer getOrder() ,public void setName(java.lang.String) ,public void setOrder(java.lang.Integer) <variables>private static final org.slf4j.Logger logger,private java.lang.String name,private java.lang.Integer order
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/AbstractSpringFieldTagProcessor.java
|
AbstractSpringFieldTagProcessor
|
doProcess
|
class AbstractSpringFieldTagProcessor
extends AbstractAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "field";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
protected static final String INPUT_TAG_NAME = "input";
protected static final String SELECT_TAG_NAME = "select";
protected static final String OPTION_TAG_NAME = "option";
protected static final String TEXTAREA_TAG_NAME = "textarea";
protected static final String ID_ATTR_NAME = "id";
protected static final String TYPE_ATTR_NAME = "type";
protected static final String NAME_ATTR_NAME = "name";
protected static final String VALUE_ATTR_NAME = "value";
protected static final String CHECKED_ATTR_NAME = "checked";
protected static final String SELECTED_ATTR_NAME = "selected";
protected static final String DISABLED_ATTR_NAME = "disabled";
protected static final String MULTIPLE_ATTR_NAME = "multiple";
private AttributeDefinition discriminatorAttributeDefinition;
protected AttributeDefinition idAttributeDefinition;
protected AttributeDefinition typeAttributeDefinition;
protected AttributeDefinition nameAttributeDefinition;
protected AttributeDefinition valueAttributeDefinition;
protected AttributeDefinition checkedAttributeDefinition;
protected AttributeDefinition selectedAttributeDefinition;
protected AttributeDefinition disabledAttributeDefinition;
protected AttributeDefinition multipleAttributeDefinition;
private final String discriminatorAttrName;
private final String[] discriminatorAttrValues;
private final boolean removeAttribute;
public AbstractSpringFieldTagProcessor(
final String dialectPrefix, final String elementName,
final String discriminatorAttrName, final String[] discriminatorAttrValues,
final boolean removeAttribute) {
super(TEMPLATE_MODE, dialectPrefix, elementName, false, ATTR_NAME, true, ATTR_PRECEDENCE, false);
this.discriminatorAttrName = discriminatorAttrName;
this.discriminatorAttrValues = discriminatorAttrValues;
this.removeAttribute = removeAttribute;
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions in order to being able to use much
// faster methods for setting/replacing attributes on the ElementAttributes implementation
this.discriminatorAttributeDefinition =
(this.discriminatorAttrName != null? attributeDefinitions.forName(TEMPLATE_MODE, this.discriminatorAttrName) : null);
this.idAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, ID_ATTR_NAME);
this.typeAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TYPE_ATTR_NAME);
this.nameAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, NAME_ATTR_NAME);
this.valueAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, VALUE_ATTR_NAME);
this.checkedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, CHECKED_ATTR_NAME);
this.selectedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, SELECTED_ATTR_NAME);
this.disabledAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, DISABLED_ATTR_NAME);
this.multipleAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, MULTIPLE_ATTR_NAME);
}
private boolean matchesDiscriminator(final IProcessableElementTag tag) {
if (this.discriminatorAttrName == null) {
return true;
}
final boolean hasDiscriminatorAttr = tag.hasAttribute(this.discriminatorAttributeDefinition.getAttributeName());
if (this.discriminatorAttrValues == null || this.discriminatorAttrValues.length == 0) {
return hasDiscriminatorAttr;
}
final String discriminatorTagValue =
(hasDiscriminatorAttr? tag.getAttributeValue(this.discriminatorAttributeDefinition.getAttributeName()) : null);
for (int i = 0; i < this.discriminatorAttrValues.length; i++) {
final String discriminatorAttrValue = this.discriminatorAttrValues[i];
if (discriminatorAttrValue == null) {
if (!hasDiscriminatorAttr || discriminatorTagValue == null) {
return true;
}
} else if (discriminatorAttrValue.equals(discriminatorTagValue)) {
return true;
}
}
return false;
}
@Override
protected 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 IThymeleafBindStatus bindStatus,
final IElementTagStructureHandler structureHandler);
// This method is designed to be called from the diverse subclasses
protected final String computeId(
final ITemplateContext context,
final IProcessableElementTag tag,
final String name, final boolean sequence) {
String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());
if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {
return (StringUtils.hasText(id) ? id : null);
}
id = FieldUtils.idFromName(name);
if (sequence) {
final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);
return id + count.toString();
}
return id;
}
}
|
/*
* First thing to check is whether this processor really matches, because so far we have asked the engine only
* to match per attribute (th:field) and host tag (input, select, option...) but we still don't know if the
* match is complete because we might still need to assess for example that the 'type' attribute has the
* correct value. For example, the same processor will not be executing on <input type="text" th:field="*{a}"/>
* and on <input type="checkbox" th:field="*{a}"/>
*/
if (!matchesDiscriminator(tag)) {
// Note in this case we do not have to remove the th:field attribute because the correct processor is still
// to be executed!
return;
}
if (this.removeAttribute) {
structureHandler.removeAttribute(attributeName);
}
final IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus == null) {
throw new TemplateProcessingException(
"Cannot process attribute '" + attributeName + "': no associated BindStatus could be found for " +
"the intended form binding operations. This can be due to the lack of a proper management of the " +
"Spring RequestContext, which is usually done through the ThymeleafView or ThymeleafReactiveView");
}
// We set the BindStatus into a local variable just in case we have more BindStatus-related processors to
// be applied for the same tag, like for example a th:errorclass
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
doProcess(context, tag, attributeName, attributeValue, bindStatus, structureHandler);
| 1,556
| 445
| 2,001
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringActionTagProcessor.java
|
SpringActionTagProcessor
|
doProcess
|
class SpringActionTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String TARGET_ATTR_NAME = "action";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String METHOD_ATTR_NAME = "method";
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private static final String VALUE_ATTR_NAME = "value";
private static final String METHOD_ATTR_DEFAULT_VALUE = "GET";
private AttributeDefinition targetAttributeDefinition;
private AttributeDefinition methodAttributeDefinition;
public SpringActionTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions 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);
this.methodAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, METHOD_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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// But before setting the 'action' attribute, we need to verify the 'method' attribute and let the
// RequestDataValueProcessor act on it.
final String methodAttributeValue = tag.getAttributeValue(this.methodAttributeDefinition.getAttributeName());
final String httpMethod = methodAttributeValue == null ? METHOD_ATTR_DEFAULT_VALUE : methodAttributeValue;
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processAction(context, newAttributeValue, httpMethod);
// Set the 'action' attribute
StandardProcessorUtils.replaceAttribute(
structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
// If this th:action is in a <form> tag, we might need to add a hidden field (depending on Spring configuration)
if ("form".equalsIgnoreCase(tag.getElementCompleteName())) {
final Map<String,String> extraHiddenFields =
RequestDataValueProcessorUtils.getExtraHiddenFields(context);
if (extraHiddenFields != null && extraHiddenFields.size() > 0) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel extraHiddenElementTags = modelFactory.createModel();
for (final Map.Entry<String,String> extraHiddenField : extraHiddenFields.entrySet()) {
final Map<String,String> extraHiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
extraHiddenAttributes.put(TYPE_ATTR_NAME, "hidden");
extraHiddenAttributes.put(NAME_ATTR_NAME, extraHiddenField.getKey());
extraHiddenAttributes.put(VALUE_ATTR_NAME, extraHiddenField.getValue()); // no need to re-apply the processor here
final IStandaloneElementTag extraHiddenElementTag =
modelFactory.createStandaloneElementTag("input", extraHiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
extraHiddenElementTags.add(extraHiddenElementTag);
}
structureHandler.insertImmediatelyAfter(extraHiddenElementTags, false);
}
}
| 477
| 579
| 1,056
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringErrorClassTagProcessor.java
|
SpringErrorClassTagProcessor
|
doProcess
|
class SpringErrorClassTagProcessor
extends AbstractAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1800;
public static final String ATTR_NAME = "errorclass";
public static final String TARGET_ATTR_NAME = "class";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringErrorClassTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, null, false, ATTR_NAME, true,ATTR_PRECEDENCE, true);
}
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 IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
/*
* There are two scenarios for a th:errorclass to appear in: one is in an element for which a th:field has already
* been executed, in which case we already have a BindStatus to check for errors; and the other one is an element
* for which a th:field has not been executed, but which should have a "name" attribute (either directly or as
* the result of executing a th:name) -- in this case, we'll have to build the BuildStatus ourselves.
*/
private static IThymeleafBindStatus computeBindStatus(final IExpressionContext context, final IProcessableElementTag tag) {
/*
* First, try to obtain an already-existing BindStatus resulting from the execution of a th:field attribute
* in the same element.
*/
final IThymeleafBindStatus bindStatus =
(IThymeleafBindStatus) context.getVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS);
if (bindStatus != null) {
return bindStatus;
}
/*
* It seems no th:field was executed on the same element, so we must rely on the "name" attribute (probably
* specified by hand or by a th:name). No th:field was executed, so no BindStatus available -- we'll have to
* build it ourselves.
*/
final String fieldName = tag.getAttributeValue("name");
if (StringUtils.isEmptyOrWhitespace(fieldName)) {
return null;
}
final VariableExpression boundExpression =
(VariableExpression) context.getVariable(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION);
if (boundExpression == null) {
// No bound expression, so just use the field name
return FieldUtils.getBindStatusFromParsedExpression(context, false, fieldName);
}
// Bound object and field object names might intersect (e.g. th:object="a.b", name="b.c"), and we must compute
// the real 'bindable' name ("a.b.c") by only using the first token in the bound object name, appending the
// rest of the field name: "a" + "b.c" -> "a.b.c"
final String boundExpressionStr = boundExpression.getExpression();
final String computedFieldName;
if (boundExpressionStr.indexOf('.') == -1) {
computedFieldName = boundExpressionStr + '.' + fieldName; // we append because we will use no form root afterwards
} else {
computedFieldName = boundExpressionStr.substring(0, boundExpressionStr.indexOf('.')) + '.' + fieldName;
}
// We set "useRoot" to false because we have already computed that part
return FieldUtils.getBindStatusFromParsedExpression(context, false, computedFieldName);
}
}
|
final IThymeleafBindStatus bindStatus = computeBindStatus(context, tag);
if (bindStatus == null) {
final AttributeName fieldAttributeName =
AttributeNames.forHTMLName(attributeName.getPrefix(), AbstractSpringFieldTagProcessor.ATTR_NAME);
throw new TemplateProcessingException(
"Cannot apply \"" + attributeName + "\": this attribute requires the existence of " +
"a \"name\" (or " + Arrays.asList(fieldAttributeName.getCompleteAttributeNames()) + ") attribute " +
"with non-empty value in the same host tag.");
}
if (bindStatus.isError()) {
final IEngineConfiguration configuration = context.getConfiguration();
final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);
final Object expressionResult = expression.execute(context);
String newAttributeValue = HtmlEscape.escapeHtml4Xml(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);
}
}
| 1,075
| 429
| 1,504
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringErrorsTagProcessor.java
|
SpringErrorsTagProcessor
|
doProcess
|
class SpringErrorsTagProcessor extends AbstractAttributeTagProcessor {
private static final String ERROR_DELIMITER = "<br />";
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "errors";
public SpringErrorsTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, ATTR_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 IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus.isError()) {
final StringBuilder strBuilder = new StringBuilder();
final String[] errorMsgs = bindStatus.getErrorMessages();
for (int i = 0; i < errorMsgs.length; i++) {
if (i > 0) {
strBuilder.append(ERROR_DELIMITER);
}
final String displayString = SpringValueFormatter.getDisplayString(errorMsgs[i], false);
strBuilder.append(HtmlEscape.escapeHtml4Xml(displayString));
}
structureHandler.setBody(strBuilder.toString(), false);
// Just in case we also have a th:errorclass in this tag
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
} else {
structureHandler.removeElement();
}
| 195
| 249
| 444
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringHrefTagProcessor.java
|
SpringHrefTagProcessor
|
doProcess
|
class SpringHrefTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String ATTR_NAME = "href";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringHrefTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE, false, true);
}
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, 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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processUrl(context, newAttributeValue);
// Set the real, non prefixed attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, ATTR_NAME, (newAttributeValue == null ? "" : newAttributeValue));
| 348
| 121
| 469
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringInputCheckboxFieldTagProcessor.java
|
SpringInputCheckboxFieldTagProcessor
|
doProcess
|
class SpringInputCheckboxFieldTagProcessor
extends AbstractSpringFieldTagProcessor {
public static final String CHECKBOX_INPUT_TYPE_ATTR_VALUE = "checkbox";
private final boolean renderHiddenMarkersBeforeCheckboxes;
public SpringInputCheckboxFieldTagProcessor(final String dialectPrefix) {
this(dialectPrefix, SpringStandardDialect.DEFAULT_RENDER_HIDDEN_MARKERS_BEFORE_CHECKBOXES);
}
public SpringInputCheckboxFieldTagProcessor(final String dialectPrefix, final boolean renderHiddenMarkersBeforeCheckboxes) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { CHECKBOX_INPUT_TYPE_ATTR_VALUE }, true);
this.renderHiddenMarkersBeforeCheckboxes = renderHiddenMarkersBeforeCheckboxes;
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private final boolean isDisabled(final IProcessableElementTag tag) {
// Disabled = attribute "disabled" exists
return tag.hasAttribute(this.disabledAttributeDefinition.getAttributeName());
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, true);
String value = null;
boolean checked = false;
Object boundValue = bindStatus.getValue();
final Class<?> valueType = bindStatus.getValueType();
if (Boolean.class.equals(valueType) || boolean.class.equals(valueType)) {
if (boundValue instanceof String) {
boundValue = Boolean.valueOf((String) boundValue);
}
final Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE);
value = "true";
checked = booleanValue.booleanValue();
} else {
value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"input(checkbox)\" tags " +
"when binding to non-boolean values");
}
checked = SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
}
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "checkbox"));
if (checked) {
StandardProcessorUtils.setAttribute(structureHandler, this.checkedAttributeDefinition, CHECKED_ATTR_NAME, CHECKED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.checkedAttributeDefinition.getAttributeName());
}
if (!isDisabled(tag)) {
/*
* Non-disabled checkboxes need an additional <input type="hidden"> in order to note their presence in
* the HTML document. Given unchecked checkboxes are not sent by browsers as a result of form submission,
* this is the only way to differentiate between a checkbox that is unchecked and a checkbox that was
* never displayed or is disabled.
*/
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenTagModel = modelFactory.createModel();
final String hiddenName = WebDataBinder.DEFAULT_FIELD_MARKER_PREFIX + name;
final String hiddenValue = "on";
final Map<String,String> hiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, "hidden");
hiddenAttributes.put(NAME_ATTR_NAME, hiddenName);
hiddenAttributes.put(VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, hiddenName, hiddenValue, "hidden"));
final IStandaloneElementTag hiddenTag =
modelFactory.createStandaloneElementTag(INPUT_TAG_NAME, hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenTagModel.add(hiddenTag);
if (this.renderHiddenMarkersBeforeCheckboxes) {
structureHandler.insertBefore(hiddenTagModel);
} else {
structureHandler.insertImmediatelyAfter(hiddenTagModel, false);
}
}
| 359
| 881
| 1,240
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringInputFileFieldTagProcessor.java
|
SpringInputFileFieldTagProcessor
|
doProcess
|
class SpringInputFileFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String FILE_INPUT_TYPE_ATTR_VALUE = "file";
public SpringInputFileFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { FILE_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
| 186
| 131
| 317
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringInputGeneralFieldTagProcessor.java
|
SpringInputGeneralFieldTagProcessor
|
doProcess
|
class SpringInputGeneralFieldTagProcessor
extends AbstractSpringFieldTagProcessor {
// HTML4 input types
public static final String TEXT_INPUT_TYPE_ATTR_VALUE = "text";
public static final String HIDDEN_INPUT_TYPE_ATTR_VALUE = "hidden";
// HTML5-specific input types
public static final String DATETIME_INPUT_TYPE_ATTR_VALUE = "datetime";
public static final String DATETIMELOCAL_INPUT_TYPE_ATTR_VALUE = "datetime-local";
public static final String DATE_INPUT_TYPE_ATTR_VALUE = "date";
public static final String MONTH_INPUT_TYPE_ATTR_VALUE = "month";
public static final String TIME_INPUT_TYPE_ATTR_VALUE = "time";
public static final String WEEK_INPUT_TYPE_ATTR_VALUE = "week";
public static final String NUMBER_INPUT_TYPE_ATTR_VALUE = "number";
public static final String RANGE_INPUT_TYPE_ATTR_VALUE = "range";
public static final String EMAIL_INPUT_TYPE_ATTR_VALUE = "email";
public static final String URL_INPUT_TYPE_ATTR_VALUE = "url";
public static final String SEARCH_INPUT_TYPE_ATTR_VALUE = "search";
public static final String TEL_INPUT_TYPE_ATTR_VALUE = "tel";
public static final String COLOR_INPUT_TYPE_ATTR_VALUE = "color";
private static final String[] ALL_TYPE_ATTR_VALUES =
new String[] {
null,
TEXT_INPUT_TYPE_ATTR_VALUE,
HIDDEN_INPUT_TYPE_ATTR_VALUE,
DATETIME_INPUT_TYPE_ATTR_VALUE,
DATETIMELOCAL_INPUT_TYPE_ATTR_VALUE,
DATE_INPUT_TYPE_ATTR_VALUE,
MONTH_INPUT_TYPE_ATTR_VALUE,
TIME_INPUT_TYPE_ATTR_VALUE,
WEEK_INPUT_TYPE_ATTR_VALUE,
NUMBER_INPUT_TYPE_ATTR_VALUE,
RANGE_INPUT_TYPE_ATTR_VALUE,
EMAIL_INPUT_TYPE_ATTR_VALUE,
URL_INPUT_TYPE_ATTR_VALUE,
SEARCH_INPUT_TYPE_ATTR_VALUE,
TEL_INPUT_TYPE_ATTR_VALUE,
COLOR_INPUT_TYPE_ATTR_VALUE
};
public SpringInputGeneralFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, ALL_TYPE_ATTR_VALUES, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private static boolean applyConversion(final String type) {
return !(type != null && ("number".equalsIgnoreCase(type) || "range".equalsIgnoreCase(type)));
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
// Thanks to precedence, this should have already been computed
final String type = tag.getAttributeValue(this.typeAttributeDefinition.getAttributeName());
// Apply the conversions (editor), depending on type (no conversion for "number" and "range"
// Also, no escaping needed as attribute values are always escaped by default
final String value =
applyConversion(type)?
SpringValueFormatter.getDisplayString(bindStatus.getValue(), bindStatus.getEditor(), true) :
SpringValueFormatter.getDisplayString(bindStatus.getActualValue(), true);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, type));
| 806
| 316
| 1,122
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringInputPasswordFieldTagProcessor.java
|
SpringInputPasswordFieldTagProcessor
|
doProcess
|
class SpringInputPasswordFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String PASSWORD_INPUT_TYPE_ATTR_VALUE = "password";
public SpringInputPasswordFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { PASSWORD_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, "", "password"));
| 192
| 178
| 370
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringInputRadioFieldTagProcessor.java
|
SpringInputRadioFieldTagProcessor
|
doProcess
|
class SpringInputRadioFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public static final String RADIO_INPUT_TYPE_ATTR_VALUE = "radio";
public SpringInputRadioFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, INPUT_TAG_NAME, TYPE_ATTR_NAME, new String[] { RADIO_INPUT_TYPE_ATTR_VALUE }, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, true);
final String value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"input(radio)\" tags");
}
final boolean checked =
SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
StandardProcessorUtils.setAttribute(
structureHandler, this.valueAttributeDefinition, VALUE_ATTR_NAME, RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "radio"));
if (checked) {
StandardProcessorUtils.setAttribute(structureHandler, this.checkedAttributeDefinition, CHECKED_ATTR_NAME, CHECKED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.checkedAttributeDefinition.getAttributeName());
}
| 192
| 340
| 532
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringMethodTagProcessor.java
|
SpringMethodTagProcessor
|
doProcess
|
class SpringMethodTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 990;
public static final String TARGET_ATTR_NAME = "method";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private static final String VALUE_ATTR_NAME = "value";
private AttributeDefinition targetAttributeDefinition;
public SpringMethodTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions 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>}
/*
* Determine if the HTTP method is supported by browsers (i.e. GET or POST).
*/
protected boolean isMethodBrowserSupported(final String method) {
return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method));
}
}
|
final String newAttributeValue = HtmlEscape.escapeHtml4Xml(expressionResult == null ? null : expressionResult.toString());
// Set the 'method' attribute, or remove it if evaluated to null
if (newAttributeValue == null || newAttributeValue.length() == 0) {
structureHandler.removeAttribute(this.targetAttributeDefinition.getAttributeName());
structureHandler.removeAttribute(attributeName);
} else {
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, newAttributeValue);
}
// If this th:action is in a <form> tag, we might need to add a hidden field for non-supported HTTP methods
if (newAttributeValue != null && "form".equalsIgnoreCase(tag.getElementCompleteName())) {
if (!isMethodBrowserSupported(newAttributeValue)) {
// Browsers only support HTTP GET and POST. If a different method
// has been specified, then Spring MVC allows us to specify it
// using a hidden input with name '_method' and set 'post' for the
// <form> tag.
StandardProcessorUtils.setAttribute(structureHandler, this.targetAttributeDefinition, TARGET_ATTR_NAME, "post");
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenMethodModel = modelFactory.createModel();
final String type = "hidden";
final String name = "_method";
final String value = RequestDataValueProcessorUtils.processFormFieldValue(context, name, newAttributeValue, type);
final Map<String,String> hiddenAttributes = new LinkedHashMap<String,String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, type);
hiddenAttributes.put(NAME_ATTR_NAME, name);
hiddenAttributes.put(VALUE_ATTR_NAME, value); // no need to escape
final IStandaloneElementTag hiddenMethodElementTag =
modelFactory.createStandaloneElementTag("input", hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenMethodModel.add(hiddenMethodElementTag);
structureHandler.insertImmediatelyAfter(hiddenMethodModel, false);
}
}
| 471
| 547
| 1,018
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringObjectTagProcessor.java
|
SpringObjectTagProcessor
|
validateSelectionValue
|
class SpringObjectTagProcessor extends AbstractStandardTargetSelectionTagProcessor {
public static final int ATTR_PRECEDENCE = 500;
public static final String ATTR_NAME = "object";
public SpringObjectTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE);
}
@Override
protected void validateSelectionValue(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IStandardExpression expression) {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> computeAdditionalLocalVariables(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IStandardExpression expression) {
// We set the (parsed) expression itself as a local variable because we might use it at the expression evaluator
return Collections.singletonMap(SpringContextVariableNames.SPRING_BOUND_OBJECT_EXPRESSION, (Object)expression);
}
}
|
if (expression == null || !(expression instanceof VariableExpression)) {
throw new TemplateProcessingException(
"The expression used for object selection is " + expression + ", which is not valid: " +
"only variable expressions (${...}) are allowed in '" + attributeName + "' attributes in " +
"Spring-enabled environments.");
}
| 300
| 92
| 392
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringOptionFieldTagProcessor.java
|
SpringOptionFieldTagProcessor
|
doProcess
|
class SpringOptionFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public SpringOptionFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, OPTION_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String value = tag.getAttributeValue(this.valueAttributeDefinition.getAttributeName());
if (value == null) {
throw new TemplateProcessingException(
"Attribute \"value\" is required in \"option\" tags");
}
final boolean selected =
SpringSelectedValueComparator.isSelected(bindStatus, HtmlEscape.unescapeHtml(value));
StandardProcessorUtils.setAttribute(
structureHandler,
this.valueAttributeDefinition, VALUE_ATTR_NAME,
RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "option"));
if (selected) {
StandardProcessorUtils.setAttribute(structureHandler, this.selectedAttributeDefinition, SELECTED_ATTR_NAME, SELECTED_ATTR_NAME);
} else {
structureHandler.removeAttribute(this.selectedAttributeDefinition.getAttributeName());
}
| 144
| 239
| 383
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringOptionInSelectFieldTagProcessor.java
|
SpringOptionInSelectFieldTagProcessor
|
doProcess
|
class SpringOptionInSelectFieldTagProcessor extends AbstractElementTagProcessor {
// This is 1005 in order to make sure it is executed just before "value" (Spring's version) and especially "th:field"
public static final int ATTR_PRECEDENCE = 1005;
public static final String OPTION_TAG_NAME = "option";
public SpringOptionInSelectFieldTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, OPTION_TAG_NAME, false, null, false, ATTR_PRECEDENCE);
}
@Override
protected void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
final AttributeName selectAttrNameToAdd =
(AttributeName) context.getVariable(SpringSelectFieldTagProcessor.OPTION_IN_SELECT_ATTR_NAME);
if (selectAttrNameToAdd == null) {
// Nothing to do
return;
}
// It seems this <option> is inside a <select th:field="...">, and the processor for that "th:field" has left
// as a local variable the name and value of the attribute to be added
final String selectAttrValueToAdd =
(String) context.getVariable(SpringSelectFieldTagProcessor.OPTION_IN_SELECT_ATTR_VALUE);
if (tag.hasAttribute(selectAttrNameToAdd)) {
if (!selectAttrValueToAdd.equals(tag.getAttributeValue(selectAttrNameToAdd))) {
throw new TemplateProcessingException(
"If specified (which is not required), attribute \"" + selectAttrNameToAdd + "\" in " +
"\"option\" tag must have exactly the same value as in its containing \"select\" tag");
}
}
// This attribute value does not need to be escaped, because we are just "transporting" the th:field in the
// container <select> to its <option>'s, without any modifications. It will be executed (and its results
// escaped) later...
structureHandler.setAttribute(selectAttrNameToAdd.getCompleteAttributeNames()[0], selectAttrValueToAdd);
| 210
| 358
| 568
|
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringSelectFieldTagProcessor.java
|
SpringSelectFieldTagProcessor
|
doProcess
|
class SpringSelectFieldTagProcessor extends AbstractSpringFieldTagProcessor {
static final String OPTION_IN_SELECT_ATTR_NAME = "%%OPTION_IN_SELECT_ATTR_NAME%%";
static final String OPTION_IN_SELECT_ATTR_VALUE = "%%OPTION_IN_SELECT_ATTR_VALUE%%";
public SpringSelectFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, SELECT_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
private final boolean isDisabled(final IProcessableElementTag tag) {
// Disabled = attribute "disabled" exists
return tag.hasAttribute(this.disabledAttributeDefinition.getAttributeName());
}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
final boolean multiple = tag.hasAttribute(this.multipleAttributeDefinition.getAttributeName());
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
structureHandler.setLocalVariable(OPTION_IN_SELECT_ATTR_NAME, attributeName);
structureHandler.setLocalVariable(OPTION_IN_SELECT_ATTR_VALUE, attributeValue);
if (multiple && !isDisabled(tag)) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel hiddenMethodElementModel = modelFactory.createModel();
final String hiddenName = WebDataBinder.DEFAULT_FIELD_MARKER_PREFIX + name;
final String type = "hidden";
final String value =
RequestDataValueProcessorUtils.processFormFieldValue(context, hiddenName, "1", type);
final Map<String,String> hiddenAttributes = new LinkedHashMap<String, String>(4,1.0f);
hiddenAttributes.put(TYPE_ATTR_NAME, type);
hiddenAttributes.put(NAME_ATTR_NAME, hiddenName);
hiddenAttributes.put(VALUE_ATTR_NAME, value);
final IStandaloneElementTag hiddenElementTag =
modelFactory.createStandaloneElementTag("input", hiddenAttributes, AttributeValueQuotes.DOUBLE, false, true);
hiddenMethodElementModel.add(hiddenElementTag);
// We insert this hidden before because <select>'s are open element (with body), and if we insert it
// after the element, we would be inserting the <input type="hidden"> inside the <select>, which would
// incorrect...
structureHandler.insertBefore(hiddenMethodElementModel);
}
| 258
| 525
| 783
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringSrcTagProcessor.java
|
SpringSrcTagProcessor
|
doProcess
|
class SpringSrcTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1000;
public static final String ATTR_NAME = "src";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private AttributeDefinition targetAttributeDefinition;
public SpringSrcTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, ATTR_NAME, ATTR_PRECEDENCE, false, true);
}
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, 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 = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed
newAttributeValue = RequestDataValueProcessorUtils.processUrl(context, newAttributeValue);
// Set the real, non prefixed attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
| 341
| 121
| 462
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringTextareaFieldTagProcessor.java
|
SpringTextareaFieldTagProcessor
|
doProcess
|
class SpringTextareaFieldTagProcessor extends AbstractSpringFieldTagProcessor {
public SpringTextareaFieldTagProcessor(final String dialectPrefix) {
super(dialectPrefix, TEXTAREA_TAG_NAME, null, null, true);
}
@Override
protected void doProcess(final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IThymeleafBindStatus bindStatus, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>}
}
|
String name = bindStatus.getExpression();
name = (name == null? "" : name);
final String id = computeId(context, tag, name, false);
final String value = SpringValueFormatter.getDisplayString(bindStatus.getValue(), bindStatus.getEditor(), true);
String processedValue =
RequestDataValueProcessorUtils.processFormFieldValue(context, name, value, "textarea");
if (!StringUtils.isEmpty(processedValue)) {
final char c0 = processedValue.charAt(0);
if (c0 == '\n') {
processedValue = '\n' + processedValue;
} else if (c0 == '\r' && processedValue.length() > 1 && processedValue.charAt(1) == '\n') {
processedValue = "\r\n" + processedValue;
} else if (c0 == '\r') {
processedValue = '\r' + processedValue;
}
}
StandardProcessorUtils.setAttribute(structureHandler, this.idAttributeDefinition, ID_ATTR_NAME, id); // No need to escape: this comes from an existing 'id' or from a token
StandardProcessorUtils.setAttribute(structureHandler, this.nameAttributeDefinition, NAME_ATTR_NAME, name); // No need to escape: this is a java-valid token
structureHandler.setBody((processedValue == null? "" : processedValue), false);
| 147
| 344
| 491
|
<methods>public void <init>(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], boolean) ,public void setAttributeDefinitions(org.thymeleaf.engine.AttributeDefinitions) <variables>public static final java.lang.String ATTR_NAME,public static final int ATTR_PRECEDENCE,protected static final java.lang.String CHECKED_ATTR_NAME,protected static final java.lang.String DISABLED_ATTR_NAME,protected static final java.lang.String ID_ATTR_NAME,protected static final java.lang.String INPUT_TAG_NAME,protected static final java.lang.String MULTIPLE_ATTR_NAME,protected static final java.lang.String NAME_ATTR_NAME,protected static final java.lang.String OPTION_TAG_NAME,protected static final java.lang.String SELECTED_ATTR_NAME,protected static final java.lang.String SELECT_TAG_NAME,private static final org.thymeleaf.templatemode.TemplateMode TEMPLATE_MODE,protected static final java.lang.String TEXTAREA_TAG_NAME,protected static final java.lang.String TYPE_ATTR_NAME,protected static final java.lang.String VALUE_ATTR_NAME,protected org.thymeleaf.engine.AttributeDefinition checkedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition disabledAttributeDefinition,private final non-sealed java.lang.String discriminatorAttrName,private final non-sealed java.lang.String[] discriminatorAttrValues,private org.thymeleaf.engine.AttributeDefinition discriminatorAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition idAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition multipleAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition nameAttributeDefinition,private final non-sealed boolean removeAttribute,protected org.thymeleaf.engine.AttributeDefinition selectedAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition typeAttributeDefinition,protected org.thymeleaf.engine.AttributeDefinition valueAttributeDefinition
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringUErrorsTagProcessor.java
|
SpringUErrorsTagProcessor
|
doProcess
|
class SpringUErrorsTagProcessor extends AbstractAttributeTagProcessor {
private static final String ERROR_DELIMITER = "<br />";
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "uerrors";
public SpringUErrorsTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, ATTR_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 IThymeleafBindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
if (bindStatus.isError()) {
final StringBuilder strBuilder = new StringBuilder();
final String[] errorMsgs = bindStatus.getErrorMessages();
for (int i = 0; i < errorMsgs.length; i++) {
if (i > 0) {
strBuilder.append(ERROR_DELIMITER);
}
final String displayString = SpringValueFormatter.getDisplayString(errorMsgs[i], false);
strBuilder.append(displayString);
}
structureHandler.setBody(strBuilder.toString(), false);
// Just in case we also have a th:errorclass in this tag
structureHandler.setLocalVariable(SpringContextVariableNames.THYMELEAF_FIELD_BIND_STATUS, bindStatus);
} else {
structureHandler.removeElement();
}
| 200
| 240
| 440
|
<methods><variables>private final non-sealed boolean removeAttribute
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/processor/SpringValueTagProcessor.java
|
SpringValueTagProcessor
|
setAttributeDefinitions
|
class SpringValueTagProcessor
extends AbstractStandardExpressionAttributeTagProcessor
implements IAttributeDefinitionsAware {
// This is 1010 in order to make sure it is executed after "name" and "type"
public static final int ATTR_PRECEDENCE = 1010;
public static final String TARGET_ATTR_NAME = "value";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
private static final String TYPE_ATTR_NAME = "type";
private static final String NAME_ATTR_NAME = "name";
private AttributeDefinition targetAttributeDefinition;
private AttributeDefinition fieldAttributeDefinition;
private AttributeDefinition typeAttributeDefinition;
private AttributeDefinition nameAttributeDefinition;
public SpringValueTagProcessor(final String dialectPrefix) {
super(TEMPLATE_MODE, dialectPrefix, TARGET_ATTR_NAME, ATTR_PRECEDENCE, false, false);
}
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) {
String newAttributeValue = HtmlEscape.escapeHtml4Xml(expressionResult == null ? "" : expressionResult.toString());
// Let RequestDataValueProcessor modify the attribute value if needed, but only in the case we don't also have
// a 'th:field' - in such case, we will let th:field do its job
if (!tag.hasAttribute(this.fieldAttributeDefinition.getAttributeName())) {
// We will need to know the 'name' and 'type' attribute values in order to (potentially) modify the 'value'
final String nameValue = tag.getAttributeValue(this.nameAttributeDefinition.getAttributeName());
final String typeValue = tag.getAttributeValue(this.typeAttributeDefinition.getAttributeName());
newAttributeValue =
RequestDataValueProcessorUtils.processFormFieldValue(context, nameValue, newAttributeValue, typeValue);
}
// Set the 'value' attribute
StandardProcessorUtils.replaceAttribute(structureHandler, attributeName, this.targetAttributeDefinition, TARGET_ATTR_NAME, (newAttributeValue == null? "" : newAttributeValue));
}
}
|
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions in order to being able to use much
// faster methods for setting/replacing attributes on the ElementAttributes implementation
final String dialectPrefix = getMatchingAttributeName().getMatchingAttributeName().getPrefix();
this.targetAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TARGET_ATTR_NAME);
this.fieldAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, dialectPrefix, AbstractSpringFieldTagProcessor.ATTR_NAME);
this.typeAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TYPE_ATTR_NAME);
this.nameAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, NAME_ATTR_NAME);
| 616
| 210
| 826
|
<methods><variables>private final non-sealed org.thymeleaf.standard.expression.StandardExpressionExecutionContext expressionExecutionContext,private final non-sealed boolean removeIfNoop
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/requestdata/RequestDataValueProcessorUtils.java
|
RequestDataValueProcessorUtils
|
processUrl
|
class RequestDataValueProcessorUtils {
public static String processAction(
final ITemplateContext context, final String action, final String httpMethod) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return action;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processAction(action, httpMethod);
}
public static String processFormFieldValue(
final ITemplateContext context, final String name, final String value, final String type) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return value;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processFormFieldValue(name, value, type);
}
public static Map<String, String> getExtraHiddenFields(final ITemplateContext context) {
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return null;
}
return thymeleafRequestContext.getRequestDataValueProcessor().getExtraHiddenFields();
}
public static String processUrl(final ITemplateContext context, final String url) {<FILL_FUNCTION_BODY>}
private RequestDataValueProcessorUtils() {
super();
}
}
|
final IThymeleafRequestContext thymeleafRequestContext = SpringContextUtils.getRequestContext(context);
if (thymeleafRequestContext == null) {
return url;
}
return thymeleafRequestContext.getRequestDataValueProcessor().processUrl(url);
| 394
| 76
| 470
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/templateresource/SpringResourceTemplateResource.java
|
SpringResourceTemplateResource
|
computeBaseName
|
class SpringResourceTemplateResource implements ITemplateResource {
private final Resource resource;
private final String characterEncoding;
public SpringResourceTemplateResource(
final ApplicationContext applicationContext, final String location, final String characterEncoding) {
super();
Validate.notNull(applicationContext, "Application Context cannot be null");
Validate.notEmpty(location, "Resource Location cannot be null or empty");
// Character encoding CAN be null (system default will be used)
this.resource = applicationContext.getResource(location);
this.characterEncoding = characterEncoding;
}
public SpringResourceTemplateResource(
final Resource resource, final String characterEncoding) {
super();
Validate.notNull(resource, "Resource cannot be null");
// Character encoding CAN be null (system default will be used)
this.resource = resource;
this.characterEncoding = characterEncoding;
}
public String getDescription() {
return this.resource.getDescription();
}
public String getBaseName() {
return computeBaseName(this.resource.getFilename());
}
public boolean exists() {
return this.resource.exists();
}
public Reader reader() throws IOException {
// Will never return null, but an IOException if not found
final InputStream inputStream = this.resource.getInputStream();
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) {
final Resource relativeResource;
try {
relativeResource = this.resource.createRelative(relativeLocation);
} catch (final IOException e) {
// Given we have delegated the createRelative(...) mechanism to Spring, it's better if we don't do
// any assumptions on what this IOException means and simply return a resource object that returns
// no reader and exists() == false.
return new SpringResourceInvalidRelativeTemplateResource(getDescription(), relativeLocation, e);
}
return new SpringResourceTemplateResource(relativeResource, this.characterEncoding);
}
static String computeBaseName(final String path) {<FILL_FUNCTION_BODY>}
private static final class SpringResourceInvalidRelativeTemplateResource implements ITemplateResource {
private final String originalResourceDescription;
private final String relativeLocation;
private final IOException ioException;
SpringResourceInvalidRelativeTemplateResource(
final String originalResourceDescription,
final String relativeLocation,
final IOException ioException) {
super();
this.originalResourceDescription = originalResourceDescription;
this.relativeLocation = relativeLocation;
this.ioException = ioException;
}
@Override
public String getDescription() {
return "Invalid relative resource for relative location \"" + this.relativeLocation +
"\" and original resource " + this.originalResourceDescription + ": " + this.ioException.getMessage();
}
@Override
public String getBaseName() {
return "Invalid relative resource for relative location \"" + this.relativeLocation +
"\" and original resource " + this.originalResourceDescription + ": " + this.ioException.getMessage();
}
@Override
public boolean exists() {
return false;
}
@Override
public Reader reader() throws IOException {
throw new IOException("Invalid relative resource", this.ioException);
}
@Override
public ITemplateResource relative(final String relativeLocation) {
return this;
}
@Override
public String toString() {
return getDescription();
}
}
}
|
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);
| 945
| 255
| 1,200
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/DetailedError.java
|
DetailedError
|
toString
|
class DetailedError {
private static final String GLOBAL_FIELD_NAME = "[global]";
private final String fieldName;
private final String code;
private final Object[] arguments;
private final String message;
public DetailedError(final String code, final Object[] arguments, final String message) {
this(GLOBAL_FIELD_NAME, code, arguments, message);
}
public DetailedError(
final String fieldName, final String code, final Object[] arguments, final String message) {
super();
Validate.notNull(fieldName, "Field name cannot be null");
Validate.notNull(message, "Message cannot be null");
this.fieldName = fieldName;
this.code = code;
this.arguments = arguments;
this.message = message;
}
public String getFieldName() {
return fieldName;
}
public String getCode() {
return code;
}
public Object[] getArguments() {
return arguments;
}
public String getMessage() {
return message;
}
public boolean isGlobal() {
return GLOBAL_FIELD_NAME.equalsIgnoreCase(this.fieldName);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(this.fieldName);
strBuilder.append(":");
strBuilder.append(this.message);
return strBuilder.toString();
| 337
| 55
| 392
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringContentTypeUtils.java
|
SpringContentTypeUtils
|
computeViewContentType
|
class SpringContentTypeUtils {
public static String computeViewContentType(
final IWebExchange webExchange, final String defaultContentType, final Charset defaultCharset) {<FILL_FUNCTION_BODY>}
private SpringContentTypeUtils() {
super();
}
}
|
if (webExchange == null) {
throw new IllegalArgumentException("Request cannot be null");
}
// First we will check if there is a content type already resolved by Spring's own content negotiation
// mechanism (see ContentNegotiatingViewResolver, which is autoconfigured in Spring Boot)
final MediaType negotiatedMediaType = (MediaType) webExchange.getAttributeValue(View.SELECTED_CONTENT_TYPE);
if (negotiatedMediaType != null && negotiatedMediaType.isConcrete()) {
final Charset negotiatedCharset = negotiatedMediaType.getCharset();
if (negotiatedCharset != null) {
return negotiatedMediaType.toString();
} else {
return ContentTypeUtils.combineContentTypeAndCharset(negotiatedMediaType.toString(), defaultCharset);
}
}
// We will apply the default charset here because, after all, we are in an HTTP environment, and
// the way charset is specified in HTTP is as a parameter in the same Content-Type HTTP header.
final String combinedContentType =
ContentTypeUtils.combineContentTypeAndCharset(defaultContentType, defaultCharset);
// Maybe there is no value for 'defaultValue', but anyway we might want to preserve the charset
// from the defaultContentType into the viewName-computed one
final Charset combinedCharset =
ContentTypeUtils.computeCharsetFromContentType(combinedContentType);
// If the request path offers clues on the content type that would be more appropriate (because it
// ends in ".html", ".xml", ".js", etc.), just use it
final String requestPathContentType =
ContentTypeUtils.computeContentTypeForRequestPath(webExchange.getRequest().getRequestPath(), combinedCharset);
if (requestPathContentType != null) {
return requestPathContentType;
}
// No way to determine a better/more specific content-type, so just return the (adequately combined) defaults
return combinedContentType;
| 81
| 497
| 578
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringReactiveModelAdditionsUtils.java
|
SpringReactiveModelAdditionsUtils
|
toReactiveModelAdditionName
|
class SpringReactiveModelAdditionsUtils {
private static final String REACTIVE_MODEL_ADDITIONS_PREFIX = "ThymeleafReactiveModelAdditions:";
public static boolean isReactiveModelAdditionName(final String name) {
return name != null && name.startsWith(REACTIVE_MODEL_ADDITIONS_PREFIX);
}
public static String fromReactiveModelAdditionName(final String name) {
if (!isReactiveModelAdditionName(name)) {
return name;
}
return name.substring(REACTIVE_MODEL_ADDITIONS_PREFIX.length());
}
public static String toReactiveModelAdditionName(final String name) {<FILL_FUNCTION_BODY>}
private SpringReactiveModelAdditionsUtils() {
super();
}
}
|
if (name == null) {
return null;
}
return REACTIVE_MODEL_ADDITIONS_PREFIX + name;
| 219
| 39
| 258
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringRequestUtils.java
|
SpringRequestUtils
|
checkViewNameNotInRequest
|
class SpringRequestUtils {
public static void checkViewNameNotInRequest(final String viewName, final IWebRequest request) {<FILL_FUNCTION_BODY>}
private static boolean containsExpression(final String text) {
final int textLen = text.length();
char c;
boolean expInit = false;
for (int i = 0; i < textLen; i++) {
c = text.charAt(i);
if (!expInit) {
if (c == '$' || c == '*' || c == '#' || c == '@' || c == '~') {
expInit = true;
}
} else {
if (c == '{') {
return true;
} else if (!Character.isWhitespace(c)) {
expInit = false;
}
}
}
return false;
}
private SpringRequestUtils() {
super();
}
}
|
final String vn = StringUtils.pack(viewName);
if (!containsExpression(vn)) {
// We are only worried about expressions coming from user input, so if the view name contains no
// expression at all, we should be safe at this stage.
return;
}
boolean found = false;
final String pathWithinApplication =
StringUtils.pack(UriEscape.unescapeUriPath(request.getPathWithinApplication()));
if (pathWithinApplication != null && containsExpression(pathWithinApplication)) {
// View name contains an expression, and it seems the path does too. This is too dangerous.
found = true;
}
if (!found) {
final Map<String,String[]> parameterMap = request.getParameterMap();
if (parameterMap != null && !parameterMap.isEmpty()) {
for (final String[] parameterValues : parameterMap.values()) {
for (int i = 0; !found && i < parameterValues.length; i++) {
final String parameterValue = StringUtils.pack(parameterValues[i]);
if (parameterValue != null && containsExpression(parameterValue) && vn.contains(parameterValue)) {
// Request parameter contains an expression, and it is contained in the view name. Too dangerous.
found = true;
}
}
if (found) {
break;
}
}
}
}
if (found) {
throw new TemplateProcessingException(
"View name contains an expression and so does either the URL path or one of the request " +
"parameters. This is forbidden in order to reduce the possibilities that direct user input " +
"is executed as a part of the view name.");
}
| 248
| 427
| 675
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringSelectedValueComparator.java
|
SpringSelectedValueComparator
|
exhaustiveCompare
|
class SpringSelectedValueComparator {
/*
* NOTE This code is based on org.springframework.web.servlet.tags.form.SelectedValueComparator as of Spring 5.0.0
* Original license is Apache License 2.0, which is the same as the license for this file.
* Original copyright notice is "Copyright 2002-2016 the original author or authors".
* Original authors are Rob Harrop and Juergen Hoeller.
*
* NOTE The code in this class has been adapted to use Thymeleaf's own BindStatus interfaces.
*/
public static boolean isSelected(final IThymeleafBindStatus bindStatus, final Object candidateValue) {
if (bindStatus == null) {
return (candidateValue == null);
}
// Check obvious equality matches with the candidate first,
// both with the rendered value and with the original value.
Object boundValue = bindStatus.getValue();
if (ObjectUtils.nullSafeEquals(boundValue, candidateValue)) {
return true;
}
Object actualValue = bindStatus.getActualValue();
if (actualValue != null && actualValue != boundValue &&
ObjectUtils.nullSafeEquals(actualValue, candidateValue)) {
return true;
}
if (actualValue != null) {
boundValue = actualValue;
} else if (boundValue == null) {
return false;
}
// Non-null value but no obvious equality with the candidate value:
// go into more exhaustive comparisons.
boolean selected = false;
if (boundValue.getClass().isArray()) {
selected = collectionCompare(CollectionUtils.arrayToList(boundValue), candidateValue, bindStatus);
} else if (boundValue instanceof Collection) {
selected = collectionCompare((Collection<?>) boundValue, candidateValue, bindStatus);
} else if (boundValue instanceof Map) {
selected = mapCompare((Map<?, ?>) boundValue, candidateValue, bindStatus);
}
if (!selected) {
selected = exhaustiveCompare(boundValue, candidateValue, bindStatus.getEditor(), null);
}
return selected;
}
private static boolean collectionCompare(
final Collection<?> boundCollection, final Object candidateValue, final IThymeleafBindStatus bindStatus) {
try {
if (boundCollection.contains(candidateValue)) {
return true;
}
} catch (ClassCastException ex) {
// Probably from a TreeSet - ignore.
}
return exhaustiveCollectionCompare(boundCollection, candidateValue, bindStatus);
}
private static boolean mapCompare(
final Map<?, ?> boundMap, final Object candidateValue, final IThymeleafBindStatus bindStatus) {
try {
if (boundMap.containsKey(candidateValue)) {
return true;
}
} catch (ClassCastException ex) {
// Probably from a TreeMap - ignore.
}
return exhaustiveCollectionCompare(boundMap.keySet(), candidateValue, bindStatus);
}
private static boolean exhaustiveCollectionCompare(
final Collection<?> collection, final Object candidateValue, final IThymeleafBindStatus bindStatus) {
final Map<PropertyEditor, Object> convertedValueCache = new HashMap<>(1);
PropertyEditor editor = null;
boolean candidateIsString = (candidateValue instanceof String);
if (!candidateIsString) {
editor = bindStatus.findEditor(candidateValue.getClass());
}
for (Object element : collection) {
if (editor == null && element != null && candidateIsString) {
editor = bindStatus.findEditor(element.getClass());
}
if (exhaustiveCompare(element, candidateValue, editor, convertedValueCache)) {
return true;
}
}
return false;
}
private static boolean exhaustiveCompare(
final Object boundValue, final Object candidate,
final PropertyEditor editor, final Map<PropertyEditor, Object> convertedValueCache) {<FILL_FUNCTION_BODY>}
private SpringSelectedValueComparator() {
super();
}
}
|
final String candidateDisplayString = SpringValueFormatter.getDisplayString(candidate, editor, false);
if (boundValue != null && boundValue.getClass().isEnum()) {
final Enum<?> boundEnum = (Enum<?>) boundValue;
final String enumCodeAsString = ObjectUtils.getDisplayString(boundEnum.name());
if (enumCodeAsString.equals(candidateDisplayString)) {
return true;
}
final String enumLabelAsString = ObjectUtils.getDisplayString(boundEnum.toString());
if (enumLabelAsString.equals(candidateDisplayString)) {
return true;
}
} else if (ObjectUtils.getDisplayString(boundValue).equals(candidateDisplayString)) {
return true;
} else if (editor != null && candidate instanceof String) {
// Try PE-based comparison (PE should *not* be allowed to escape creating thread)
final String candidateAsString = (String) candidate;
final Object candidateAsValue;
if (convertedValueCache != null && convertedValueCache.containsKey(editor)) {
candidateAsValue = convertedValueCache.get(editor);
} else {
editor.setAsText(candidateAsString);
candidateAsValue = editor.getValue();
if (convertedValueCache != null) {
convertedValueCache.put(editor, candidateAsValue);
}
}
if (ObjectUtils.nullSafeEquals(boundValue, candidateAsValue)) {
return true;
}
}
return false;
| 1,046
| 380
| 1,426
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringStandardExpressionUtils.java
|
SpringStandardExpressionUtils
|
containsSpELInstantiationOrStaticOrParam
|
class SpringStandardExpressionUtils {
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 containsSpELInstantiationOrStaticOrParam(final String expression) {<FILL_FUNCTION_BODY>}
private static boolean isPreviousStaticMarker(final String expression, final int idx) {
char c,c1;
int n = idx;
while (n-- != 0) {
c = expression.charAt(n);
if (c == 'T') {
if (n == 0) {
return true;
}
c1 = expression.charAt(n - 1);
return !isSafeIdentifierChar(c1);
} else if (!Character.isWhitespace(c)) {
return false;
}
}
return false;
}
private static boolean isSafeIdentifierChar(final char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
}
private SpringStandardExpressionUtils() {
super();
}
}
|
/*
* Checks whether the expression contains instantiation of objects ("new SomeClass") or makes use of
* static methods ("T(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
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;
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 == '(' && ((n - 1 >= 0) && isPreviousStaticMarker(exp, n))) {
return true;
}
}
return false;
| 370
| 641
| 1,011
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/util/SpringValueFormatter.java
|
SpringValueFormatter
|
getDisplayString
|
class SpringValueFormatter {
/*
* NOTE This code is based on org.springframework.web.servlet.tags.form.ValueFormatter as of Spring 5.0.0
* Original license is Apache License 2.0, which is the same as the license for this file.
* Original copyright notice is "Copyright 2002-2012 the original author or authors".
* Original authors are Rob Harrop and Juergen Hoeller.
*/
public static String getDisplayString(final Object value, final boolean htmlEscape) {
final String displayValue = ObjectUtils.getDisplayString(value);
return (htmlEscape ? HtmlUtils.htmlEscape(displayValue) : displayValue);
}
public static String getDisplayString(final Object value, final PropertyEditor propertyEditor, final boolean htmlEscape) {<FILL_FUNCTION_BODY>}
private SpringValueFormatter() {
super();
}
}
|
if (propertyEditor != null && !(value instanceof String)) {
try {
propertyEditor.setValue(value);
final String text = propertyEditor.getAsText();
if (text != null) {
return getDisplayString(text, htmlEscape);
}
} catch (final Throwable ex) {
// The PropertyEditor might not support this value... pass through.
}
}
return getDisplayString(value, htmlEscape);
| 244
| 119
| 363
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/web/webflux/MultiValueMapUtil.java
|
MultiValueMapUtil
|
cookieToStringArrayMultiMap
|
class MultiValueMapUtil {
static String[] EMPTY_VALUES = new String[0];
static Map<String,String[]> stringToStringArrayMultiMap(final MultiValueMap<String,String> multiValueMap) {
if (multiValueMap == null) {
return null;
}
final Map<String,String[]> stringArrayMap =
new LinkedHashMap<String,String[]>(multiValueMap.size() + 1, 1.0f);
for (final Map.Entry<String, List<String>> multiValueMapEntry : multiValueMap.entrySet()) {
final List<String> multiValueMapEntryValue = multiValueMapEntry.getValue();
stringArrayMap.put(
multiValueMapEntry.getKey(),
multiValueMapEntry.getValue().toArray(new String[multiValueMapEntryValue.size()]));
}
return Collections.unmodifiableMap(stringArrayMap);
}
static Map<String,String[]> cookieToStringArrayMultiMap(final MultiValueMap<String, HttpCookie> multiValueMap) {<FILL_FUNCTION_BODY>}
private MultiValueMapUtil() {
super();
}
}
|
if (multiValueMap == null) {
return null;
}
final Map<String,String[]> stringArrayMap =
new LinkedHashMap<String,String[]>(multiValueMap.size() + 1, 1.0f);
for (final Map.Entry<String, List<HttpCookie>> multiValueMapEntry : multiValueMap.entrySet()) {
stringArrayMap.put(
multiValueMapEntry.getKey(),
multiValueMapEntry.getValue().stream().map(HttpCookie::getValue).toArray(String[]::new));
}
return Collections.unmodifiableMap(stringArrayMap);
| 297
| 157
| 454
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/web/webflux/SpringWebFluxWebApplication.java
|
SpringWebFluxWebApplication
|
buildExchange
|
class SpringWebFluxWebApplication implements ISpringWebFluxWebApplication {
// This class is made NOT final so that it can be proxied by Dependency Injection frameworks
/*
* There is no equivalent in Spring WebFlux to an application-level attribute container (e.g. ServletContext).
* So for the attribute part of this interface, this implementation will simply keep an empty attribute map.
*/
private final ReactiveAdapterRegistry reactiveAdapterRegistry;
SpringWebFluxWebApplication(final ReactiveAdapterRegistry reactiveAdapterRegistry) {
super();
// reactiveAdapterRegistry can be null
this.reactiveAdapterRegistry = reactiveAdapterRegistry;
}
public static SpringWebFluxWebApplication buildApplication(final ReactiveAdapterRegistry reactiveAdapterRegistry) {
// reactiveAdapterRegistry can be null
return new SpringWebFluxWebApplication(reactiveAdapterRegistry);
}
public ISpringWebFluxWebExchange buildExchange(
final ServerWebExchange exchange, final Locale locale, final MediaType mediaType, final Charset charset) {<FILL_FUNCTION_BODY>}
@Override
public ReactiveAdapterRegistry getReactiveAdapterRegistry() {
return this.reactiveAdapterRegistry;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
throw new UnsupportedOperationException("No support for application-level attributes in Spring WebFlux");
}
@Override
public void removeAttribute(final String name) {
Validate.notNull(name, "Name cannot be null");
throw new UnsupportedOperationException("No support for application-level attributes in Spring WebFlux");
}
@Override
public boolean resourceExists(final String path) {
Validate.notNull(path, "Path cannot be null");
throw new UnsupportedOperationException("No support for webapplication-based resource resolution in Spring WebFlux");
}
@Override
public InputStream getResourceAsStream(final String path) {
Validate.notNull(path, "Path cannot be null");
throw new UnsupportedOperationException("No support for webapplication-based resource resolution in Spring WebFlux");
}
}
|
Validate.notNull(exchange, "ServerWebExchange cannot be null");
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(mediaType, "Media Type cannot be null");
Validate.notNull(charset, "Charset cannot be null");
final SpringWebFluxWebRequest request = new SpringWebFluxWebRequest(exchange.getRequest());
return new SpringWebFluxWebExchange(request, this, exchange, locale, mediaType, charset);
| 587
| 130
| 717
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/web/webflux/SpringWebFluxWebExchange.java
|
SpringWebFluxWebExchange
|
getPrincipal
|
class SpringWebFluxWebExchange implements ISpringWebFluxWebExchange {
private final SpringWebFluxWebRequest webRequest;
private final SpringWebFluxWebApplication webApplication;
private SpringWebFluxWebSession webSession; // can be null, and is always lazily initialized
private boolean webSessionInitialized;
private final ServerWebExchange exchange;
private final Locale locale;
private final MediaType mediaType;
private final Charset charset;
SpringWebFluxWebExchange(final SpringWebFluxWebRequest webRequest,
final SpringWebFluxWebApplication webApplication,
final ServerWebExchange exchange,
final Locale locale,
final MediaType mediaType,
final Charset charset) {
super();
Validate.notNull(webRequest, "Request cannot be null");
Validate.notNull(webApplication, "Application cannot be null");
Validate.notNull(exchange, "Server Web Exchange cannot be null");
Validate.notNull(locale, "Locale cannot be null");
Validate.notNull(mediaType, "Media Type cannot be null");
Validate.notNull(charset, "Charset cannot be null");
this.webRequest = webRequest;
this.webApplication = webApplication;
this.exchange = exchange;
this.locale = locale;
this.mediaType = mediaType;
this.charset = charset;
// Session is lazily initialized because it requires the model to have been resolved (from Mono<Session>)
this.webSession = null;
this.webSessionInitialized = false;
}
@Override
public ISpringWebFluxWebRequest getRequest() {
return this.webRequest;
}
@Override
public ISpringWebFluxWebSession getSession() {
// ServerWebExchange returns a Mono<WebSession>, which SpringStandardDialect makes sure to ask reactor to
// resolve before the view gets executed.
// NOTE this will not be available until just before the view starts executing
if (!this.webSessionInitialized) {
final WebSession session = this.exchange.getAttribute(SpringContextUtils.WEB_SESSION_ATTRIBUTE_NAME);
if (session != null) {
this.webSession = new SpringWebFluxWebSession(session);
this.webSessionInitialized = true;
}
}
return this.webSession;
}
@Override
public ISpringWebFluxWebApplication getApplication() {
return this.webApplication;
}
@Override
public Principal getPrincipal() {<FILL_FUNCTION_BODY>}
@Override
public Locale getLocale() {
// We prefer this to the one established in ServerWebExchange, as the in Spring WebFlux environments
// the view that is being processed might establish its own value for the locale.
return this.locale;
}
@Override
public String getContentType() {
return this.mediaType.toString();
}
@Override
public String getCharacterEncoding() {
return this.charset.name();
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(this.exchange.getAttributes());
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.exchange.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {
Validate.notNull(name, "Name cannot be null");
if (value == null) {
this.exchange.getAttributes().remove(name);
} else {
this.exchange.getAttributes().put(name, value);
}
}
@Override
public void removeAttribute(final String name) {
Validate.notNull(name, "Name cannot be null");
this.exchange.getAttributes().remove(name);
}
@Override
public Object getNativeExchangeObject() {
return this.exchange;
}
@Override
public String transformURL(final String url) {
return this.exchange.transformUrl(url);
}
}
|
// ServerWebExchange returns a Mono<Principal>, which SpringStandardDialect makes sure to ask reactor to
// resolve before the view gets executed.
// NOTE this will not be available until just before the view starts executing
return this.exchange.getAttribute(SpringContextUtils.WEB_EXCHANGE_PRINCIPAL_ATTRIBUTE_NAME);
| 1,078
| 94
| 1,172
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/web/webflux/SpringWebFluxWebSession.java
|
SpringWebFluxWebSession
|
setAttributeValue
|
class SpringWebFluxWebSession implements ISpringWebFluxWebSession {
private final WebSession session;
SpringWebFluxWebSession(final WebSession session) {
super();
Validate.notNull(session, "Session cannot be null");
this.session = session;
}
@Override
public boolean exists() {
return this.session.isStarted();
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(this.session.getAttributes());
}
@Override
public Object getAttributeValue(final String name) {
Validate.notNull(name, "Name cannot be null");
return this.session.getAttribute(name);
}
@Override
public void setAttributeValue(final String name, final Object value) {<FILL_FUNCTION_BODY>}
@Override
public void removeAttribute(final String name) {
Validate.notNull(name, "Name cannot be null");
this.session.getAttributes().remove(name);
}
@Override
public Object getNativeSessionObject() {
return this.session;
}
}
|
Validate.notNull(name, "Name cannot be null");
if (value == null) {
this.session.getAttributes().remove(name);
} else {
this.session.getAttributes().put(name, value);
}
| 300
| 64
| 364
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/webflow/view/AjaxThymeleafView.java
|
AjaxThymeleafView
|
render
|
class AjaxThymeleafView extends ThymeleafView implements AjaxEnabledView {
private static final Logger vlogger = LoggerFactory.getLogger(AjaxThymeleafView.class);
private static final String FRAGMENTS_PARAM = "fragments";
private AjaxHandler ajaxHandler = null;
public AjaxThymeleafView() {
super();
}
public AjaxHandler getAjaxHandler() {
return this.ajaxHandler;
}
public void setAjaxHandler(final AjaxHandler ajaxHandler) {
this.ajaxHandler = ajaxHandler;
}
@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {<FILL_FUNCTION_BODY>}
@SuppressWarnings({ "rawtypes", "unused" })
protected Set<String> getRenderFragments(
final Map model, final HttpServletRequest request, final HttpServletResponse response) {
final String fragmentsParam = request.getParameter(FRAGMENTS_PARAM);
final String[] renderFragments = StringUtils.commaDelimitedListToStringArray(fragmentsParam);
if (renderFragments.length == 0) {
return null;
}
if (renderFragments.length == 1) {
return Collections.singleton(renderFragments[0]);
}
return new HashSet<String>(Arrays.asList(renderFragments));
}
}
|
final AjaxHandler templateAjaxHandler = getAjaxHandler();
if (templateAjaxHandler == null) {
throw new ConfigurationException("[THYMELEAF] AJAX Handler set into " +
AjaxThymeleafView.class.getSimpleName() + " instance for template " +
getTemplateName() + " is null.");
}
if (templateAjaxHandler.isAjaxRequest(request, response)) {
final Set<String> fragmentsToRender = getRenderFragments(model, request, response);
if (fragmentsToRender == null || fragmentsToRender.size() == 0) {
vlogger.warn("[THYMELEAF] An Ajax request was detected, but no fragments were specified to be re-rendered. "
+ "Falling back to full page render. This can cause unpredictable results when processing "
+ "the ajax response on the client.");
super.render(model, request, response);
return;
}
super.renderFragment(fragmentsToRender, model, request, response);
} else {
super.render(model, request, response);
}
| 398
| 291
| 689
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public java.lang.String getMarkupSelector() ,public void render(Map<java.lang.String,?>, jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse) throws java.lang.Exception,public void setMarkupSelector(java.lang.String) <variables>private Set<java.lang.String> markupSelectors,private static final non-sealed java.lang.String pathVariablesSelector
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/webflow/view/AjaxThymeleafViewResolver.java
|
AjaxRedirectView
|
sendRedirect
|
class AjaxRedirectView extends RedirectView {
private static final Logger vlogger = LoggerFactory.getLogger(AjaxRedirectView.class);
private AjaxHandler ajaxHandler = new DefaultAjaxHandler();
AjaxRedirectView(final AjaxHandler ajaxHandler, final String redirectUrl,
final boolean redirectContextRelative, final boolean redirectHttp10Compatible) {
super(redirectUrl, redirectContextRelative, redirectHttp10Compatible);
this.ajaxHandler = ajaxHandler;
}
@Override
protected void sendRedirect(final HttpServletRequest request, final HttpServletResponse response,
final String targetUrl, final boolean http10Compatible)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (this.ajaxHandler == null) {
throw new ConfigurationException("[THYMELEAF] AJAX Handler set into " +
AjaxThymeleafViewResolver.class.getSimpleName() + " instance is null.");
}
if (this.ajaxHandler.isAjaxRequest(request, response)) {
if (vlogger.isTraceEnabled()) {
vlogger.trace(
"[THYMELEAF] RedirectView for URL \"{}\" is an AJAX request. AjaxHandler of class {} " +
"will be in charge of processing the request.", targetUrl, this.ajaxHandler.getClass().getName());
}
this.ajaxHandler.sendAjaxRedirect(targetUrl, request, response, false);
} else {
vlogger.trace(
"[THYMELEAF] RedirectView for URL \"{}\" is not an AJAX request. Request will be handled " +
"as a normal redirect", targetUrl);
super.sendRedirect(request, response, targetUrl, http10Compatible);
}
| 193
| 269
| 462
|
<methods>public void <init>() ,public void addStaticVariable(java.lang.String, java.lang.Object) ,public boolean getAlwaysProcessRedirectAndForward() ,public java.lang.String getCharacterEncoding() ,public java.lang.String getContentType() ,public java.lang.String[] getExcludedViewNames() ,public boolean getForceContentType() ,public int getOrder() ,public boolean getProducePartialOutputWhileProcessing() ,public Map<java.lang.String,java.lang.Object> getStaticVariables() ,public org.thymeleaf.spring6.ISpringTemplateEngine getTemplateEngine() ,public java.lang.String[] getViewNames() ,public boolean isRedirectContextRelative() ,public boolean isRedirectHttp10Compatible() ,public void setAlwaysProcessRedirectAndForward(boolean) ,public void setCharacterEncoding(java.lang.String) ,public void setContentType(java.lang.String) ,public void setExcludedViewNames(java.lang.String[]) ,public void setForceContentType(boolean) ,public void setOrder(int) ,public void setProducePartialOutputWhileProcessing(boolean) ,public void setRedirectContextRelative(boolean) ,public void setRedirectHttp10Compatible(boolean) ,public void setStaticVariables(Map<java.lang.String,?>) ,public void setTemplateEngine(org.thymeleaf.spring6.ISpringTemplateEngine) ,public void setViewClass(Class<? extends org.thymeleaf.spring6.view.AbstractThymeleafView>) ,public void setViewNames(java.lang.String[]) <variables>public static final java.lang.String FORWARD_URL_PREFIX,public static final java.lang.String REDIRECT_URL_PREFIX,private boolean alwaysProcessRedirectAndForward,private java.lang.String characterEncoding,private java.lang.String contentType,private java.lang.String[] excludedViewNames,private boolean forceContentType,private int order,private boolean producePartialOutputWhileProcessing,private boolean redirectContextRelative,private boolean redirectHttp10Compatible,private final Map<java.lang.String,java.lang.Object> staticVariables,private org.thymeleaf.spring6.ISpringTemplateEngine templateEngine,private Class<? extends org.thymeleaf.spring6.view.AbstractThymeleafView> viewClass,private java.lang.String[] viewNames,private static final org.slf4j.Logger vrlogger
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/webflow/view/FlowAjaxThymeleafView.java
|
FlowAjaxThymeleafView
|
getRenderFragments
|
class FlowAjaxThymeleafView extends AjaxThymeleafView {
public FlowAjaxThymeleafView() {
super();
}
@Override
@SuppressWarnings("rawtypes")
protected Set<String> getRenderFragments(
final Map model, final HttpServletRequest request, final HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
final RequestContext context = RequestContextHolder.getRequestContext();
if (context == null) {
return super.getRenderFragments(model, request, response);
}
final String[] fragments = (String[]) context.getFlashScope().get(View.RENDER_FRAGMENTS_ATTRIBUTE);
if (fragments == null || fragments.length == 0) {
return super.getRenderFragments(model, request, response);
}
if (fragments.length == 1) {
return Collections.singleton(fragments[0]);
}
return new HashSet<String>(Arrays.asList(fragments));
| 119
| 172
| 291
|
<methods>public void <init>() ,public org.springframework.webflow.context.servlet.AjaxHandler getAjaxHandler() ,public void render(Map<java.lang.String,?>, jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse) throws java.lang.Exception,public void setAjaxHandler(org.springframework.webflow.context.servlet.AjaxHandler) <variables>private static final java.lang.String FRAGMENTS_PARAM,private org.springframework.webflow.context.servlet.AjaxHandler ajaxHandler,private static final org.slf4j.Logger vlogger
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/cache/AbstractCacheManager.java
|
AbstractCacheManager
|
clearAllCaches
|
class AbstractCacheManager implements ICacheManager {
private volatile ICache<TemplateCacheKey,TemplateModel> templateCache;
private volatile boolean templateCacheInitialized = false;
private volatile ICache<ExpressionCacheKey,Object> expressionCache;
private volatile boolean expressionCacheInitialized = false;
protected AbstractCacheManager() {
super();
}
public final ICache<TemplateCacheKey, TemplateModel> getTemplateCache() {
if (!this.templateCacheInitialized) {
synchronized(this) {
if (!this.templateCacheInitialized) {
this.templateCache = initializeTemplateCache();
this.templateCacheInitialized = true;
}
}
}
return this.templateCache;
}
public final ICache<ExpressionCacheKey, Object> getExpressionCache() {
if (!this.expressionCacheInitialized) {
synchronized(this) {
if (!this.expressionCacheInitialized) {
this.expressionCache = initializeExpressionCache();
this.expressionCacheInitialized = true;
}
}
}
return this.expressionCache;
}
public <K, V> ICache<K, V> getSpecificCache(final String name) {
// No specific caches are used by default
return null;
}
public List<String> getAllSpecificCacheNames() {
// No specific caches are used by default
return Collections.emptyList();
}
public void clearAllCaches() {<FILL_FUNCTION_BODY>}
protected abstract ICache<TemplateCacheKey,TemplateModel> initializeTemplateCache();
protected abstract ICache<ExpressionCacheKey,Object> initializeExpressionCache();
}
|
final ICache<TemplateCacheKey, TemplateModel> templateCacheObj = getTemplateCache();
if (templateCacheObj != null) {
templateCacheObj.clear();
}
final ICache<ExpressionCacheKey, Object> expressionCacheObj = getExpressionCache();
if (expressionCacheObj != null) {
expressionCacheObj.clear();
}
final List<String> allSpecificCacheNamesObj = getAllSpecificCacheNames();
if (allSpecificCacheNamesObj != null) {
for (final String specificCacheName : allSpecificCacheNamesObj) {
final ICache<?,?> specificCache = getSpecificCache(specificCacheName);
if (specificCache != null) {
specificCache.clear();
}
}
}
| 431
| 198
| 629
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/cache/ExpressionCacheKey.java
|
ExpressionCacheKey
|
equals
|
class ExpressionCacheKey implements Serializable {
private static final long serialVersionUID = 872451230923L;
private final String type;
private final String expression0;
private final String expression1;
private final int h;
public ExpressionCacheKey(final String type, final String expression0) {
this(type, expression0, null);
}
public ExpressionCacheKey(final String type, final String expression0, final String expression1) {
super();
Validate.notNull(type, "Type cannot be null");
Validate.notNull(expression0, "Expression cannot be null");
this.type = type;
this.expression0 = expression0;
this.expression1 = expression1;
// This being a cache key, its equals and hashCode methods will potentially execute many
// times, so this could help performance
this.h = computeHashCode();
}
public String getType() {
return this.type;
}
public String getExpression0() {
return this.expression0;
}
public String getExpression1() {
return this.expression1;
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.h;
}
private int computeHashCode() {
int result = this.type.hashCode();
result = 31 * result + this.expression0.hashCode();
result = 31 * result + (this.expression1 != null ? this.expression1.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(this.type);
strBuilder.append('|');
strBuilder.append(this.expression0);
if (this.expression1 != null) {
strBuilder.append('|');
strBuilder.append(this.expression1);
}
return strBuilder.toString();
}
}
|
if (this == o) {
return true;
}
if (!(o instanceof ExpressionCacheKey)) {
return false;
}
final ExpressionCacheKey that = (ExpressionCacheKey) o;
if (this.h != that.h) { // fail fast
return false;
}
if (!this.type.equals(that.type)) {
return false;
}
if (!this.expression0.equals(that.expression0)) {
return false;
}
return this.expression1 != null ? this.expression1.equals(that.expression1) : that.expression1 == null;
| 537
| 167
| 704
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/cache/StandardCache.java
|
CacheDataContainer
|
putWithoutTracing
|
class CacheDataContainer<K,V> {
private final String name;
private final boolean sizeLimit;
private final int maxSize;
private final boolean traceExecution;
private final Logger logger;
private final ConcurrentHashMap<K,CacheEntry<V>> container;
private final Object[] fifo;
private int fifoPointer;
CacheDataContainer(final String name, final int initialCapacity,
final int maxSize, final boolean traceExecution, final Logger logger) {
super();
this.name = name;
this.container = new ConcurrentHashMap<K,CacheEntry<V>>(initialCapacity, 0.9f, 2);
this.maxSize = maxSize;
this.sizeLimit = (maxSize >= 0);
if (this.sizeLimit) {
this.fifo = new Object[this.maxSize];
Arrays.fill(this.fifo, null);
} else {
this.fifo = null;
}
this.fifoPointer = 0;
this.traceExecution = traceExecution;
this.logger = logger;
}
public CacheEntry<V> get(final Object key) {
// FIFO is not used for this --> better performance, but no LRU (only insertion order will apply)
return this.container.get(key);
}
public Set<K> keySet() {
// This 'strange' cast is needed in order to keep compatibility with Java 6 and 7, when compiling with
// Java 8. The reason is, the return type of Java 8's ConcurrentHashMap#keySet() changed to a class
// called KeySetView, implementing java.util.Set but new in Java 8. This made this code throw a
// java.lang.NoSuchMethodError when executed in Java 6 or 7.
// By adding the cast, we are binding bytecode not to the specific keySet() method of ConcurrentHashMap,
// but to the one defined at the java.util.Map interface, which simply returns java.util.Set.
return ((Map<K,CacheEntry<V>>)this.container).keySet();
}
public int put(final K key, final CacheEntry<V> value) {
if (this.traceExecution) {
return putWithTracing(key, value);
}
return putWithoutTracing(key, value);
}
private int putWithoutTracing(final K key, final CacheEntry<V> value) {<FILL_FUNCTION_BODY>}
private synchronized int putWithTracing(final K key, final CacheEntry<V> value) {
final CacheEntry<V> existing = this.container.putIfAbsent(key, value);
if (existing == null) {
if (this.sizeLimit) {
final Object removedKey = this.fifo[this.fifoPointer];
if (removedKey != null) {
final CacheEntry<V> removed = this.container.remove(removedKey);
if (removed != null) {
final Integer newSize = Integer.valueOf(this.container.size());
this.logger.trace(
"[THYMELEAF][{}][{}][CACHE_REMOVE][{}] Max size exceeded for cache \"{}\". Removing entry for key \"{}\". New size is {}.",
new Object[] {TemplateEngine.threadIndex(), this.name, newSize, this.name, removedKey, newSize});
}
}
this.fifo[this.fifoPointer] = key;
this.fifoPointer = (this.fifoPointer + 1) % this.maxSize;
}
}
return this.container.size();
}
public int remove(final K key) {
if (this.traceExecution) {
return removeWithTracing(key);
}
return removeWithoutTracing(key);
}
private int removeWithoutTracing(final K key) {
// FIFO is also updated to avoid 'removed' keys remaining at FIFO (which could end up reducing cache size to 1)
final CacheEntry<V> removed = this.container.remove(key);
if (removed != null) {
if (this.sizeLimit && key != null) {
for (int i = 0; i < this.maxSize; i++) {
if (key.equals(this.fifo[i])) {
this.fifo[i] = null;
break;
}
}
}
}
return -1;
}
private synchronized int removeWithTracing(final K key) {
// FIFO is also updated to avoid 'removed' keys remaining at FIFO (which could end up reducing cache size to 1)
final CacheEntry<V> removed = this.container.remove(key);
if (removed == null) {
// When tracing is active, this means nothing was removed
return -1;
}
if (this.sizeLimit && key != null) {
for (int i = 0; i < this.maxSize; i++) {
if (key.equals(this.fifo[i])) {
this.fifo[i] = null;
break;
}
}
}
return this.container.size();
}
public void clear() {
this.container.clear();
}
public int size() {
return this.container.size();
}
}
|
// If we are not tracing, it's better to avoid the size() operation which has
// some performance implications in ConcurrentHashMap (iteration and counting these maps
// is slow if they are big)
final CacheEntry<V> existing = this.container.putIfAbsent(key, value);
if (existing != null) {
// When not in 'trace' mode, will always return -1
return -1;
}
if (this.sizeLimit) {
synchronized (this.fifo) {
final Object removedKey = this.fifo[this.fifoPointer];
if (removedKey != null) {
this.container.remove(removedKey);
}
this.fifo[this.fifoPointer] = key;
this.fifoPointer = (this.fifoPointer + 1) % this.maxSize;
}
}
return -1;
| 1,396
| 240
| 1,636
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/cache/TTLCacheEntryValidity.java
|
TTLCacheEntryValidity
|
isCacheStillValid
|
class TTLCacheEntryValidity
implements ICacheEntryValidity {
private final long cacheTTLMs;
private final long creationTimeInMillis;
/**
* <p>
* Creates a new instance of this validity implementation.
* </p>
*
* @param cacheTTLMs the TTL to be applied to the template resolution.
*/
public TTLCacheEntryValidity(final long cacheTTLMs) {
super();
this.cacheTTLMs = cacheTTLMs;
this.creationTimeInMillis = System.currentTimeMillis();
}
/**
* <p>
* Returns the TTL in milliseconds to be applied to template
* validity.
* </p>
*
* @return the TTL in milliseconds
*/
public long getCacheTTLMs() {
return this.cacheTTLMs;
}
/**
* <p>
* Returns true. Templates are always considered cacheable using this
* validity implementation.
* </p>
*
* @return true
*/
public boolean isCacheable() {
return true;
}
/**
* <p>
* Returns whether the template resolution can still be considered valid. This
* is done by computing the difference in milliseconds between the moment when
* this object was created and the moment this method is called, and checking
* it is less than the established TTL (time-to-live).
* </p>
*
* @return whether the (cached) template resolution can still be considered valid.
*/
public boolean isCacheStillValid() {<FILL_FUNCTION_BODY>}
}
|
final long currentTimeInMillis = System.currentTimeMillis();
return (currentTimeInMillis < this.creationTimeInMillis + this.cacheTTLMs);
| 461
| 46
| 507
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/cache/TemplateCacheKey.java
|
TemplateCacheKey
|
computeHashCode
|
class TemplateCacheKey implements Serializable {
private static final long serialVersionUID = 45842555123291L;
private final String ownerTemplate;
private final String template;
private final Set<String> templateSelectors;
private final int lineOffset;
private final int colOffset;
private final TemplateMode templateMode;
private final Map<String,Object> templateResolutionAttributes;
private final int h;
public TemplateCacheKey(
final String ownerTemplate, final String template, final Set<String> templateSelectors,
final int lineOffset, final int colOffset, final TemplateMode templateMode,
final Map<String,Object> templateResolutionAttributes) {
// NOTE we are assuming that templateSelectors is either null or a non-empty, naturally-ordered set. Also,
// we are also assuming that templateResolutionAttributes is either null or non-empty. Also, BOTH
// should be unmodifiable. This should have been sorted out at the TemplateSpec constructor.
super();
// ownerTemplate will be null if this template is standalone (not something we are processing from inside another one like e.g. an inlining)
Validate.notNull(template, "Template cannot be null");
// templateSelectors can be null if we are selecting the entire template
// templateMode can be null if this template is standalone (no owner template) AND we are forcing a specific template mode for its processing
// templateResolutionAttributes
this.ownerTemplate = ownerTemplate;
this.template = template;
this.templateSelectors = templateSelectors;
this.lineOffset = lineOffset;
this.colOffset = colOffset;
this.templateMode = templateMode;
this.templateResolutionAttributes = templateResolutionAttributes;
// This being a cache key, its equals and hashCode methods will potentially execute many
// times, so this could help performance
this.h = computeHashCode();
}
public String getOwnerTemplate() {
return this.ownerTemplate;
}
public String getTemplate() {
return this.template;
}
public Set<String> getTemplateSelectors() {
return this.templateSelectors;
}
public int getLineOffset() {
return this.lineOffset;
}
public int getColOffset() {
return this.colOffset;
}
public TemplateMode getTemplateMode() {
return this.templateMode;
}
public Map<String, Object> getTemplateResolutionAttributes() {
return this.templateResolutionAttributes;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TemplateCacheKey)) {
return false;
}
final TemplateCacheKey that = (TemplateCacheKey) o;
if (this.h != that.h) { // fail fast
return false;
}
if (this.lineOffset != that.lineOffset) {
return false;
}
if (this.colOffset != that.colOffset) {
return false;
}
if (this.ownerTemplate != null ? !this.ownerTemplate.equals(that.ownerTemplate) : that.ownerTemplate != null) {
return false;
}
if (!this.template.equals(that.template)) {
return false;
}
if (this.templateSelectors != null ? !this.templateSelectors.equals(that.templateSelectors) : that.templateSelectors != null) {
return false;
}
if (this.templateMode != that.templateMode) {
return false;
}
// Note how it is important that template resolution attribute values correctly implement equals() and hashCode()
return !(this.templateResolutionAttributes != null ? !this.templateResolutionAttributes.equals(that.templateResolutionAttributes) : that.templateResolutionAttributes != null);
}
@Override
public int hashCode() {
return this.h;
}
private int computeHashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(LoggingUtils.loggifyTemplateName(this.template));
if (this.ownerTemplate != null) {
strBuilder.append('@');
strBuilder.append('(');
strBuilder.append(LoggingUtils.loggifyTemplateName(this.ownerTemplate));
strBuilder.append(';');
strBuilder.append(this.lineOffset);
strBuilder.append(',');
strBuilder.append(this.colOffset);
strBuilder.append(')');
}
if (this.templateSelectors != null) {
strBuilder.append("::");
strBuilder.append(this.templateSelectors);
}
if (this.templateMode != null) {
strBuilder.append(" @");
strBuilder.append(this.templateMode);
}
if (this.templateResolutionAttributes != null) {
strBuilder.append(" (");
strBuilder.append(this.templateResolutionAttributes);
strBuilder.append(")");
}
return strBuilder.toString();
}
}
|
int result = this.ownerTemplate != null ? this.ownerTemplate.hashCode() : 0;
result = 31 * result + this.template.hashCode();
result = 31 * result + (this.templateSelectors != null ? this.templateSelectors.hashCode() : 0);
result = 31 * result + this.lineOffset;
result = 31 * result + this.colOffset;
result = 31 * result + (this.templateMode != null ? this.templateMode.hashCode() : 0);
result = 31 * result + (this.templateResolutionAttributes != null ? this.templateResolutionAttributes.hashCode() : 0);
return result;
| 1,333
| 173
| 1,506
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/AbstractEngineContext.java
|
AbstractEngineContext
|
getExpressionObjects
|
class AbstractEngineContext implements IEngineContext {
// NOTE we are not extending AbstractContext or AbstractExpressionContext on purpose, as the variable-oriented
// methods are going to be handled by the subclasses, not any superclasses.
private final IEngineConfiguration configuration;
private final Map<String,Object> templateResolutionAttributes;
private final Locale locale;
private IExpressionObjects expressionObjects = null;
private IdentifierSequences identifierSequences = null;
protected AbstractEngineContext(
final IEngineConfiguration configuration,
final Map<String,Object> templateResolutionAttributes,
final Locale locale) {
super();
Validate.notNull(configuration, "Configuration cannot be null");
// templateResolutionAttributes CAN be null
Validate.notNull(locale, "Locale cannot be null");
this.configuration = configuration;
this.locale = locale;
this.templateResolutionAttributes = templateResolutionAttributes;
// Most templates will not need this, so we will initialize it lazily
this.identifierSequences = null;
}
public final IEngineConfiguration getConfiguration() {
return this.configuration;
}
public final Map<String,Object> getTemplateResolutionAttributes() {
return this.templateResolutionAttributes;
}
public final Locale getLocale() {
return this.locale;
}
public final IExpressionObjects getExpressionObjects() {<FILL_FUNCTION_BODY>}
public final TemplateMode getTemplateMode() {
return getTemplateData().getTemplateMode();
}
public final IModelFactory getModelFactory() {
return this.configuration.getModelFactory(getTemplateMode());
}
public final String getMessage(
final Class<?> origin, final String key, final Object[] messageParameters, final boolean useAbsentMessageRepresentation) {
// origin CAN be null
Validate.notNull(key, "Message key cannot be null");
// messageParameter CAN be null
final Set<IMessageResolver> messageResolvers = this.configuration.getMessageResolvers();
// Try to resolve the message
for (final IMessageResolver messageResolver : messageResolvers) {
final String resolvedMessage =
messageResolver.resolveMessage(this, origin, key, messageParameters);
if (resolvedMessage != null) {
return resolvedMessage;
}
}
// Message unresolved: try to create an "absent message representation" (if specified to do so)
if (useAbsentMessageRepresentation) {
for (final IMessageResolver messageResolver : messageResolvers) {
final String absentMessageRepresentation =
messageResolver.createAbsentMessageRepresentation(this, origin, key, messageParameters);
if (absentMessageRepresentation != null) {
return absentMessageRepresentation;
}
}
}
return null;
}
public final String buildLink(final String base, final Map<String, Object> parameters) {
// base CAN be null
// parameters CAN be null
final Set<ILinkBuilder> linkBuilders = this.configuration.getLinkBuilders();
// Try to resolve the message
for (final ILinkBuilder linkBuilder : linkBuilders) {
final String link = linkBuilder.buildLink(this, base, parameters);
if (link != null) {
return link;
}
}
// Message unresolved: this should never happen, so we should fail
throw new TemplateProcessingException(
"No configured link builder instance was able to build link with base \"" + base + "\" and " +
"parameters " + parameters);
}
public final IdentifierSequences getIdentifierSequences() {
// No problem in lazily initializing this here, as context objects should not be used by
// multiple threads.
if (this.identifierSequences == null) {
this.identifierSequences = new IdentifierSequences();
}
return this.identifierSequences;
}
}
|
// We delay creation of expression objects in case they are not needed at all
if (this.expressionObjects == null) {
this.expressionObjects = new ExpressionObjects(this, this.configuration.getExpressionObjectFactory());
}
return this.expressionObjects;
| 1,014
| 66
| 1,080
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/AbstractExpressionContext.java
|
AbstractExpressionContext
|
getExpressionObjects
|
class AbstractExpressionContext extends AbstractContext implements IExpressionContext {
private final IEngineConfiguration configuration;
private IExpressionObjects expressionObjects = null;
protected AbstractExpressionContext(final IEngineConfiguration configuration) {
super();
Validate.notNull(configuration, "Configuration cannot be null");
this.configuration = configuration;
}
protected AbstractExpressionContext(final IEngineConfiguration configuration, final Locale locale) {
super(locale);
Validate.notNull(configuration, "Configuration cannot be null");
this.configuration = configuration;
}
protected AbstractExpressionContext(
final IEngineConfiguration configuration, final Locale locale, final Map<String, Object> variables) {
super(locale, variables);
Validate.notNull(configuration, "Configuration cannot be null");
this.configuration = configuration;
}
@Override
public final IEngineConfiguration getConfiguration() {
return this.configuration;
}
@Override
public IExpressionObjects getExpressionObjects() {<FILL_FUNCTION_BODY>}
}
|
// We delay creation of expression objects in case they are not needed at all
if (this.expressionObjects == null) {
this.expressionObjects = new ExpressionObjects(this, this.configuration.getExpressionObjectFactory());
}
return this.expressionObjects;
| 264
| 66
| 330
|
<methods>public void clearVariables() ,public final boolean containsVariable(java.lang.String) ,public final java.util.Locale getLocale() ,public final java.lang.Object getVariable(java.lang.String) ,public final Set<java.lang.String> getVariableNames() ,public void removeVariable(java.lang.String) ,public void setLocale(java.util.Locale) ,public void setVariable(java.lang.String, java.lang.Object) ,public void setVariables(Map<java.lang.String,java.lang.Object>) <variables>private java.util.Locale locale,private final non-sealed Map<java.lang.String,java.lang.Object> variables
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/IdentifierSequences.java
|
IdentifierSequences
|
getPreviousIDSeq
|
class IdentifierSequences {
private final Map<String,Integer> idCounts;
public IdentifierSequences() {
super();
this.idCounts = new HashMap<String,Integer>(1,1.0f);
}
/**
* <p>
* Returns a new index (ID count) for a specific
* value of the {@code id} attribute, and increments
* the count.
* </p>
*
* @param id the ID for which the count will be computed
* @return the new count, ready to be used
*/
public Integer getAndIncrementIDSeq(final String id) {
Validate.notNull(id, "ID cannot be null");
Integer count = this.idCounts.get(id);
if (count == null) {
count = Integer.valueOf(1);
}
this.idCounts.put(id, Integer.valueOf(count.intValue() + 1));
return count;
}
/**
* <p>
* Returns the index (ID count) for a specific
* value of the {@code id} attribute without incrementing
* the count.
* </p>
*
* @param id the ID for which the count will be retrieved
* @return the current count
*/
public Integer getNextIDSeq(final String id) {
Validate.notNull(id, "ID cannot be null");
Integer count = this.idCounts.get(id);
if (count == null) {
count = Integer.valueOf(1);
}
return count;
}
/**
* <p>
* Returns the last index (ID count) returned for a specific
* value of the {@code id} attribute (without incrementing
* the count).
* </p>
*
* @param id the ID for which the last count will be retrieved
* @return the count
*/
public Integer getPreviousIDSeq(final String id) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(id, "ID cannot be null");
final Integer count = this.idCounts.get(id);
if (count == null) {
throw new TemplateProcessingException(
"Cannot obtain previous ID count for ID \"" + id + "\"");
}
return Integer.valueOf(count.intValue() - 1);
| 542
| 91
| 633
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/LazyContextVariable.java
|
LazyContextVariable
|
getValue
|
class LazyContextVariable<T> implements ILazyContextVariable<T> {
private volatile boolean initialized = false;
private T value;
protected LazyContextVariable() {
super();
}
/**
* <p>
* Lazily resolve the value.
* </p>
* <p>
* This will be transparently called by the Thymeleaf engine at template rendering time when an object
* of this class is resolved in a Thymeleaf expression.
* </p>
* <p>
* Note lazy variables will be resolved just once, and their resolved values will be reused as many times
* as they appear in the template.
* </p>
*
* @return the resolved value.
*/
public final T getValue() {<FILL_FUNCTION_BODY>}
/**
* <p>
* Perform the actual resolution of the variable's value.
* </p>
* <p>
* This method will be called only once, the first time this variable is resolved.
* </p>
*
* @return the resolved value.
*/
protected abstract T loadValue();
}
|
if (!this.initialized) {
synchronized (this) {
if (!this.initialized) {
this.value = loadValue();
this.initialized = true;
}
}
}
return this.value;
| 312
| 65
| 377
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/context/StandardEngineContextFactory.java
|
StandardEngineContextFactory
|
createEngineContext
|
class StandardEngineContextFactory implements IEngineContextFactory {
public StandardEngineContextFactory() {
super();
}
public IEngineContext createEngineContext(
final IEngineConfiguration configuration, final TemplateData templateData,
final Map<String, Object> templateResolutionAttributes, final IContext context) {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(context, "Context object cannot be null");
// NOTE calling getVariableNames() on an IWebContext would be very expensive, as it would mean
// calling HttpServletRequest#getAttributeNames(), which is very slow in some common implementations
// (e.g. Apache Tomcat). So it's a good thing we might have tried to reuse the IEngineContext
// before calling this factory.
final Set<String> variableNames = context.getVariableNames();
if (variableNames == null || variableNames.isEmpty()) {
if (Contexts.isWebContext(context)) {
final IWebContext webContext = Contexts.asWebContext(context);
return new WebEngineContext(
configuration, templateData, templateResolutionAttributes,
webContext.getExchange(),
webContext.getLocale(), Collections.EMPTY_MAP);
}
return new EngineContext(
configuration, templateData, templateResolutionAttributes,
context.getLocale(), Collections.EMPTY_MAP);
}
final Map<String,Object> variables = new LinkedHashMap<String, Object>(variableNames.size() + 1, 1.0f);
for (final String variableName : variableNames) {
variables.put(variableName, context.getVariable(variableName));
}
if (Contexts.isWebContext(context)) {
final IWebContext webContext = Contexts.asWebContext(context);
return new WebEngineContext(
configuration, templateData, templateResolutionAttributes,
webContext.getExchange(),
webContext.getLocale(), variables);
}
return new EngineContext(
configuration, templateData, templateResolutionAttributes,
context.getLocale(), variables);
| 96
| 433
| 529
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AbstractElementTag.java
|
AbstractElementTag
|
toString
|
class AbstractElementTag extends AbstractTemplateEvent implements IElementTag {
final TemplateMode templateMode;
final ElementDefinition elementDefinition;
final String elementCompleteName;
final boolean synthetic;
protected AbstractElementTag(
final TemplateMode templateMode,
final ElementDefinition elementDefinition,
final String elementCompleteName,
final boolean synthetic) {
super();
this.templateMode = templateMode;
this.elementDefinition = elementDefinition;
this.elementCompleteName = elementCompleteName;
this.synthetic = synthetic;
}
protected AbstractElementTag(
final TemplateMode templateMode,
final ElementDefinition elementDefinition,
final String elementCompleteName,
final boolean synthetic,
final String templateName, final int line, final int col) {
super(templateName, line, col);
this.templateMode = templateMode;
this.elementDefinition = elementDefinition;
this.elementCompleteName = elementCompleteName;
this.synthetic = synthetic;
}
public final TemplateMode getTemplateMode() {
return this.templateMode;
}
public final String getElementCompleteName() {
return this.elementCompleteName;
}
public final ElementDefinition getElementDefinition() {
return this.elementDefinition;
}
public final boolean isSynthetic() {
return this.synthetic;
}
@Override
public final String toString() {<FILL_FUNCTION_BODY>}
}
|
final Writer stringWriter = new FastStringWriter();
try {
write(stringWriter);
} catch (final IOException e) {
throw new TemplateProcessingException("Exception while creating String representation of model entity", e);
}
return stringWriter.toString();
| 376
| 68
| 444
|
<methods>public final int getCol() ,public final int getLine() ,public final java.lang.String getTemplateName() ,public final boolean hasLocation() <variables>final non-sealed int col,final non-sealed int line,final non-sealed java.lang.String templateName
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AbstractGatheringModelProcessable.java
|
AbstractGatheringModelProcessable
|
gatherText
|
class AbstractGatheringModelProcessable implements IGatheringModelProcessable {
private final ProcessorTemplateHandler processorTemplateHandler;
private final IEngineContext context;
private final Model syntheticModel;
private final TemplateModelController modelController;
private final TemplateFlowController flowController;
private final SkipBody buildTimeSkipBody;
private final boolean buildTimeSkipCloseTag;
private final ProcessorExecutionVars processorExecutionVars;
private boolean gatheringFinished = false;
private int modelLevel;
AbstractGatheringModelProcessable(
final IEngineConfiguration configuration, final ProcessorTemplateHandler processorTemplateHandler, final IEngineContext context,
final TemplateModelController modelController, final TemplateFlowController flowController,
final SkipBody buildTimeSkipBody, final boolean buildTimeSkipCloseTag,
final ProcessorExecutionVars processorExecutionVars) {
super();
this.processorTemplateHandler = processorTemplateHandler;
this.context = context;
this.modelController = modelController;
this.flowController = flowController;
this.buildTimeSkipBody = buildTimeSkipBody;
this.buildTimeSkipCloseTag = buildTimeSkipCloseTag;
if (this.context == null) {
throw new TemplateProcessingException(
"Neither iteration nor model gathering are supported because local variable support is DISABLED. " +
"This is due to the use of an implementation of the " + ITemplateContext.class.getName() + " interface " +
"that does not provide local-variable support. In order to have local-variable support, the context " +
"implementation should also implement the " + IEngineContext.class.getName() +
" interface");
}
this.syntheticModel = new Model(configuration, context.getTemplateMode());
this.processorExecutionVars = processorExecutionVars.cloneVars();
this.gatheringFinished = false;
this.modelLevel = 0;
}
public final void resetGatheredSkipFlagsAfterNoIterations() {
if (this.buildTimeSkipBody == SkipBody.PROCESS_ONE_ELEMENT) {
this.modelController.skip(SkipBody.SKIP_ELEMENTS, this.buildTimeSkipCloseTag);
} else {
this.modelController.skip(this.buildTimeSkipBody, this.buildTimeSkipCloseTag);
}
}
public final void resetGatheredSkipFlags() {
this.modelController.skip(this.buildTimeSkipBody, this.buildTimeSkipCloseTag);
}
protected final void prepareProcessing() {
this.processorTemplateHandler.setCurrentGatheringModel(this);
resetGatheredSkipFlags();
}
protected final ProcessorTemplateHandler getProcessorTemplateHandler() {
return this.processorTemplateHandler;
}
protected final TemplateFlowController getFlowController() {
return this.flowController;
}
public final boolean isGatheringFinished() {
return this.gatheringFinished;
}
protected final IEngineContext getContext() {
return this.context;
}
public ProcessorExecutionVars initializeProcessorExecutionVars() {
// This was cloned during construction
return this.processorExecutionVars;
}
public final Model getInnerModel() {
return this.syntheticModel;
}
public final void gatherText(final IText text) {<FILL_FUNCTION_BODY>}
public final void gatherComment(final IComment comment) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(comment);
}
public final void gatherCDATASection(final ICDATASection cdataSection) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(cdataSection);
}
public final void gatherStandaloneElement(final IStandaloneElementTag standaloneElementTag) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(standaloneElementTag);
if (this.modelLevel == 0) {
this.gatheringFinished = true;
}
}
public final void gatherOpenElement(final IOpenElementTag openElementTag) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(openElementTag);
this.modelLevel++;
}
public final void gatherCloseElement(final ICloseElementTag closeElementTag) {
if (closeElementTag.isUnmatched()) {
gatherUnmatchedCloseElement(closeElementTag);
return;
}
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.modelLevel--;
this.syntheticModel.add(closeElementTag);
if (this.modelLevel == 0) {
// OK, we are finished gathering, this close tag ends the process
this.gatheringFinished = true;
}
}
public final void gatherUnmatchedCloseElement(final ICloseElementTag closeElementTag) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(closeElementTag);
}
public final void gatherDocType(final IDocType docType) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(docType);
}
public final void gatherXMLDeclaration(final IXMLDeclaration xmlDeclaration) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(xmlDeclaration);
}
public final void gatherProcessingInstruction(final IProcessingInstruction processingInstruction) {
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(processingInstruction);
}
}
|
if (this.gatheringFinished) {
throw new TemplateProcessingException("Gathering is finished already! We cannot gather more events");
}
this.syntheticModel.add(text);
| 1,667
| 53
| 1,720
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AbstractTemplateEvent.java
|
AbstractTemplateEvent
|
hasLocation
|
class AbstractTemplateEvent implements ITemplateEvent {
final String templateName;
final int line;
final int col;
AbstractTemplateEvent() {
this(null, -1, -1);
}
AbstractTemplateEvent(final String templateName, final int line, final int col) {
super();
this.templateName = templateName;
this.line = line;
this.col = col;
}
AbstractTemplateEvent(final AbstractTemplateEvent original) {
super();
this.templateName = original.templateName;
this.line = original.line;
this.col = original.col;
}
public final boolean hasLocation() {<FILL_FUNCTION_BODY>}
public final String getTemplateName() {
return this.templateName;
}
public final int getLine() {
return this.line;
}
public final int getCol() {
return this.col;
}
}
|
return (this.templateName != null && this.line != -1 && this.col != -1);
| 254
| 31
| 285
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AbstractTextualTemplateEvent.java
|
AbstractTextualTemplateEvent
|
computeInlineable
|
class AbstractTextualTemplateEvent extends AbstractTemplateEvent implements IEngineTemplateEvent {
private final CharSequence contentCharSeq;
private final String contentStr;
private final int contentLength;
private volatile String computedContentStr = null;
private volatile int computedContentLength = -1;
private volatile Boolean computedContentIsWhitespace = null;
private volatile Boolean computedContentIsInlineable = null;
AbstractTextualTemplateEvent(final CharSequence content) {
super();
this.contentCharSeq = content;
if (content != null && content instanceof String) {
this.contentStr = (String)content;
this.contentLength = content.length();
} else {
this.contentStr = null;
this.contentLength = -1;
}
}
AbstractTextualTemplateEvent(final CharSequence content, final String templateName, final int line, final int col) {
super(templateName, line, col);
this.contentCharSeq = content;
if (content != null && content instanceof String) {
this.contentStr = (String)content;
this.contentLength = content.length();
} else {
this.contentStr = null;
this.contentLength = -1;
}
}
protected final String getContentText() {
if (this.contentStr != null || this.contentCharSeq == null) {
return this.contentStr;
}
String t = this.computedContentStr;
if (t == null) {
this.computedContentStr = t = this.contentCharSeq.toString();
}
return t;
}
protected final int getContentLength() {
if (this.contentLength >= 0 || this.contentCharSeq == null) {
return this.contentLength;
}
int l = this.computedContentLength;
if (l < 0) {
this.computedContentLength = l = this.contentCharSeq.length();
}
return l;
}
protected final char charAtContent(final int index) {
// no need to perform index bounds checking: it would slow down traversing operations a lot, and
// it would be exactly the same exception we'd obtain by basically trying to access that index, so let's do
// it directly instead
if (this.contentStr != null) {
return this.contentStr.charAt(index);
}
if (this.computedContentStr != null) {
// Once the String is computed, this could be faster
return this.computedContentStr.charAt(index);
}
return this.contentCharSeq.charAt(index);
}
protected final CharSequence contentSubSequence(final int start, final int end) {
// no need to perform index bounds checking: it would slow down traversing operations a lot, and
// it would be exactly the same exception we'd obtain by basically trying to access that index, so let's do
// it directly instead
if (this.contentStr != null) {
return this.contentStr.subSequence(start, end);
}
if (this.computedContentStr != null) {
// Once the String is computed, this could be faster
return this.computedContentStr.subSequence(start, end);
}
return this.contentCharSeq.subSequence(start, end);
}
final boolean isWhitespace() {
Boolean w = this.computedContentIsWhitespace;
if (w == null) {
this.computedContentIsWhitespace = w = computeWhitespace();
}
return w.booleanValue();
}
final boolean isInlineable() {
Boolean i = this.computedContentIsInlineable;
if (i == null) {
this.computedContentIsInlineable = i = computeInlineable();
}
return i.booleanValue();
}
private Boolean computeWhitespace() {
int n = getContentLength(); // This will leave computedContentLength computed in case it's needed afterwards
if (n == 0) {
return Boolean.FALSE; // empty texts are NOT whitespace
}
char c;
while (n-- != 0) {
c = charAtContent(n);
if (c != ' ' && c != '\n') { // shortcut - most characters in many templates are just whitespace.
if (!Character.isWhitespace(c)) {
return Boolean.FALSE;
}
}
}
return Boolean.TRUE;
}
private Boolean computeInlineable() {<FILL_FUNCTION_BODY>}
public final void writeContent(final Writer writer) throws IOException {
if (this.contentStr != null) {
writer.write(this.contentStr);
} else if (this.computedContentStr != null) {
writer.write(this.computedContentStr);
} else if (this.contentCharSeq instanceof IWritableCharSequence) {
// In the special case we are using a writable CharSequence, we will avoid creating a String
// for the whole content
((IWritableCharSequence) this.contentCharSeq).write(writer);
} else {
writer.write(getContentText()); // We write, but make sure we cache the String we create
}
}
@Override
public String toString() {
return getContentText();
}
}
|
int n = getContentLength(); // This will leave computedContentLength computed in case it's needed afterwards
if (n == 0) {
return Boolean.FALSE;
}
char c0, c1;
c0 = 0x0;
int inline = 0;
while (n-- != 0) {
c1 = charAtContent(n);
if (n > 0 && c1 == ']' && c0 == ']') {
inline = 1;
n--;
c1 = charAtContent(n);
} else if (n > 0 && c1 == ')' && c0 == ']') {
inline = 2;
n--;
c1 = charAtContent(n);
} else if (inline == 1 && c1 == '[' && c0 == '[') {
return Boolean.TRUE;
} else if (inline == 2 && c1 == '[' && c0 == '(') {
return Boolean.TRUE;
}
c0 = c1;
}
return Boolean.FALSE;
| 1,394
| 268
| 1,662
|
<methods>public final int getCol() ,public final int getLine() ,public final java.lang.String getTemplateName() ,public final boolean hasLocation() <variables>final non-sealed int col,final non-sealed int line,final non-sealed java.lang.String templateName
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/Attribute.java
|
Attribute
|
hasLocation
|
class Attribute implements IAttribute {
static final String DEFAULT_OPERATOR = "=";
/*
* Note: An Attribute should not be made responsible for converting non-String values to String, or computing
* the boolean-ness of attributes or their representation. All these should be the responsibility of the
* diverse processors being executed. This class is a raw representation of what appears/will appear on template.
*/
final AttributeDefinition definition;
final String completeName;
final String operator; // can be null
final String value;
final AttributeValueQuotes valueQuotes;
final String templateName;
final int line;
final int col;
private volatile IStandardExpression standardExpression = null;
Attribute(
final AttributeDefinition definition,
final String completeName,
final String operator,
final String value,
final AttributeValueQuotes valueQuotes,
final String templateName,
final int line,
final int col) {
super();
this.definition = definition;
this.completeName = completeName;
this.value = value;
if (value == null) {
this.operator = null;
} else {
if (operator == null) {
this.operator = DEFAULT_OPERATOR;
} else {
this.operator = operator;
}
}
if (value == null) {
// Null value will always have null quotes
this.valueQuotes = null;
} else {
if (valueQuotes == null) {
this.valueQuotes = AttributeValueQuotes.DOUBLE;
} else if (valueQuotes == AttributeValueQuotes.NONE && value.length() == 0) {
// We will not allow no quotes with the empty string
this.valueQuotes = AttributeValueQuotes.DOUBLE;
} else {
this.valueQuotes = valueQuotes;
}
}
this.templateName = templateName;
this.line = line;
this.col = col;
}
public AttributeDefinition getAttributeDefinition() {
return this.definition;
}
public String getAttributeCompleteName() {
return this.completeName;
}
public String getOperator() {
return this.operator;
}
public String getValue() {
return this.value;
}
public AttributeValueQuotes getValueQuotes() {
return this.valueQuotes;
}
public String getTemplateName() {
return this.templateName;
}
public final boolean hasLocation() {<FILL_FUNCTION_BODY>}
public int getLine() {
return this.line;
}
public int getCol() {
return this.col;
}
IStandardExpression getCachedStandardExpression() {
return this.standardExpression;
}
void setCachedStandardExpression(final IStandardExpression standardExpression) {
this.standardExpression = standardExpression;
}
/*
* This method allows the easy creation of instances derivate from this one but keeping some specific fields
*/
Attribute modify(
final AttributeDefinition definition,
final String completeName,
final String value,
final AttributeValueQuotes valueQuotes) {
return new Attribute(
(definition == null? this.definition : definition),
(completeName == null? this.completeName : completeName),
this.operator,
value, // This is not keepable
(valueQuotes == null? this.valueQuotes : valueQuotes),
this.templateName,
this.line,
this.col);
}
public void write(final Writer writer) throws IOException {
/*
* How an attribute will be written:
* - If value == null : only the attribute name will be written.
* - If value != null : the attribute will be written according to its quotes
*/
writer.write(this.completeName);
if (this.value != null) {
writer.write(this.operator);
if (this.valueQuotes == null) {
writer.write(this.value);
} else {
switch (this.valueQuotes) {
case DOUBLE:
writer.write('"');
writer.write(this.value);
writer.write('"');
break;
case SINGLE:
writer.write('\'');
writer.write(this.value);
writer.write('\'');
break;
case NONE:
writer.write(this.value);
break;
}
}
}
}
@Override
public String toString() {
final Writer stringWriter = new FastStringWriter();
try {
write(stringWriter);
} catch (final IOException e) {
// Should never happen!
throw new TemplateProcessingException("Error computing attribute representation", e);
}
return stringWriter.toString();
}
}
|
return (this.templateName != null && this.line != -1 && this.col != -1);
| 1,267
| 31
| 1,298
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AttributeDefinition.java
|
AttributeDefinition
|
equals
|
class AttributeDefinition {
final AttributeName attributeName;
private final Set<IElementProcessor> associatedProcessorsSet;
final IElementProcessor[] associatedProcessors; // The internal representation is an array for better performance
final boolean hasAssociatedProcessors;
AttributeDefinition(final AttributeName attributeName, final Set<IElementProcessor> associatedProcessors) {
super();
if (attributeName == null) {
throw new IllegalArgumentException("Attribute name cannot be null");
}
if (associatedProcessors == null) {
throw new IllegalArgumentException("Associated processors cannot be null");
}
this.attributeName = attributeName;
this.associatedProcessorsSet = Collections.unmodifiableSet(associatedProcessors);
this.associatedProcessors = new IElementProcessor[this.associatedProcessorsSet.size()];
int i = 0;
for (final IElementProcessor processor : this.associatedProcessorsSet) {
this.associatedProcessors[i++] = processor;
}
Arrays.sort(this.associatedProcessors, ProcessorComparators.PROCESSOR_COMPARATOR);
this.hasAssociatedProcessors = this.associatedProcessors.length > 0;
}
public final AttributeName getAttributeName() {
return this.attributeName;
}
public boolean hasAssociatedProcessors() {
return this.hasAssociatedProcessors;
}
public Set<IElementProcessor> getAssociatedProcessors() {
return this.associatedProcessorsSet;
}
public final String toString() {
return getAttributeName().toString();
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.attributeName.hashCode();
}
}
|
if (this == o) {
return true;
}
if (!o.getClass().equals(this.getClass())) {
return false;
}
final AttributeDefinition that = (AttributeDefinition) o;
if (!this.attributeName.equals(that.attributeName)) {
return false;
}
return true;
| 479
| 94
| 573
|
<no_super_class>
|
thymeleaf_thymeleaf
|
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/AttributeName.java
|
AttributeName
|
equals
|
class AttributeName {
/*
* NOTE it is VERY important that an AttributeName does NOT contain a TemplateMode, because there is a type
* of AttributeName (TextAttributeName) that is used for 3 different template modes: TEXT, JAVASCRIPT and CSS
*/
protected final String prefix;
protected final String attributeName;
protected final String[] completeAttributeNames;
private final int h;
protected AttributeName(final String prefix, final String attributeName, final String[] completeAttributeNames) {
super();
if (attributeName == null || attributeName.trim().length() == 0) {
throw new IllegalArgumentException("Attribute name cannot be null or empty");
}
// Prefix CAN be null (if the attribute is not prefixed)
this.prefix = prefix;
this.attributeName = attributeName;
this.completeAttributeNames = completeAttributeNames;
this.h = Arrays.hashCode(this.completeAttributeNames);
}
public String getAttributeName() {
return this.attributeName;
}
public boolean isPrefixed() {
return this.prefix != null;
}
public String getPrefix() {
return this.prefix;
}
public String[] getCompleteAttributeNames() {
return this.completeAttributeNames;
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.h;
}
@Override
public String toString() {
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append('{');
strBuilder.append(this.completeAttributeNames[0]);
for (int i = 1; i < this.completeAttributeNames.length; i++) {
strBuilder.append(',');
strBuilder.append(this.completeAttributeNames[i]);
}
strBuilder.append('}');
return strBuilder.toString();
}
}
|
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (!o.getClass().equals(this.getClass())) {
return false;
}
final AttributeName that = (AttributeName) o;
if (this.h != that.h) {
return false;
}
if (!this.completeAttributeNames[0].equals(that.completeAttributeNames[0])) {
// No need to check the other names as we have already checked the class
return false;
}
return true;
| 519
| 159
| 678
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.