proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/CDATASection.java
CDATASection
getCDATASection
class CDATASection extends AbstractTextualTemplateEvent implements ICDATASection { // CDATA Section nodes do not exist in text parsing, so we are safe expliciting markup structures here static final String CDATA_PREFIX = "<![CDATA["; static final String CDATA_SUFFIX = "]]>"; final String prefix; final String suffix; private volatile String computedCDATASectionStr = null; CDATASection(final CharSequence content) { this(CDATA_PREFIX, content, CDATA_SUFFIX); } CDATASection(final String prefix, final CharSequence content, final String suffix) { super(content); this.prefix = prefix; this.suffix = suffix; } CDATASection(final CharSequence content, final String templateName, final int line, final int col) { this(CDATA_PREFIX, content, CDATA_SUFFIX, templateName, line, col); } CDATASection(final String prefix, final CharSequence content, final String suffix, final String templateName, final int line, final int col) { super(content, templateName, line, col); this.prefix = prefix; this.suffix = suffix; } public String getCDATASection() {<FILL_FUNCTION_BODY>} public String getContent() { return getContentText(); } public int length() { return this.prefix.length() + getContentLength() + this.suffix.length(); } public char charAt(final int index) { if (index < this.prefix.length()) { return this.prefix.charAt(index); } final int prefixedContentLen = this.prefix.length() + getContentLength(); if (index >= prefixedContentLen) { return this.suffix.charAt(index - prefixedContentLen); } return charAtContent(index - this.prefix.length()); } public CharSequence subSequence(final int start, final int end) { // First we will try to avoid computing the complete String if (start >= this.prefix.length() && end < (this.prefix.length() + getContentLength())) { return contentSubSequence((start - this.prefix.length()), (end - this.prefix.length())); } return getCDATASection().subSequence(start, end); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writer.write(this.prefix); writeContent(writer); writer.write(this.suffix); } // Meant to be called only from within the engine static CDATASection asEngineCDATASection(final ICDATASection cdataSection) { if (cdataSection instanceof CDATASection) { return (CDATASection) cdataSection; } return new CDATASection(cdataSection.getContent(), cdataSection.getTemplateName(), cdataSection.getLine(), cdataSection.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleCDATASection(this); } @Override public String toString() { return getCDATASection(); } }
String c = this.computedCDATASectionStr; if (c == null) { this.computedCDATASectionStr = c = this.prefix + getContentText() + this.suffix; } return c;
884
63
947
<methods>public java.lang.String toString() ,public final void writeContent(java.io.Writer) throws java.io.IOException<variables>private volatile java.lang.Boolean computedContentIsInlineable,private volatile java.lang.Boolean computedContentIsWhitespace,private volatile int computedContentLength,private volatile java.lang.String computedContentStr,private final non-sealed java.lang.CharSequence contentCharSeq,private final non-sealed int contentLength,private final non-sealed java.lang.String contentStr
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/CDATASectionStructureHandler.java
CDATASectionStructureHandler
setContent
class CDATASectionStructureHandler implements ICDATASectionStructureHandler { boolean setContent; CharSequence setContentValue; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeCDATASection; CDATASectionStructureHandler() { super(); reset(); } public void setContent(final CharSequence content) {<FILL_FUNCTION_BODY>} public void replaceWith(final IModel model, final boolean processable) { reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable; } public void removeCDATASection() { reset(); this.removeCDATASection = true; } public void reset() { this.setContent = false; this.setContentValue = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeCDATASection = false; } }
reset(); Validate.notNull(content, "Content cannot be null"); this.setContent = true; this.setContentValue = content;
320
42
362
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/CloseElementTag.java
CloseElementTag
asEngineCloseElementTag
class CloseElementTag extends AbstractElementTag implements ICloseElementTag, IEngineTemplateEvent { final String trailingWhiteSpace; // can be null if there is none final boolean unmatched; CloseElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final String trailingWhiteSpace, final boolean synthetic, final boolean unmatched) { super(templateMode, elementDefinition, elementCompleteName, synthetic); this.trailingWhiteSpace = trailingWhiteSpace; this.unmatched = unmatched; } CloseElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final String trailingWhiteSpace, final boolean synthetic, final boolean unmatched, final String templateName, final int line, final int col) { super(templateMode, elementDefinition, elementCompleteName, synthetic, templateName, line, col); this.trailingWhiteSpace = trailingWhiteSpace; this.unmatched = unmatched; } public boolean isUnmatched() { return this.unmatched; } // ------------ // NO GETTER for trailingWhiteSpace, as it is an internal-only property with no interest outside the engine // ------------ public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { if (this.synthetic) { // Nothing to be written... synthetic elements were not present at the original template! return; } // NOTE that being unmatched or not doesn't have an influence in how the tag is represented in output if (this.templateMode.isText()) { writer.write("[/"); writer.write(this.elementCompleteName); if (this.trailingWhiteSpace != null) { writer.write(this.trailingWhiteSpace); } writer.write("]"); return; } writer.write("</"); writer.write(this.elementCompleteName); if (this.trailingWhiteSpace != null) { writer.write(this.trailingWhiteSpace); } writer.write('>'); } // Meant to be called only from within the engine static CloseElementTag asEngineCloseElementTag(final ICloseElementTag closeElementTag) {<FILL_FUNCTION_BODY>} @Override public void beHandled(final ITemplateHandler handler) { handler.handleCloseElement(this); } }
if (closeElementTag instanceof CloseElementTag) { return (CloseElementTag) closeElementTag; } return new CloseElementTag( closeElementTag.getTemplateMode(), closeElementTag.getElementDefinition(), closeElementTag.getElementCompleteName(), null, closeElementTag.isSynthetic(), closeElementTag.isUnmatched(), closeElementTag.getTemplateName(), closeElementTag.getLine(), closeElementTag.getCol());
686
113
799
<methods>public final java.lang.String getElementCompleteName() ,public final org.thymeleaf.engine.ElementDefinition getElementDefinition() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() ,public final boolean isSynthetic() ,public final java.lang.String toString() <variables>final non-sealed java.lang.String elementCompleteName,final non-sealed org.thymeleaf.engine.ElementDefinition elementDefinition,final non-sealed boolean synthetic,final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/Comment.java
Comment
charAt
class Comment extends AbstractTextualTemplateEvent implements IComment { // Comment nodes do not exist in text parsing, so we are safe expliciting markup structures here private static final String COMMENT_PREFIX = "<!--"; private static final String COMMENT_SUFFIX = "-->"; final String prefix; final String suffix; private volatile String computedCommentStr = null; Comment(final CharSequence content) { this(COMMENT_PREFIX, content, COMMENT_SUFFIX); } Comment(final String prefix, final CharSequence content, final String suffix) { super(content); this.prefix = prefix; this.suffix = suffix; } Comment(final CharSequence content, final String templateName, final int line, final int col) { this(COMMENT_PREFIX, content, COMMENT_SUFFIX, templateName, line, col); } Comment(final String prefix, final CharSequence content, final String suffix, final String templateName, final int line, final int col) { super(content, templateName, line, col); this.prefix = prefix; this.suffix = suffix; } public String getComment() { String c = this.computedCommentStr; if (c == null) { this.computedCommentStr = c = this.prefix + getContentText() + this.suffix; } return c; } public String getContent() { return getContentText(); } public int length() { return this.prefix.length() + getContentLength() + this.suffix.length(); } public char charAt(final int index) {<FILL_FUNCTION_BODY>} public CharSequence subSequence(final int start, final int end) { // First we will try to avoid computing the complete String if (start >= this.prefix.length() && end < (this.prefix.length() + getContentLength())) { return contentSubSequence((start - this.prefix.length()), (end - this.prefix.length())); } return getComment().subSequence(start, end); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writer.write(this.prefix); writeContent(writer); writer.write(this.suffix); } // Meant to be called only from within the engine static Comment asEngineComment(final IComment comment) { if (comment instanceof Comment) { return (Comment) comment; } return new Comment(comment.getContent(), comment.getTemplateName(), comment.getLine(), comment.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleComment(this); } @Override public String toString() { return getComment(); } }
if (index < this.prefix.length()) { return this.prefix.charAt(index); } final int prefixedContentLen = this.prefix.length() + getContentLength(); if (index >= prefixedContentLen) { return this.suffix.charAt(index - prefixedContentLen); } return charAtContent(index - this.prefix.length());
775
99
874
<methods>public java.lang.String toString() ,public final void writeContent(java.io.Writer) throws java.io.IOException<variables>private volatile java.lang.Boolean computedContentIsInlineable,private volatile java.lang.Boolean computedContentIsWhitespace,private volatile int computedContentLength,private volatile java.lang.String computedContentStr,private final non-sealed java.lang.CharSequence contentCharSeq,private final non-sealed int contentLength,private final non-sealed java.lang.String contentStr
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/CommentStructureHandler.java
CommentStructureHandler
setContent
class CommentStructureHandler implements ICommentStructureHandler { boolean setContent; CharSequence setContentValue; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeComment; CommentStructureHandler() { super(); reset(); } public void setContent(final CharSequence content) {<FILL_FUNCTION_BODY>} public void replaceWith(final IModel model, final boolean processable) { reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable; } public void removeComment() { reset(); this.removeComment = true; } public void reset() { this.setContent = false; this.setContentValue = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeComment = false; } }
reset(); Validate.notNull(content, "Content cannot be null"); this.setContent = true; this.setContentValue = content;
299
42
341
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/DataDrivenTemplateIterator.java
DataDrivenTemplateIterator
finishStep
class DataDrivenTemplateIterator implements Iterator<Object> { private static final char[] SSE_HEAD_EVENT_NAME = "head".toCharArray(); private static final char[] SSE_MESSAGE_EVENT_NAME = "message".toCharArray(); private static final char[] SSE_TAIL_EVENT_NAME = "tail".toCharArray(); private final List<Object> values; private IThrottledTemplateWriterControl writerControl; private ISSEThrottledTemplateWriterControl sseControl; private char[] sseEventsPrefix; private char[] sseEventsComposedMessageEventName; // Used to cache the prefixed name of the most used type private long sseEventsID; private boolean inStep; private boolean feedingComplete; private boolean queried; public DataDrivenTemplateIterator() { super(); this.values = new ArrayList<Object>(10); this.writerControl = null; this.sseControl = null; this.sseEventsPrefix = null; this.sseEventsComposedMessageEventName = null; this.sseEventsID = 0L; this.inStep = false; this.feedingComplete = false; this.queried = false; } public void setWriterControl(final IThrottledTemplateWriterControl writerControl) { this.writerControl = writerControl; if (writerControl instanceof ISSEThrottledTemplateWriterControl) { this.sseControl = (ISSEThrottledTemplateWriterControl) this.writerControl; } else { this.sseControl = null; } } public void setSseEventsPrefix(final String sseEventsPrefix) { this.sseEventsPrefix = (sseEventsPrefix == null || sseEventsPrefix.length() == 0? null : sseEventsPrefix.toCharArray()); this.sseEventsComposedMessageEventName = composeToken(SSE_MESSAGE_EVENT_NAME); } public void setSseEventsFirstID(final long sseEventsFirstID) { this.sseEventsID = sseEventsFirstID; } public void takeBackLastEventID() { if (this.sseEventsID > 0L) { this.sseEventsID--; } } @Override public boolean hasNext() { this.queried = true; return !this.values.isEmpty(); } @Override public Object next() { this.queried = true; if (this.values.isEmpty()) { throw new NoSuchElementException(); } final Object value = this.values.get(0); this.values.remove(0); return value; } public void startIteration() { this.inStep = true; if (this.sseControl != null) { final char[] id = composeToken(Long.toString(this.sseEventsID).toCharArray()); final char[] event = this.sseEventsComposedMessageEventName; this.sseControl.startEvent(id, event); this.sseEventsID++; } } public void finishIteration() { finishStep(); } /** * <p> * Returns whether this data driven iterator has been actually queried, i.e., whether its {@link #hasNext()} or * {@link #next()} methods have been called at least once. * </p> * <p> * This indicates if the template has actually reached a point at which this iterator has been already * needed or not. The typical use of this is to be able to switch between the "head" and the "data/buffer" phase. * </p> * * @return {@code true} if this iterator has been queried, {@code false} if not. * * @since 3.0.3 */ public boolean hasBeenQueried() { return this.queried; } @Override public void remove() { throw new UnsupportedOperationException("remove() is not supported in Throttled Iterator"); } boolean isPaused() { this.queried = true; return this.values.isEmpty() && !this.feedingComplete; } public boolean continueBufferExecution() { return !this.values.isEmpty(); } public void feedBuffer(final List<Object> newElements) { this.values.addAll(newElements); } public void startHead() { this.inStep = true; if (this.sseControl != null) { final char[] id = composeToken(Long.toString(this.sseEventsID).toCharArray()); final char[] event = composeToken(SSE_HEAD_EVENT_NAME); this.sseControl.startEvent(id, event); this.sseEventsID++; } } public void feedingComplete() { this.feedingComplete = true; } public void startTail() { this.inStep = true; if (this.sseControl != null) { final char[] id = composeToken(Long.toString(this.sseEventsID).toCharArray()); final char[] event = composeToken(SSE_TAIL_EVENT_NAME); this.sseControl.startEvent(id, event); this.sseEventsID++; } } public void finishStep() {<FILL_FUNCTION_BODY>} public boolean isStepOutputFinished() { if (this.inStep) { return false; } if (this.writerControl != null) { try { return !this.writerControl.isOverflown(); } catch (final IOException e) { throw new TemplateProcessingException("Cannot signal end of SSE event", e); } } // We just don't know, so we will not worry about overflow return true; } private char[] composeToken(final char[] token) { if (this.sseEventsPrefix == null) { return token; } final char[] result = new char[this.sseEventsPrefix.length + 1 + token.length]; System.arraycopy(this.sseEventsPrefix, 0, result, 0, this.sseEventsPrefix.length); result[this.sseEventsPrefix.length] = '_'; System.arraycopy(token, 0, result, this.sseEventsPrefix.length + 1, token.length); return result; } }
if (!this.inStep) { return; } this.inStep = false; if (this.sseControl != null) { try { this.sseControl.endEvent(); } catch (final IOException e) { throw new TemplateProcessingException("Cannot signal end of SSE event", e); } }
1,712
93
1,805
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/DecreaseContextLevelProcessable.java
DecreaseContextLevelProcessable
process
class DecreaseContextLevelProcessable implements IEngineProcessable { private final IEngineContext context; private final TemplateFlowController flowController; DecreaseContextLevelProcessable(final IEngineContext context, final TemplateFlowController flowController) { super(); this.context = context; this.flowController = flowController; } public boolean process() {<FILL_FUNCTION_BODY>} }
/* * First, check the stopProcess flag */ if (this.flowController.stopProcessing) { return false; } /* * Process the queue */ if (this.context != null) { this.context.decreaseLevel(); } return true;
111
88
199
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/DocType.java
DocType
computeDocType
class DocType extends AbstractTemplateEvent implements IDocType, IEngineTemplateEvent { // DOCTYPE nodes do not exist in text parsing, so we are safe expliciting markup structures here public static final String DEFAULT_KEYWORD = "DOCTYPE"; public static final String DEFAULT_ELEMENT_NAME = "html"; public static final String DEFAULT_TYPE_PUBLIC = "PUBLIC"; public static final String DEFAULT_TYPE_SYSTEM = "SYSTEM"; private final String keyword; private final String elementName; private final String type; private final String publicId; private final String systemId; private final String internalSubset; private final String docType; DocType() { this(null, null); } DocType(final String publicId, final String systemId) { this(DEFAULT_KEYWORD, DEFAULT_ELEMENT_NAME, publicId, systemId, null); } DocType( final String keyword, final String elementName, final String publicId, final String systemId, final String internalSubset) { super(); this.keyword = keyword; this.elementName = elementName; this.type = computeType(publicId, systemId); this.publicId = publicId; this.systemId = systemId; this.internalSubset = internalSubset; this.docType = computeDocType(); } DocType( final String docType, final String keyword, final String elementName, final String publicId, final String systemId, final String internalSubset, final String templateName, final int line, final int col) { super(templateName, line, col); this.keyword = keyword; this.elementName = elementName; this.type = computeType(publicId, systemId); this.publicId = publicId; this.systemId = systemId; this.internalSubset = internalSubset; this.docType = (docType != null? docType : computeDocType()); } public String getKeyword() { return this.keyword; } public String getElementName() { return this.elementName; } public String getType() { return this.type; } public String getPublicId() { return this.publicId; } public String getSystemId() { return this.systemId; } public String getInternalSubset() { return this.internalSubset; } public String getDocType() { return this.docType; } private String computeDocType() {<FILL_FUNCTION_BODY>} private static String computeType(final String publicId, final String systemId) { if (publicId != null && systemId == null) { throw new IllegalArgumentException( "DOCTYPE clause cannot have a non-null PUBLIC ID and a null SYSTEM ID"); } if (publicId == null && systemId == null) { return null; } if (publicId != null) { return DEFAULT_TYPE_PUBLIC; } return DEFAULT_TYPE_SYSTEM; } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writer.write(this.docType); } // Meant to be called only from within the engine static DocType asEngineDocType(final IDocType docType) { if (docType instanceof DocType) { return (DocType) docType; } return new DocType( null, docType.getKeyword(), docType.getElementName(), docType.getPublicId(), docType.getSystemId(), docType.getInternalSubset(), docType.getTemplateName(), docType.getLine(), docType.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleDocType(this); } @Override public String toString() { return getDocType(); } }
final StringBuilder strBuilder = new StringBuilder(120); strBuilder.append("<!"); strBuilder.append(this.keyword); strBuilder.append(' '); strBuilder.append(this.elementName); if (this.type != null) { strBuilder.append(' '); strBuilder.append(type); if (this.publicId != null) { strBuilder.append(" \""); strBuilder.append(this.publicId); strBuilder.append('"'); } strBuilder.append(" \""); strBuilder.append(this.systemId); strBuilder.append('"'); } if (this.internalSubset != null) { strBuilder.append(" ["); strBuilder.append(this.internalSubset); strBuilder.append(']'); } strBuilder.append('>'); return strBuilder.toString();
1,098
239
1,337
<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/DocTypeStructureHandler.java
DocTypeStructureHandler
reset
class DocTypeStructureHandler implements IDocTypeStructureHandler { boolean setDocType; String setDocTypeKeyword; String setDocTypeElementName; String setDocTypePublicId; String setDocTypeSystemId; String setDocTypeInternalSubset; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeDocType; DocTypeStructureHandler() { super(); reset(); } public void setDocType( final String keyword, final String elementName, final String publicId, final String systemId, final String internalSubset) { reset(); Validate.notNull(keyword, "Keyword cannot be null"); Validate.notNull(elementName, "Element name cannot be null"); this.setDocType = true; this.setDocTypeKeyword = keyword; this.setDocTypeElementName = elementName; this.setDocTypePublicId = publicId; this.setDocTypeSystemId = systemId; this.setDocTypeInternalSubset = internalSubset; } public void replaceWith(final IModel model, final boolean processable) { reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable; } public void removeDocType() { reset(); this.removeDocType = true; } public void reset() {<FILL_FUNCTION_BODY>} }
this.setDocType = false; this.setDocTypeKeyword = null; this.setDocTypeElementName = null; this.setDocTypePublicId = null; this.setDocTypeSystemId = null; this.setDocTypeInternalSubset = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeDocType = false;
419
121
540
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ElementDefinition.java
ElementDefinition
equals
class ElementDefinition { final ElementName elementName; private final Set<IElementProcessor> associatedProcessorsSet; final IElementProcessor[] associatedProcessors; // The internal representation is an array for better performance final boolean hasAssociatedProcessors; ElementDefinition(final ElementName elementName, final Set<IElementProcessor> associatedProcessors) { super(); if (elementName == null) { throw new IllegalArgumentException("Element name cannot be null"); } if (associatedProcessors == null) { throw new IllegalArgumentException("Associated processors cannot be null"); } this.elementName = elementName; 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 ElementName getElementName() { return this.elementName; } public boolean hasAssociatedProcessors() { return this.hasAssociatedProcessors; } public Set<IElementProcessor> getAssociatedProcessors() { return this.associatedProcessorsSet; } public final String toString() { return getElementName().toString(); } @Override public boolean equals(final Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return this.elementName.hashCode(); } }
if (this == o) { return true; } if (!o.getClass().equals(this.getClass())) { return false; } final ElementDefinition that = (ElementDefinition) o; if (!this.elementName.equals(that.elementName)) { return false; } return true;
474
93
567
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ElementModelStructureHandler.java
ElementModelStructureHandler
setLocalVariable
class ElementModelStructureHandler implements IElementModelStructureHandler { boolean setLocalVariable; Map<String,Object> addedLocalVariables; boolean removeLocalVariable; Set<String> removedLocalVariableNames; boolean setSelectionTarget; Object selectionTargetObject; boolean setInliner; IInliner setInlinerValue; boolean setTemplateData; TemplateData setTemplateDataValue; ElementModelStructureHandler() { super(); reset(); } public void removeLocalVariable(final String name) { // Can be combined with others, no need to resetGathering this.removeLocalVariable = true; if (this.removedLocalVariableNames == null) { this.removedLocalVariableNames = new HashSet<String>(3); } this.removedLocalVariableNames.add(name); } public void setLocalVariable(final String name, final Object value) {<FILL_FUNCTION_BODY>} public void setSelectionTarget(final Object selectionTarget) { // Can be combined with others, no need to resetGathering this.setSelectionTarget = true; this.selectionTargetObject = selectionTarget; } public void setInliner(final IInliner inliner) { this.setInliner = true; this.setInlinerValue = inliner; } public void setTemplateData(final TemplateData templateData) { this.setTemplateData = true; this.setTemplateDataValue = templateData; } public void reset() { this.setLocalVariable = false; if (this.addedLocalVariables != null && this.addedLocalVariables.size() > 0) { this.addedLocalVariables.clear(); } this.removeLocalVariable = false; if (this.removedLocalVariableNames != null && this.removedLocalVariableNames.size() > 0) { this.removedLocalVariableNames.clear(); } this.setSelectionTarget = false; this.selectionTargetObject = null; this.setInliner = false; this.setInlinerValue = null; this.setTemplateData = false; this.setTemplateDataValue = null; } void applyContextModifications(final IEngineContext engineContext) { if (engineContext == null) { return; } if (this.setLocalVariable) { engineContext.setVariables(this.addedLocalVariables); } if (this.removeLocalVariable) { for (final String variableName : this.removedLocalVariableNames) { engineContext.removeVariable(variableName); } } if (this.setSelectionTarget) { engineContext.setSelectionTarget(this.selectionTargetObject); } if (this.setInliner) { engineContext.setInliner(this.setInlinerValue); } if (this.setTemplateData) { engineContext.setTemplateData(this.setTemplateDataValue); } } }
// Can be combined with others, no need to resetGathering this.setLocalVariable = true; if (this.addedLocalVariables == null) { this.addedLocalVariables = new HashMap<String, Object>(3); } this.addedLocalVariables.put(name, value);
817
81
898
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ElementName.java
ElementName
toString
class ElementName { /* * NOTE it is VERY important that an ElementName does NOT contain a TemplateMode, because there is a type * of ElementName (TextElementName) that is used for 3 different template modes: TEXT, JAVASCRIPT and CSS */ protected final String prefix; protected final String elementName; protected final String[] completeElementNames; private final int h; protected ElementName(final String prefix, final String elementName, final String[] completeElementNames) { super(); if (elementName == null || (elementName.length() > 0 && elementName.trim().length() == 0)) { // can be the empty string (e.g. in text modes) throw new IllegalArgumentException("Element name cannot be null"); } // Prefix CAN be null (if the element is not prefixed) this.prefix = prefix; this.elementName = elementName; this.completeElementNames = completeElementNames; this.h = Arrays.hashCode(this.completeElementNames); } public String getElementName() { return this.elementName; } public boolean isPrefixed() { return this.prefix != null; } public String getPrefix() { return this.prefix; } public String[] getCompleteElementNames() { return this.completeElementNames; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ElementName)) { return false; } final ElementName that = (ElementName) o; if (this.h != that.h) { return false; } if (!Arrays.equals(this.completeElementNames, that.completeElementNames)) { return false; } return true; } @Override public int hashCode() { return this.h; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder strBuilder = new StringBuilder(); strBuilder.append('{'); strBuilder.append(this.completeElementNames[0]); for (int i = 1; i < this.completeElementNames.length; i++) { strBuilder.append(','); strBuilder.append(this.completeElementNames[i]); } strBuilder.append('}'); return strBuilder.toString();
546
106
652
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/EngineContextManager.java
EngineContextManager
createEngineContextIfNeeded
class EngineContextManager { static IEngineContext prepareEngineContext( final IEngineConfiguration configuration, final TemplateData templateData, final Map<String, Object> templateResolutionAttributes, final IContext context) { final IEngineContext engineContext = createEngineContextIfNeeded(configuration, templateData, templateResolutionAttributes, context); // We will always do this, even if the context is a new object (in which case it would be completely needed) // because we want to make sure the 'disposeEngineContext' call that will come afterwards can safely // decrease the level engineContext.increaseLevel(); if (context instanceof IEngineContext) { // Set the template resolution into the context, but only if we haven't just created it engineContext.setTemplateData(templateData); } return engineContext; } static void disposeEngineContext(final IEngineContext engineContext) { engineContext.decreaseLevel(); } private static IEngineContext createEngineContextIfNeeded( final IEngineConfiguration configuration, final TemplateData templateData, final Map<String, Object> templateResolutionAttributes, final IContext context) {<FILL_FUNCTION_BODY>} private EngineContextManager() { super(); } }
if (context instanceof IEngineContext) { // If this context is already an IEngineContext, we will not clone it return (IEngineContext) context; } // It's the engine context factory the one who has the responsibility of creating the specific // implementation of the engine context needed. final IEngineContextFactory engineContextFactory = configuration.getEngineContextFactory(); return engineContextFactory.createEngineContext( configuration, templateData, templateResolutionAttributes, context);
330
121
451
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/EngineEventUtils.java
EngineEventUtils
computeWhitespace
class EngineEventUtils { public static boolean isWhitespace(final IText text) { if (text == null) { return false; } if (text instanceof Text) { return ((Text) text).isWhitespace(); } return computeWhitespace(text); } public static boolean isWhitespace(final ICDATASection cdataSection) { if (cdataSection == null) { return false; } if (cdataSection instanceof CDATASection) { return ((CDATASection) cdataSection).isWhitespace(); } return computeWhitespace(cdataSection.getContent()); } public static boolean isWhitespace(final IComment comment) { if (comment == null) { return false; } if (comment instanceof Comment) { return ((Comment) comment).isWhitespace(); } return computeWhitespace(comment.getContent()); } public static boolean isInlineable(final IText text) { if (text == null) { return false; } if (text instanceof Text) { return ((Text) text).isInlineable(); } return computeInlineable(text); } public static boolean isInlineable(final ICDATASection cdataSection) { if (cdataSection == null) { return false; } if (cdataSection instanceof CDATASection) { return ((CDATASection) cdataSection).isInlineable(); } return computeInlineable(cdataSection.getContent()); } public static boolean isInlineable(final IComment comment) { if (comment == null) { return false; } if (comment instanceof Comment) { return ((Comment) comment).isInlineable(); } return computeInlineable(comment.getContent()); } private static boolean computeWhitespace(final CharSequence text) {<FILL_FUNCTION_BODY>} private static boolean computeInlineable(final CharSequence text) { int n = text.length(); if (n == 0) { return false; } char c0, c1; c0 = 0x0; int inline = 0; while (n-- != 0) { c1 = text.charAt(n); if (c1 == ']' && c0 == ']') { inline = 1; } else if (c1 == ')' && c0 == ']') { inline = 2; } else if (inline == 1 && c1 == '[' && c0 == '[') { return true; } else if (inline == 2 && c1 == '[' && c0 == '(') { return true; } c0 = c1; } return false; } /* * The idea behind this method is to cache in the Attribute object itself the IStandardExpression object corresponding * with the expression to be executed, so that we don't have to hit the expression cache at all */ public static IStandardExpression computeAttributeExpression( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) { if (!(tag instanceof AbstractProcessableElementTag)) { return parseAttributeExpression(context, attributeValue); } final AbstractProcessableElementTag processableElementTag = (AbstractProcessableElementTag)tag; final Attribute attribute = (Attribute) processableElementTag.getAttribute(attributeName); IStandardExpression expression = attribute.getCachedStandardExpression(); if (expression != null) { return expression; } expression = parseAttributeExpression(context, attributeValue); // If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it! if (expression != null && !(expression instanceof FragmentExpression) && attributeValue.indexOf('_') < 0) { attribute.setCachedStandardExpression(expression); } return expression; } private static IStandardExpression parseAttributeExpression(final ITemplateContext context, final String attributeValue) { final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); return expressionParser.parseExpression(context, attributeValue); } private EngineEventUtils() { super(); } }
int n = text.length(); if (n == 0) { return false; } char c; while (n-- != 0) { c = text.charAt(n); if (!Character.isWhitespace(c)) { return false; } } return true;
1,165
86
1,251
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/GatheringModelProcessable.java
GatheringModelProcessable
process
class GatheringModelProcessable extends AbstractGatheringModelProcessable { private final IEngineContext context; private int offset; GatheringModelProcessable( final IEngineConfiguration configuration, ProcessorTemplateHandler processorTemplateHandler, final IEngineContext context, final TemplateModelController modelController, final TemplateFlowController flowController, final SkipBody gatheredSkipBody, final boolean gatheredSkipCloseTag, final ProcessorExecutionVars processorExecutionVars) { super(configuration, processorTemplateHandler, context, modelController, flowController, gatheredSkipBody, gatheredSkipCloseTag, processorExecutionVars); this.context = context; this.offset = 0; } public boolean process() {<FILL_FUNCTION_BODY>} }
/* * First, check the stopProcess flag */ final TemplateFlowController flowController = getFlowController(); if (flowController != null && flowController.stopProcessing) { return false; } if (this.offset == 0) { /* * Reset the "skipBody" and "skipCloseTag" values at the event model controller, and also set this * synthetic model into the processor handler so that it can be used by the executed events */ prepareProcessing(); } /* * PROCESS THE MODEL */ final Model model = getInnerModel(); this.offset += model.process(getProcessorTemplateHandler(), this.offset, flowController); /* * Compute whether the whole model has been processed or not */ final boolean processed = (flowController == null || (this.offset == model.queueSize && !flowController.stopProcessing)); if (processed) { /* * DECREASE THE CONTEXT LEVEL * This was increased before starting gathering, when the handling of the first gathered event started. */ this.context.decreaseLevel(); } return processed;
195
301
496
<methods>public final void gatherCDATASection(org.thymeleaf.model.ICDATASection) ,public final void gatherCloseElement(org.thymeleaf.model.ICloseElementTag) ,public final void gatherComment(org.thymeleaf.model.IComment) ,public final void gatherDocType(org.thymeleaf.model.IDocType) ,public final void gatherOpenElement(org.thymeleaf.model.IOpenElementTag) ,public final void gatherProcessingInstruction(org.thymeleaf.model.IProcessingInstruction) ,public final void gatherStandaloneElement(org.thymeleaf.model.IStandaloneElementTag) ,public final void gatherText(org.thymeleaf.model.IText) ,public final void gatherUnmatchedCloseElement(org.thymeleaf.model.ICloseElementTag) ,public final void gatherXMLDeclaration(org.thymeleaf.model.IXMLDeclaration) ,public final org.thymeleaf.engine.Model getInnerModel() ,public org.thymeleaf.engine.ProcessorExecutionVars initializeProcessorExecutionVars() ,public final boolean isGatheringFinished() ,public final void resetGatheredSkipFlags() ,public final void resetGatheredSkipFlagsAfterNoIterations() <variables>private final non-sealed org.thymeleaf.engine.TemplateModelController.SkipBody buildTimeSkipBody,private final non-sealed boolean buildTimeSkipCloseTag,private final non-sealed org.thymeleaf.context.IEngineContext context,private final non-sealed org.thymeleaf.engine.TemplateFlowController flowController,private boolean gatheringFinished,private final non-sealed org.thymeleaf.engine.TemplateModelController modelController,private int modelLevel,private final non-sealed org.thymeleaf.engine.ProcessorExecutionVars processorExecutionVars,private final non-sealed org.thymeleaf.engine.ProcessorTemplateHandler processorTemplateHandler,private final non-sealed org.thymeleaf.engine.Model syntheticModel
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/HTMLAttributeName.java
HTMLAttributeName
forName
class HTMLAttributeName extends AttributeName { final String completeNamespacedAttributeName; final String completeHTML5AttributeName; static HTMLAttributeName forName(final String prefix, final String attributeName) {<FILL_FUNCTION_BODY>} private HTMLAttributeName( final String prefix, final String attributeName, final String completeNamespacedAttributeName, final String completeHTML5AttributeName, final String[] completeAttributeNames) { super(prefix, attributeName, completeAttributeNames); this.completeNamespacedAttributeName = completeNamespacedAttributeName; this.completeHTML5AttributeName = completeHTML5AttributeName; } public String getCompleteNamespacedAttributeName() { return this.completeNamespacedAttributeName; } public String getCompleteHTML5AttributeName() { return this.completeHTML5AttributeName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; final String nameAttributeName = (attributeName == null || attributeName.length() == 0)? null : attributeName.toLowerCase(); final String namePrefix; final String completeNamespacedAttributeName; final String completeHTML5AttributeName; final String[] completeAttributeNames; if (hasPrefix) { namePrefix = prefix.toLowerCase(); completeNamespacedAttributeName = namePrefix + ":" + nameAttributeName; completeHTML5AttributeName = "data-" + namePrefix + "-" + nameAttributeName; completeAttributeNames = new String[] { completeNamespacedAttributeName, completeHTML5AttributeName }; } else { namePrefix = null; completeNamespacedAttributeName = nameAttributeName; completeHTML5AttributeName = nameAttributeName; completeAttributeNames = new String[] { nameAttributeName }; } return new HTMLAttributeName( namePrefix, nameAttributeName, completeNamespacedAttributeName, completeHTML5AttributeName, completeAttributeNames);
241
278
519
<methods>public boolean equals(java.lang.Object) ,public java.lang.String getAttributeName() ,public java.lang.String[] getCompleteAttributeNames() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String attributeName,protected final non-sealed java.lang.String[] completeAttributeNames,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/HTMLElementName.java
HTMLElementName
forName
class HTMLElementName extends ElementName { final String completeNamespacedElementName; final String completeHTML5ElementName; static HTMLElementName forName(final String prefix, final String elementName) {<FILL_FUNCTION_BODY>} private HTMLElementName( final String prefix, final String elementName, final String completeNamespacedElementName, final String completeHTML5ElementName, final String[] completeElementNames) { super(prefix, elementName, completeElementNames); this.completeNamespacedElementName = completeNamespacedElementName; this.completeHTML5ElementName = completeHTML5ElementName; } public String getCompleteNamespacedElementName() { return this.completeNamespacedElementName; } public String getCompleteHTML5ElementName() { return this.completeHTML5ElementName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; // No-suffix element names are allowed by the HTML5 Custom Element specification ("<tag->" is valid), // so we will just normalize to the empty string so that we treat them in the same way as no-name // elements in the textual template modes. final String nameElementName = (elementName == null || elementName.length() == 0)? "" : elementName.toLowerCase(); final String namePrefix; final String completeNamespacedElementName; final String completeHTML5ElementName; final String[] completeAttributeNames; if (hasPrefix) { namePrefix = prefix.toLowerCase(); completeNamespacedElementName = namePrefix + ":" + nameElementName; completeHTML5ElementName = namePrefix + "-" + nameElementName; completeAttributeNames = new String[] { completeNamespacedElementName, completeHTML5ElementName }; } else { namePrefix = null; completeNamespacedElementName = nameElementName; completeHTML5ElementName = nameElementName; completeAttributeNames = new String[] { nameElementName }; } return new HTMLElementName( namePrefix, nameElementName, completeNamespacedElementName, completeHTML5ElementName, completeAttributeNames);
238
337
575
<methods>public boolean equals(java.lang.Object) ,public java.lang.String[] getCompleteElementNames() ,public java.lang.String getElementName() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String[] completeElementNames,protected final non-sealed java.lang.String elementName,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/IterationStatusVar.java
IterationStatusVar
toString
class IterationStatusVar { int index; Integer size; // it can be null if we don't know the size of the iterated object beforehand! Object current; IterationStatusVar() { super(); } public int getIndex() { return this.index; } public int getCount() { return this.index + 1; } public boolean hasSize() { return this.size != null; } public Integer getSize() { return this.size; } public Object getCurrent() { return this.current; } public boolean isEven() { // We start counting in 1 in order to be consistent with :nth-child(odd) and :nth-child(even) CSS selectors return ((this.index + 1) % 2 == 0); } public boolean isOdd() { return !isEven(); } public boolean isFirst() { return (this.index == 0); } public boolean isLast() { return (this.index == this.size - 1); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "{index = " + this.index + ", count = " + (this.index + 1) + ", size = " + this.size + ", current = " + (this.current == null? "null" : this.current.toString()) + "}";
320
66
386
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ModelBuilderTemplateHandler.java
ModelBuilderTemplateHandler
handleCDATASection
class ModelBuilderTemplateHandler extends AbstractTemplateHandler { private final List<IEngineTemplateEvent> events; private final IEngineConfiguration configuration; private final TemplateData templateData; public ModelBuilderTemplateHandler(final IEngineConfiguration configuration, final TemplateData templateData) { super(); Validate.notNull(configuration, "Configuration cannot be null"); Validate.notNull(templateData, "Template Data cannot be null"); this.configuration = configuration; this.templateData = templateData; this.events = new ArrayList<IEngineTemplateEvent>(100); } public TemplateModel getModel() { return new TemplateModel(this.configuration, this.templateData, this.events.toArray(new IEngineTemplateEvent[this.events.size()])); } // Note we are NOT implementing the setContext method, because we don't need it at all when just using // this handler for parsing (we are not processing anything!) @Override public void handleTemplateStart(final ITemplateStart templateStart) { this.events.add(TemplateStart.asEngineTemplateStart(templateStart)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleTemplateStart(templateStart); } @Override public void handleTemplateEnd(final ITemplateEnd templateEnd) { this.events.add(TemplateEnd.asEngineTemplateEnd(templateEnd)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleTemplateEnd(templateEnd); } @Override public void handleText(final IText text) { this.events.add(Text.asEngineText(text)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleText(text); } @Override public void handleComment(final IComment comment) { this.events.add(Comment.asEngineComment(comment)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleComment(comment); } @Override public void handleCDATASection(final ICDATASection cdataSection) {<FILL_FUNCTION_BODY>} @Override public void handleStandaloneElement(final IStandaloneElementTag standaloneElementTag) { this.events.add(StandaloneElementTag.asEngineStandaloneElementTag(standaloneElementTag)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleStandaloneElement(standaloneElementTag); } @Override public void handleOpenElement(final IOpenElementTag openElementTag) { this.events.add(OpenElementTag.asEngineOpenElementTag(openElementTag)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleOpenElement(openElementTag); } @Override public void handleCloseElement(final ICloseElementTag closeElementTag) { this.events.add(CloseElementTag.asEngineCloseElementTag(closeElementTag)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleCloseElement(closeElementTag); } @Override public void handleDocType(final IDocType docType) { this.events.add(DocType.asEngineDocType(docType)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleDocType(docType); } @Override public void handleXMLDeclaration(final IXMLDeclaration xmlDeclaration) { this.events.add(XMLDeclaration.asEngineXMLDeclaration(xmlDeclaration)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleXMLDeclaration(xmlDeclaration); } @Override public void handleProcessingInstruction(final IProcessingInstruction processingInstruction) { this.events.add(ProcessingInstruction.asEngineProcessingInstruction(processingInstruction)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleProcessingInstruction(processingInstruction); } }
this.events.add(CDATASection.asEngineCDATASection(cdataSection)); // The engine event we might have created is not forwarded - this makes cache creating transparent to the handler chain super.handleCDATASection(cdataSection);
1,110
65
1,175
<methods>public void handleCDATASection(org.thymeleaf.model.ICDATASection) ,public void handleCloseElement(org.thymeleaf.model.ICloseElementTag) ,public void handleComment(org.thymeleaf.model.IComment) ,public void handleDocType(org.thymeleaf.model.IDocType) ,public void handleOpenElement(org.thymeleaf.model.IOpenElementTag) ,public void handleProcessingInstruction(org.thymeleaf.model.IProcessingInstruction) ,public void handleStandaloneElement(org.thymeleaf.model.IStandaloneElementTag) ,public void handleTemplateEnd(org.thymeleaf.model.ITemplateEnd) ,public void handleTemplateStart(org.thymeleaf.model.ITemplateStart) ,public void handleText(org.thymeleaf.model.IText) ,public void handleXMLDeclaration(org.thymeleaf.model.IXMLDeclaration) ,public void setContext(org.thymeleaf.context.ITemplateContext) ,public void setNext(org.thymeleaf.engine.ITemplateHandler) <variables>private org.thymeleaf.context.ITemplateContext context,private org.thymeleaf.engine.ITemplateHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/OpenElementTag.java
OpenElementTag
removeAttribute
class OpenElementTag extends AbstractProcessableElementTag implements IOpenElementTag, IEngineTemplateEvent { OpenElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final Attributes attributes, final boolean synthetic) { super(templateMode, elementDefinition, elementCompleteName, attributes, synthetic); } OpenElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final Attributes attributes, final boolean synthetic, final String templateName, final int line, final int col) { super(templateMode, elementDefinition, elementCompleteName, attributes, synthetic, templateName, line, col); } OpenElementTag setAttribute( final AttributeDefinitions attributeDefinitions, final AttributeDefinition attributeDefinition, final String completeName, final String value, final AttributeValueQuotes valueQuotes) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.setAttribute(attributeDefinitions, this.templateMode, attributeDefinition, completeName, value, valueQuotes); return new OpenElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.templateName, this.line, this.col); } OpenElementTag replaceAttribute( final AttributeDefinitions attributeDefinitions, final AttributeName oldName, final AttributeDefinition newAttributeDefinition, final String completeNewName, final String value, final AttributeValueQuotes valueQuotes) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.replaceAttribute(attributeDefinitions, this.templateMode, oldName, newAttributeDefinition, completeNewName, value, valueQuotes); return new OpenElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.templateName, this.line, this.col); } OpenElementTag removeAttribute(final String prefix, final String name) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(this.templateMode, prefix, name); if (oldAttributes == newAttributes) { return this; } return new OpenElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.templateName, this.line, this.col); } OpenElementTag removeAttribute(final String completeName) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(this.templateMode, completeName); if (oldAttributes == newAttributes) { return this; } return new OpenElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.templateName, this.line, this.col); } OpenElementTag removeAttribute(final AttributeName attributeName) {<FILL_FUNCTION_BODY>} public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { if (this.synthetic) { // Nothing to be written... synthetic elements were not present at the original template! return; } if (this.templateMode.isText()) { writer.write("[#"); writer.write(this.elementCompleteName); if (this.attributes != null) { this.attributes.write(writer); } writer.write("]"); return; } writer.write('<'); writer.write(this.elementCompleteName); if (this.attributes != null) { this.attributes.write(writer); } writer.write('>'); } // Meant to be called only from within the engine static OpenElementTag asEngineOpenElementTag(final IOpenElementTag openElementTag) { if (openElementTag instanceof OpenElementTag) { return (OpenElementTag) openElementTag; } final IAttribute[] originalAttributeArray = openElementTag.getAllAttributes(); final Attributes attributes; if (originalAttributeArray == null || originalAttributeArray.length == 0) { attributes = null; } else { // We will perform a deep cloning of the attributes into objects of the Attribute class, so that // we make sure absolutely all Attributes in the new event are under the engine's control final Attribute[] newAttributeArray = new Attribute[originalAttributeArray.length]; for (int i = 0; i < originalAttributeArray.length; i++) { final IAttribute originalAttribute = originalAttributeArray[i]; newAttributeArray[i] = new Attribute( originalAttribute.getAttributeDefinition(), originalAttribute.getAttributeCompleteName(), originalAttribute.getOperator(), originalAttribute.getValue(), originalAttribute.getValueQuotes(), originalAttribute.getTemplateName(), originalAttribute.getLine(), originalAttribute.getCol()); } final String[] newInnerWhiteSpaces; if (newAttributeArray.length == 1) { newInnerWhiteSpaces = Attributes.DEFAULT_WHITE_SPACE_ARRAY; } else { newInnerWhiteSpaces = new String[newAttributeArray.length]; Arrays.fill(newInnerWhiteSpaces, Attributes.DEFAULT_WHITE_SPACE); } attributes = new Attributes(newAttributeArray, newInnerWhiteSpaces); } return new OpenElementTag( openElementTag.getTemplateMode(), openElementTag.getElementDefinition(), openElementTag.getElementCompleteName(), attributes, openElementTag.isSynthetic(), openElementTag.getTemplateName(), openElementTag.getLine(), openElementTag.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleOpenElement(this); } }
final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(attributeName); if (oldAttributes == newAttributes) { return this; } return new OpenElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.templateName, this.line, this.col);
1,609
117
1,726
<methods>public org.thymeleaf.model.IAttribute[] getAllAttributes() ,public final org.thymeleaf.model.IAttribute getAttribute(java.lang.String) ,public final org.thymeleaf.model.IAttribute getAttribute(java.lang.String, java.lang.String) ,public final org.thymeleaf.model.IAttribute getAttribute(org.thymeleaf.engine.AttributeName) ,public Map<java.lang.String,java.lang.String> getAttributeMap() ,public final java.lang.String getAttributeValue(java.lang.String) ,public final java.lang.String getAttributeValue(java.lang.String, java.lang.String) ,public final java.lang.String getAttributeValue(org.thymeleaf.engine.AttributeName) ,public final boolean hasAttribute(java.lang.String) ,public final boolean hasAttribute(java.lang.String, java.lang.String) ,public final boolean hasAttribute(org.thymeleaf.engine.AttributeName) <variables>private static final org.thymeleaf.processor.element.IElementProcessor[] EMPTY_ASSOCIATED_PROCESSORS,private volatile org.thymeleaf.processor.element.IElementProcessor[] associatedProcessors,final non-sealed org.thymeleaf.engine.Attributes attributes
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/OpenElementTagModelProcessable.java
OpenElementTagModelProcessable
process
class OpenElementTagModelProcessable implements IEngineProcessable { private final OpenElementTag openElementTag; private final ProcessorExecutionVars vars; private final TemplateFlowController flowController; private final TemplateModelController modelController; private final ProcessorTemplateHandler processorTemplateHandler; private final ITemplateHandler nextTemplateHandler; private boolean beforeProcessed; private boolean delegationProcessed; private boolean afterProcessed; private int offset; OpenElementTagModelProcessable( final OpenElementTag openElementTag, final ProcessorExecutionVars vars, final TemplateModelController modelController, final TemplateFlowController flowController, final ProcessorTemplateHandler processorTemplateHandler, final ITemplateHandler nextTemplateHandler) { super(); this.openElementTag = openElementTag; this.vars = vars; this.flowController = flowController; this.modelController = modelController; this.processorTemplateHandler = processorTemplateHandler; this.nextTemplateHandler = nextTemplateHandler; this.beforeProcessed = false; this.delegationProcessed = false; this.afterProcessed = false; this.offset = 0; } public boolean process() {<FILL_FUNCTION_BODY>} }
/* * First, check the stopProcess flag */ if (this.flowController.stopProcessing) { return false; } if (!this.beforeProcessed) { /* * PROCESS THE QUEUE BEFORE DELEGATING, if specified to do so */ if (this.vars.modelBefore != null) { this.offset += this.vars.modelBefore.process(this.nextTemplateHandler, this.offset, this.flowController); // This is never processable if (this.offset < this.vars.modelBefore.queueSize || this.flowController.stopProcessing) { return false; } } this.beforeProcessed = true; this.offset = 0; } if (!this.delegationProcessed) { /* * PROCESS THE REST OF THE HANDLER CHAIN and INCREASE THE MODEL LEVEL RIGHT AFTERWARDS */ if (!this.vars.discardEvent) { this.nextTemplateHandler.handleOpenElement(this.openElementTag); } this.delegationProcessed = true; this.offset = 0; } if (this.flowController.stopProcessing) { return false; } if (!this.afterProcessed) { /* * PROCESS THE QUEUE, launching all the queued events. Note executing the queue after increasing the model * level makes sense even if what the queue contains is a replacement for the complete element (including open * and close tags), because that way whatever comes in the queue will be encapsulated in a different model level * and its internal open/close tags should not affect the correct delimitation of this block. */ if (this.vars.modelAfter != null) { final ITemplateHandler modelHandler = this.vars.modelAfterProcessable ? this.processorTemplateHandler : this.nextTemplateHandler; this.offset += this.vars.modelAfter.process(modelHandler, this.offset, this.flowController); if (this.offset < this.vars.modelAfter.queueSize || this.flowController.stopProcessing) { return false; } } this.afterProcessed = true; } /* * SET BODY TO BE SKIPPED, if required. Importantly, this has to be done AFTER executing the queue */ this.modelController.skip(this.vars.skipBody, this.vars.skipCloseTag); return true;
317
634
951
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/OutputTemplateHandler.java
OutputTemplateHandler
handleCDATASection
class OutputTemplateHandler extends AbstractTemplateHandler { private final Writer writer; /** * <p> * Creates a new instance of this handler. * </p> * * @param writer the writer to which output will be written. */ public OutputTemplateHandler(final Writer writer) { super(); if (writer == null) { throw new IllegalArgumentException("Writer cannot be null"); } this.writer = writer; } @Override public void handleText(final IText text) { try { text.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", text.getTemplateName(), text.getLine(), text.getCol(), e); } // Just in case someone set us a 'next' super.handleText(text); } @Override public void handleComment(final IComment comment) { try { comment.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", comment.getTemplateName(), comment.getLine(), comment.getCol(), e); } // Just in case someone set us a 'next' super.handleComment(comment); } @Override public void handleCDATASection(final ICDATASection cdataSection) {<FILL_FUNCTION_BODY>} @Override public void handleStandaloneElement(final IStandaloneElementTag standaloneElementTag) { try { standaloneElementTag.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", standaloneElementTag.getTemplateName(), standaloneElementTag.getLine(), standaloneElementTag.getCol(), e); } // Just in case someone set us a 'next' super.handleStandaloneElement(standaloneElementTag); } @Override public void handleOpenElement(final IOpenElementTag openElementTag) { try { openElementTag.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", openElementTag.getTemplateName(), openElementTag.getLine(), openElementTag.getCol(), e); } // Just in case someone set us a 'next' super.handleOpenElement(openElementTag); } @Override public void handleCloseElement(final ICloseElementTag closeElementTag) { try { closeElementTag.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", closeElementTag.getTemplateName(), closeElementTag.getLine(), closeElementTag.getCol(), e); } // Just in case someone set us a 'next' super.handleCloseElement(closeElementTag); } @Override public void handleDocType(final IDocType docType) { try { docType.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", docType.getTemplateName(), docType.getLine(), docType.getCol(), e); } // Just in case someone set us a 'next' super.handleDocType(docType); } @Override public void handleXMLDeclaration(final IXMLDeclaration xmlDeclaration) { try { xmlDeclaration.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", xmlDeclaration.getTemplateName(), xmlDeclaration.getLine(), xmlDeclaration.getCol(), e); } // Just in case someone set us a 'next' super.handleXMLDeclaration(xmlDeclaration); } @Override public void handleProcessingInstruction(final IProcessingInstruction processingInstruction) { try { processingInstruction.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", processingInstruction.getTemplateName(), processingInstruction.getLine(), processingInstruction.getCol(), e); } // Just in case someone set us a 'next' super.handleProcessingInstruction(processingInstruction); } }
try { cdataSection.write(this.writer); } catch (final Exception e) { throw new TemplateOutputException( "An error happened during template rendering", cdataSection.getTemplateName(), cdataSection.getLine(), cdataSection.getCol(), e); } // Just in case someone set us a 'next' super.handleCDATASection(cdataSection);
1,185
107
1,292
<methods>public void handleCDATASection(org.thymeleaf.model.ICDATASection) ,public void handleCloseElement(org.thymeleaf.model.ICloseElementTag) ,public void handleComment(org.thymeleaf.model.IComment) ,public void handleDocType(org.thymeleaf.model.IDocType) ,public void handleOpenElement(org.thymeleaf.model.IOpenElementTag) ,public void handleProcessingInstruction(org.thymeleaf.model.IProcessingInstruction) ,public void handleStandaloneElement(org.thymeleaf.model.IStandaloneElementTag) ,public void handleTemplateEnd(org.thymeleaf.model.ITemplateEnd) ,public void handleTemplateStart(org.thymeleaf.model.ITemplateStart) ,public void handleText(org.thymeleaf.model.IText) ,public void handleXMLDeclaration(org.thymeleaf.model.IXMLDeclaration) ,public void setContext(org.thymeleaf.context.ITemplateContext) ,public void setNext(org.thymeleaf.engine.ITemplateHandler) <variables>private org.thymeleaf.context.ITemplateContext context,private org.thymeleaf.engine.ITemplateHandler next
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ProcessingInstruction.java
ProcessingInstruction
asEngineProcessingInstruction
class ProcessingInstruction extends AbstractTemplateEvent implements IProcessingInstruction, IEngineTemplateEvent { private final String target; private final String content; private final String processingInstruction; ProcessingInstruction( final String target, final String content) { super(); this.target = target; this.content = content; this.processingInstruction = computeProcessingInstruction(); } ProcessingInstruction( final String processingInstruction, final String target, final String content, final String templateName, final int line, final int col) { super(templateName, line, col); this.target = target; this.content = content; this.processingInstruction = (processingInstruction != null? processingInstruction : computeProcessingInstruction()); } public String getTarget() { return this.target; } public String getContent() { return this.content; } public String getProcessingInstruction() { return this.processingInstruction; } private String computeProcessingInstruction() { final StringBuilder strBuilder = new StringBuilder(100); strBuilder.append("<?"); strBuilder.append(this.target); if (this.content != null) { strBuilder.append(' '); strBuilder.append(this.content); } strBuilder.append("?>"); return strBuilder.toString(); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writer.write(this.processingInstruction); } static ProcessingInstruction asEngineProcessingInstruction(final IProcessingInstruction processingInstruction) {<FILL_FUNCTION_BODY>} @Override public void beHandled(final ITemplateHandler handler) { handler.handleProcessingInstruction(this); } @Override public String toString() { return getProcessingInstruction(); } }
if (processingInstruction instanceof ProcessingInstruction) { return (ProcessingInstruction) processingInstruction; } return new ProcessingInstruction( null, processingInstruction.getTarget(), processingInstruction.getContent(), processingInstruction.getTemplateName(), processingInstruction.getLine(), processingInstruction.getCol());
557
89
646
<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/ProcessingInstructionStructureHandler.java
ProcessingInstructionStructureHandler
replaceWith
class ProcessingInstructionStructureHandler implements IProcessingInstructionStructureHandler { boolean setProcessingInstruction; String setProcessingInstructionTarget; String setProcessingInstructionContent; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeProcessingInstruction; ProcessingInstructionStructureHandler() { super(); reset(); } public void setProcessingInstruction(final String target, final String content) { reset(); Validate.notNull(target, "Target cannot be null"); Validate.notNull(content, "Content cannot be null"); this.setProcessingInstruction = true; this.setProcessingInstructionTarget = target; this.setProcessingInstructionContent = content; } public void replaceWith(final IModel model, final boolean processable) {<FILL_FUNCTION_BODY>} public void removeProcessingInstruction() { reset(); this.removeProcessingInstruction = true; } public void reset() { this.setProcessingInstruction = false; this.setProcessingInstructionTarget = null; this.setProcessingInstructionContent = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeProcessingInstruction = false; } }
reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable;
381
57
438
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ProcessorExecutionVars.java
ProcessorExecutionVars
cloneVars
class ProcessorExecutionVars { final ElementProcessorIterator processorIterator; Model modelBefore = null; Model modelAfter = null; boolean modelAfterProcessable = false; boolean discardEvent = false; TemplateModelController.SkipBody skipBody = TemplateModelController.SkipBody.PROCESS; boolean skipCloseTag = false; ProcessorExecutionVars() { super(); this.processorIterator = new ElementProcessorIterator(); } ProcessorExecutionVars cloneVars() {<FILL_FUNCTION_BODY>} }
final ProcessorExecutionVars clone = new ProcessorExecutionVars(); clone.processorIterator.resetAsCloneOf(this.processorIterator); if (this.modelBefore != null) { clone.modelBefore = (Model) this.modelBefore.cloneModel(); } if (this.modelAfter != null) { clone.modelAfter = (Model) this.modelAfter.cloneModel(); } clone.modelAfterProcessable = this.modelAfterProcessable; clone.discardEvent = this.discardEvent; clone.skipBody = this.skipBody; clone.skipCloseTag = this.skipCloseTag; return clone;
142
167
309
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/SSEThrottledTemplateWriter.java
SSEThrottledTemplateWriter
doStartEvent
class SSEThrottledTemplateWriter extends ThrottledTemplateWriter implements ISSEThrottledTemplateWriterControl { private final static char[] SSE_ID_PREFIX = "id: ".toCharArray(); private final static char[] SSE_EVENT_PREFIX = "event: ".toCharArray(); private final static char[] SSE_DATA_PREFIX = "data: ".toCharArray(); private char[] id = null; private char[] event = null; private boolean eventHasMeta = false; private boolean newEvent = true; SSEThrottledTemplateWriter(final String templateName, final TemplateFlowController flowController) { super(templateName, flowController); } public void startEvent(final char[] id, final char[] event) { // char[] are mutable but this is not an issue as this class is package-protected and the code from // which this method is called is under control this.newEvent = true; this.id = id; this.event = event; } private void doStartEvent() throws IOException {<FILL_FUNCTION_BODY>} public void endEvent() throws IOException { if (!this.newEvent) { super.write('\n'); super.write('\n'); } else if (this.eventHasMeta) { // If we only wrote meta, we still need an additional line feed to separate from the next event super.write('\n'); } } @Override public void write(final int c) throws IOException { if (this.newEvent) { doStartEvent(); super.write(SSE_DATA_PREFIX); this.newEvent = false; } super.write(c); if (c == '\n') { // This is a line feed, so we need to write the prefix afterwards super.write(SSE_DATA_PREFIX); } } @Override public void write(final String str) throws IOException { write(str, 0, str.length()); } @Override public void write(final String str, final int off, final int len) throws IOException { if (str == null) { throw new NullPointerException(); } else if ((off < 0) || (off > str.length()) || (len < 0) || ((off + len) > str.length()) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len == 0) { // Even if we are writing nothing, we need to give the underlying buffered implementation the chance to // overflow... super.write(str, off, len); return; } if (this.newEvent) { doStartEvent(); super.write(SSE_DATA_PREFIX); this.newEvent = false; } char c; int i = off; int x = i; final int maxi = (off + len); while (i < maxi) { c = str.charAt(i++); if (c == '\n') { // This is a line feed, so we write everything until this point, then the prefix, then we continue super.write(str, x, (i - x)); super.write(SSE_DATA_PREFIX); x = i; } } // Finally we write whatever is left at the original buffer if (x < i) { super.write(str, x, (i - x)); } } @Override public void write(final char[] cbuf) throws IOException { write(cbuf, 0, cbuf.length); } @Override public void write(final char[] cbuf, final int off, final int len) throws IOException { if (cbuf == null) { throw new NullPointerException(); } else if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len == 0) { // Even if we are writing nothing, we need to give the underlying buffered implementation the chance to // overflow... super.write(cbuf, off, len); return; } if (this.newEvent) { doStartEvent(); super.write(SSE_DATA_PREFIX); this.newEvent = false; } char c; int i = off; int x = i; final int maxi = (off + len); while (i < maxi) { c = cbuf[i++]; if (c == '\n') { // This is a line feed, so we write everything until this point, then the prefix, then we continue super.write(cbuf, x, (i - x)); super.write(SSE_DATA_PREFIX); x = i; } } // Finally we write whatever is left at the original buffer if (x < i) { super.write(cbuf, x, (i - x)); } } // Used to check internally that neither event names nor IDs contain line feeds private static boolean checkTokenValid(final char[] token) { if (token == null || token.length == 0) { return true; } for (int i = 0; i < token.length; i++) { if (token[i] == '\n') { return false; } } return true; } }
this.eventHasMeta = false; if (this.event != null) { // Write the "event" field if (!checkTokenValid(this.event)) { throw new IllegalArgumentException("Event for SSE event cannot contain a newline (\\n) character"); } super.write(SSE_EVENT_PREFIX); super.write(this.event); super.write('\n'); this.eventHasMeta = true; } if (this.id != null) { // Write the "id" field if (!checkTokenValid(this.id)) { throw new IllegalArgumentException("ID for SSE event cannot contain a newline (\\n) character"); } super.write(SSE_ID_PREFIX); super.write(this.id); super.write('\n'); this.eventHasMeta = true; }
1,446
225
1,671
<methods>public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public int getMaxOverflowSize() ,public int getOverflowGrowCount() ,public int getWrittenCount() ,public boolean isOverflown() throws java.io.IOException,public boolean isStopped() throws java.io.IOException,public void write(int) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(char[], int, int) throws java.io.IOException<variables>private org.thymeleaf.engine.ThrottledTemplateWriter.IThrottledTemplateWriterAdapter adapter,private final non-sealed org.thymeleaf.engine.TemplateFlowController flowController,private boolean flushable,private final non-sealed java.lang.String templateName,private java.io.Writer writer
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/SimpleModelProcessable.java
SimpleModelProcessable
process
class SimpleModelProcessable implements IEngineProcessable { private final Model model; private final ITemplateHandler modelHandler; private final TemplateFlowController flowController; private int offset; SimpleModelProcessable( final Model model, final ITemplateHandler modelHandler, final TemplateFlowController flowController) { super(); this.model = model; this.modelHandler = modelHandler; this.flowController = flowController; this.offset = 0; } public boolean process() {<FILL_FUNCTION_BODY>} ITemplateHandler getModelHandler() { return this.modelHandler; } Model getModel() { return this.model; } }
/* * First, check the stopProcess flag */ if (this.flowController.stopProcessing) { return false; } /* * Process the queue */ this.offset += this.model.process(this.modelHandler, this.offset, this.flowController); /* * Compute whether the whole model has been processed or not */ return (this.offset == this.model.queueSize && !this.flowController.stopProcessing);
187
128
315
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/StandaloneElementTag.java
StandaloneElementTag
setAttribute
class StandaloneElementTag extends AbstractProcessableElementTag implements IStandaloneElementTag, IEngineTemplateEvent { final boolean minimized; StandaloneElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final Attributes attributes, final boolean synthetic, final boolean minimized) { super(templateMode, elementDefinition, elementCompleteName, attributes, synthetic); Validate.isTrue(minimized || templateMode == TemplateMode.HTML, "Not-minimized standalone elements are only allowed in HTML template mode (is " + templateMode + ")"); this.minimized = minimized; } StandaloneElementTag( final TemplateMode templateMode, final ElementDefinition elementDefinition, final String elementCompleteName, final Attributes attributes, final boolean synthetic, final boolean minimized, final String templateName, final int line, final int col) { super(templateMode, elementDefinition, elementCompleteName, attributes, synthetic, templateName, line, col); Validate.isTrue(minimized || templateMode == TemplateMode.HTML, "Not-minimized standalone elements are only allowed in HTML template mode (is " + templateMode + ")"); this.minimized = minimized; } public boolean isMinimized() { return this.minimized; } StandaloneElementTag setAttribute( final AttributeDefinitions attributeDefinitions, final AttributeDefinition attributeDefinition, final String completeName, final String value, final AttributeValueQuotes valueQuotes) {<FILL_FUNCTION_BODY>} StandaloneElementTag replaceAttribute( final AttributeDefinitions attributeDefinitions, final AttributeName oldName, final AttributeDefinition newAttributeDefinition, final String completeNewName, final String value, final AttributeValueQuotes valueQuotes) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.replaceAttribute(attributeDefinitions, this.templateMode, oldName, newAttributeDefinition, completeNewName, value, valueQuotes); return new StandaloneElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.minimized, this.templateName, this.line, this.col); } StandaloneElementTag removeAttribute(final String prefix, final String name) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(this.templateMode, prefix, name); if (oldAttributes == newAttributes) { return this; } return new StandaloneElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.minimized, this.templateName, this.line, this.col); } StandaloneElementTag removeAttribute(final String completeName) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(this.templateMode, completeName); if (oldAttributes == newAttributes) { return this; } return new StandaloneElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.minimized, this.templateName, this.line, this.col); } StandaloneElementTag removeAttribute(final AttributeName attributeName) { final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.removeAttribute(attributeName); if (oldAttributes == newAttributes) { return this; } return new StandaloneElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.minimized, this.templateName, this.line, this.col); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { if (this.synthetic) { // Nothing to be written... synthetic elements were not present at the original template! return; } if (this.templateMode.isText()) { writer.write("[#"); writer.write(this.elementCompleteName); if (this.attributes != null) { this.attributes.write(writer); } if (this.minimized) { writer.write("/]"); } else { writer.write("]"); } return; } writer.write('<'); writer.write(this.elementCompleteName); if (this.attributes != null) { this.attributes.write(writer); } if (this.minimized) { writer.write("/>"); } else { writer.write('>'); } } // Meant to be called only from within the engine static StandaloneElementTag asEngineStandaloneElementTag(final IStandaloneElementTag standaloneElementTag) { if (standaloneElementTag instanceof StandaloneElementTag) { return (StandaloneElementTag) standaloneElementTag; } final IAttribute[] originalAttributeArray = standaloneElementTag.getAllAttributes(); final Attributes attributes; if (originalAttributeArray == null || originalAttributeArray.length == 0) { attributes = null; } else { // We will perform a deep cloning of the attributes into objects of the Attribute class, so that // we make sure absolutely all Attributes in the new event are under the engine's control final Attribute[] newAttributeArray = new Attribute[originalAttributeArray.length]; for (int i = 0; i < originalAttributeArray.length; i++) { final IAttribute originalAttribute = originalAttributeArray[i]; newAttributeArray[i] = new Attribute( originalAttribute.getAttributeDefinition(), originalAttribute.getAttributeCompleteName(), originalAttribute.getOperator(), originalAttribute.getValue(), originalAttribute.getValueQuotes(), originalAttribute.getTemplateName(), originalAttribute.getLine(), originalAttribute.getCol()); } final String[] newInnerWhiteSpaces; if (newAttributeArray.length == 1) { newInnerWhiteSpaces = Attributes.DEFAULT_WHITE_SPACE_ARRAY; } else { newInnerWhiteSpaces = new String[newAttributeArray.length]; Arrays.fill(newInnerWhiteSpaces, Attributes.DEFAULT_WHITE_SPACE); } attributes = new Attributes(newAttributeArray, newInnerWhiteSpaces); } return new StandaloneElementTag( standaloneElementTag.getTemplateMode(), standaloneElementTag.getElementDefinition(), standaloneElementTag.getElementCompleteName(), attributes, standaloneElementTag.isSynthetic(), standaloneElementTag.isMinimized(), standaloneElementTag.getTemplateName(), standaloneElementTag.getLine(), standaloneElementTag.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleStandaloneElement(this); } }
final Attributes oldAttributes = (this.attributes != null? this.attributes : Attributes.EMPTY_ATTRIBUTES); final Attributes newAttributes = oldAttributes.setAttribute(attributeDefinitions, this.templateMode, attributeDefinition, completeName, value, valueQuotes); return new StandaloneElementTag(this.templateMode, this.elementDefinition, this.elementCompleteName, newAttributes, this.synthetic, this.minimized, this.templateName, this.line, this.col);
1,883
126
2,009
<methods>public org.thymeleaf.model.IAttribute[] getAllAttributes() ,public final org.thymeleaf.model.IAttribute getAttribute(java.lang.String) ,public final org.thymeleaf.model.IAttribute getAttribute(java.lang.String, java.lang.String) ,public final org.thymeleaf.model.IAttribute getAttribute(org.thymeleaf.engine.AttributeName) ,public Map<java.lang.String,java.lang.String> getAttributeMap() ,public final java.lang.String getAttributeValue(java.lang.String) ,public final java.lang.String getAttributeValue(java.lang.String, java.lang.String) ,public final java.lang.String getAttributeValue(org.thymeleaf.engine.AttributeName) ,public final boolean hasAttribute(java.lang.String) ,public final boolean hasAttribute(java.lang.String, java.lang.String) ,public final boolean hasAttribute(org.thymeleaf.engine.AttributeName) <variables>private static final org.thymeleaf.processor.element.IElementProcessor[] EMPTY_ASSOCIATED_PROCESSORS,private volatile org.thymeleaf.processor.element.IElementProcessor[] associatedProcessors,final non-sealed org.thymeleaf.engine.Attributes attributes
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/StandaloneElementTagModelProcessable.java
StandaloneElementTagModelProcessable
process
class StandaloneElementTagModelProcessable implements IEngineProcessable { private final StandaloneElementTag standaloneElementTag; private final ProcessorExecutionVars vars; private final IEngineContext context; private final TemplateFlowController flowController; private final TemplateModelController modelController; private final ProcessorTemplateHandler processorTemplateHandler; private final ITemplateHandler nextTemplateHandler; private boolean beforeProcessed; private boolean delegationProcessed; private boolean afterProcessed; private int offset; StandaloneElementTagModelProcessable( final StandaloneElementTag standaloneElementTag, final ProcessorExecutionVars vars, final IEngineContext context, final TemplateModelController modelController, final TemplateFlowController flowController, final ProcessorTemplateHandler processorTemplateHandler, final ITemplateHandler nextTemplateHandler) { super(); this.standaloneElementTag = standaloneElementTag; this.vars = vars; this.context = context; this.flowController = flowController; this.modelController = modelController; this.processorTemplateHandler = processorTemplateHandler; this.nextTemplateHandler = nextTemplateHandler; this.beforeProcessed = false; this.delegationProcessed = false; this.afterProcessed = false; this.offset = 0; } public boolean process() {<FILL_FUNCTION_BODY>} }
/* * First, check the stopProcess flag */ if (this.flowController.stopProcessing) { return false; } if (!this.beforeProcessed) { /* * PROCESS THE QUEUE BEFORE DELEGATING, if specified to do so */ if (this.vars.modelBefore != null) { this.offset += this.vars.modelBefore.process(this.nextTemplateHandler, this.offset, this.flowController); // This is never processable if (this.offset < this.vars.modelBefore.queueSize || this.flowController.stopProcessing) { return false; } } this.beforeProcessed = true; this.offset = 0; } if (!this.delegationProcessed) { /* * PROCESS THE REST OF THE HANDLER CHAIN and INCREASE THE MODEL LEVEL RIGHT AFTERWARDS */ if (!this.vars.discardEvent) { this.nextTemplateHandler.handleStandaloneElement(this.standaloneElementTag); } this.delegationProcessed = true; this.offset = 0; } if (this.flowController.stopProcessing) { return false; } if (!this.afterProcessed) { /* * PROCESS THE QUEUE, launching all the queued events. Note executing the queue after increasing the model * level makes sense even if what the queue contains is a replacement for the complete element (including open * and close tags), because that way whatever comes in the queue will be encapsulated in a different model level * and its internal open/close tags should not affect the correct delimitation of this block. */ if (this.vars.modelAfter != null) { final ITemplateHandler modelHandler = this.vars.modelAfterProcessable ? this.processorTemplateHandler : this.nextTemplateHandler; this.offset += this.vars.modelAfter.process(modelHandler, this.offset, this.flowController); if (this.offset < this.vars.modelAfter.queueSize || this.flowController.stopProcessing) { return false; } } this.afterProcessed = true; } /* * DECREASE THE CONTEXT LEVEL once we have executed all the processors (and maybe a body if we added * one to the tag converting it into an open tag) */ if (this.context != null) { this.context.decreaseLevel(); } return true;
348
649
997
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateBoundariesStructureHandler.java
TemplateBoundariesStructureHandler
setLocalVariable
class TemplateBoundariesStructureHandler implements ITemplateBoundariesStructureHandler { boolean insertText; String insertTextValue; boolean insertTextProcessable; boolean insertModel; IModel insertModelValue; boolean insertModelProcessable; boolean setLocalVariable; Map<String,Object> addedLocalVariables; boolean removeLocalVariable; Set<String> removedLocalVariableNames; boolean setSelectionTarget; Object selectionTargetObject; boolean setInliner; IInliner setInlinerValue; TemplateBoundariesStructureHandler() { super(); reset(); } public void insert(final String text, final boolean processable) { resetAllButLocalVariables(); Validate.notNull(text, "Text cannot be null"); this.insertText = true; this.insertTextValue = text; this.insertTextProcessable = processable; } public void insert(final IModel model, final boolean processable) { resetAllButLocalVariables(); Validate.notNull(model, "Model cannot be null"); this.insertModel = true; this.insertModelValue = model; this.insertModelProcessable = processable; } public void removeLocalVariable(final String name) { // Can be combined with others, no need to resetGathering this.removeLocalVariable = true; if (this.removedLocalVariableNames == null) { this.removedLocalVariableNames = new HashSet<String>(3); } this.removedLocalVariableNames.add(name); } public void setLocalVariable(final String name, final Object value) {<FILL_FUNCTION_BODY>} public void setSelectionTarget(final Object selectionTarget) { // Can be combined with others, no need to resetGathering this.setSelectionTarget = true; this.selectionTargetObject = selectionTarget; } public void setInliner(final IInliner inliner) { this.setInliner = true; this.setInlinerValue = inliner; } public void reset() { resetAllButLocalVariables(); this.setLocalVariable = false; if (this.addedLocalVariables != null) { this.addedLocalVariables.clear(); } this.removeLocalVariable = false; if (this.removedLocalVariableNames != null) { this.removedLocalVariableNames.clear(); } this.setSelectionTarget = false; this.selectionTargetObject = null; this.setInliner = false; this.setInlinerValue = null; } private void resetAllButLocalVariables() { this.insertText = false; this.insertTextValue = null; this.insertTextProcessable = false; this.insertModel = false; this.insertModelValue = null; this.insertModelProcessable = false; } void applyContextModifications(final IEngineContext engineContext) { if (this.setLocalVariable) { engineContext.setVariables(this.addedLocalVariables); } if (this.removeLocalVariable) { for (final String variableName : this.removedLocalVariableNames) { engineContext.removeVariable(variableName); } } if (this.setSelectionTarget) { engineContext.setSelectionTarget(this.selectionTargetObject); } if (this.setInliner) { engineContext.setInliner(this.setInlinerValue); } } }
// Can be combined with others, no need to resetGathering this.setLocalVariable = true; if (this.addedLocalVariables == null) { this.addedLocalVariables = new HashMap<String, Object>(3); } this.addedLocalVariables.put(name, value);
953
81
1,034
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateData.java
TemplateData
hasTemplateSelectors
class TemplateData { private final String template; private final Set<String> templateSelectors; private final ITemplateResource templateResource; private final TemplateMode templateMode; private final ICacheEntryValidity cacheValidity; /** * <p> * Builds a new {@code TemplateData} object. * </p> * <p> * This constructor should be considered internal, as there should be no reason why * instances of this class should be created from outside the Template Engine itself. * </p> * * @param template the template * @param templateSelectors the template selectors * @param templateResource the template resource * @param templateMode the template mode */ TemplateData( final String template, final Set<String> templateSelectors, final ITemplateResource templateResource, final TemplateMode templateMode, final ICacheEntryValidity cacheValidity) { super(); // NO VALIDATIONS OR TRANSFORMATIONS ARE PERFORMED ON DATA. This constructor is package-protected so that // objects of this class can only be created from the engine (specifically, the TemplateManager). This // template manager will make sure only templateSelectors and templateResolutionAttributes can be null, and // that if they aren't they should be non-empty. Also, templateSelectors will come ordered by natural order, // an operation that is performed at the TemplateSpec constructor itself. this.template = template; this.templateSelectors = templateSelectors; this.templateResource = templateResource; this.templateMode = templateMode; this.cacheValidity = cacheValidity; } /** * <p> * Returns the template (usually the template name). * </p> * <p> * This <em>template</em> normally represents the <em>template name</em>, but can be the entire template * contents if the template was specified as a String and resolved by a * {@link org.thymeleaf.templateresolver.StringTemplateResolver} or equivalent. * </p> * * @return the template. Cannot be null. */ public String getTemplate() { return this.template; } /** * <p> * Returns whether this spec has template selectors specified or not. * </p> * * @return {@code true} of there are template selectors, {@code false} if not. */ public boolean hasTemplateSelectors() {<FILL_FUNCTION_BODY>} /** * <p> * Returns the template selectors, if there are any. * </p> * <p> * Template selectors allow the possibility to process only a part of the specified template, expressing * this selection in a syntax similar to jQuery, CSS or XPath selectors. Note this is only available for * <em>markup template modes</em> ({@code HTML}, {@code XML}). For more info on <em>template selectors</em> * syntax, have a look at <a href="http://www.attoparser.org">AttoParser</a>'s <em>markup selectors</em> * documentation. * </p> * * @return the template selectors, or {@code null} if there are none. */ public Set<String> getTemplateSelectors() { return this.templateSelectors; } /** * <p> * Returns the template resource. * </p> * <p> * Template resource instances are usually created by implementations of * {@link org.thymeleaf.templateresolver.ITemplateResolver}. * </p> * <p> * Note that, even if this resource object will never be {@code null}, the existence of the * resource object does not necessarily imply the existence of the resource itself unless * the template resolver was configured for calling {@link ITemplateResource#exists()} upon * template resolution. * </p> * * @return the template resource. Cannot be null. */ public ITemplateResource getTemplateResource() { return this.templateResource; } /** * <p> * Returns the template mode the template is being processed with. * </p> * <p> * Most times this template mode is the one suggested by the * {@link org.thymeleaf.templateresolver.ITemplateResolver} that resolved the template, but * in those times that a template mode was <em>forced</em> by specifying it at a * {@link org.thymeleaf.TemplateSpec} object or at a call to the {@link org.thymeleaf.engine.TemplateManager}, * these will override the template mode suggested by the template resolver. * </p> * * @return the template mode for the template. Cannot be null. */ public TemplateMode getTemplateMode() { return this.templateMode; } /** * <p> * Returns the template resolution <i>validity</i>. * </p> * <p> * This validity establishes whether the template can be included in the * template cache, and also for how long its resolution will be considered <i>valid</i>. * </p> * <p> * When a cached template is not considered valid, its cache entry is discarded * and it is resolved again. * </p> * * @return the validity object */ public ICacheEntryValidity getValidity() { return this.cacheValidity; } }
// Checking for null is enough, as we have already processed this in the constructor return this.templateSelectors != null;
1,475
34
1,509
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateEnd.java
TemplateEnd
write
class TemplateEnd extends AbstractTemplateEvent implements ITemplateEnd, IEngineTemplateEvent { final static TemplateEnd TEMPLATE_END_INSTANCE = new TemplateEnd(); private TemplateEnd() { super(); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException {<FILL_FUNCTION_BODY>} // Meant to be called only from within the engine static TemplateEnd asEngineTemplateEnd(final ITemplateEnd templateEnd) { return TEMPLATE_END_INSTANCE; } @Override public void beHandled(final ITemplateHandler handler) { handler.handleTemplateEnd(this); } @Override public final String toString() { return ""; } }
// Nothing to be done here -- template end events are not writable to output!
230
22
252
<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/TemplateEndModelProcessable.java
TemplateEndModelProcessable
process
class TemplateEndModelProcessable implements IEngineProcessable { private final ITemplateEnd templateEnd; private final Model model; private final ITemplateHandler modelHandler; private final ProcessorTemplateHandler processorTemplateHandler; private final ITemplateHandler nextHandler; private final TemplateFlowController flowController; private int offset; TemplateEndModelProcessable( final ITemplateEnd templateEnd, final Model model, final ITemplateHandler modelHandler, final ProcessorTemplateHandler processorTemplateHandler, final ITemplateHandler nextHandler, final TemplateFlowController flowController) { super(); this.templateEnd = templateEnd; this.model = model; this.modelHandler = modelHandler; this.processorTemplateHandler = processorTemplateHandler; this.nextHandler = nextHandler; this.flowController = flowController; this.offset = 0; } public boolean process() {<FILL_FUNCTION_BODY>} }
/* * First, check the stopProcess flag */ if (this.flowController.stopProcessing) { return false; } /* * Process the queue */ this.offset += this.model.process(this.modelHandler, this.offset, this.flowController); if (this.offset < this.model.queueSize || this.flowController.stopProcessing) { return false; } /* * PROCESS THE REST OF THE HANDLER CHAIN. */ this.nextHandler.handleTemplateEnd(this.templateEnd); /* * LAST ROUND OF CHECKS. If we have not returned our indexes to -1, something has gone wrong during processing */ this.processorTemplateHandler.performTearDownChecks(this.templateEnd); /* * RETURN TRUE. Even if a stop was signaled after handling the TemplateEnd, we should not worry about it * because it would only affect events being executed AFTER delegating. And there are no events executing * after the TemplateEnd, ever. */ return true;
240
286
526
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateHandlerAdapterRawHandler.java
TemplateHandlerAdapterRawHandler
handleText
class TemplateHandlerAdapterRawHandler implements IRawHandler { private final String templateName; private final ITemplateHandler templateHandler; private final int lineOffset; private final int colOffset; public TemplateHandlerAdapterRawHandler(final String templateName, final ITemplateHandler templateHandler, final int lineOffset, final int colOffset) { super(); Validate.notNull(templateHandler, "Template handler cannot be null"); this.templateName = templateName; this.templateHandler = templateHandler; // These cannot be null this.lineOffset = (lineOffset > 0 ? lineOffset - 1 : lineOffset); // line n for offset will be line 1 for the newly parsed template this.colOffset = (colOffset > 0 ? colOffset - 1 : colOffset); // line n for offset will be line 1 for the newly parsed template } public void handleDocumentStart( final long startTimeNanos, final int line, final int col) throws RawParseException { // The reported times refer to parsing times, and processing a template is more complex, so we'll just ignore the info this.templateHandler.handleTemplateStart(TemplateStart.TEMPLATE_START_INSTANCE); } public void handleDocumentEnd( final long endTimeNanos, final long totalTimeNanos, final int line, final int col) throws RawParseException { // The reported times refer to parsing times, and processing a template is more complex, so we'll just ignore the info this.templateHandler.handleTemplateEnd(TemplateEnd.TEMPLATE_END_INSTANCE); } public void handleText( final char[] buffer, final int offset, final int len, final int line, final int col) throws RawParseException {<FILL_FUNCTION_BODY>} }
this.templateHandler.handleText( new Text(new String(buffer, offset, len), this.templateName, this.lineOffset + line, (line == 1? this.colOffset : 0) + col));
465
55
520
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateModel.java
TemplateModel
immutableModelException
class TemplateModel implements IModel { final IEngineConfiguration configuration; final TemplateData templateData; final IEngineTemplateEvent[] queue; // This is final because this IModel is IMMUTABLE // Package-protected constructor, because we don't want anyone creating these objects from outside the engine. // If a processor (be it standard or custom-made) wants to create a piece of model, that should be a Model // object, not this. TemplateModel( final IEngineConfiguration configuration, final TemplateData templateData, final IEngineTemplateEvent[] queue) { super(); Validate.notNull(configuration, "Engine Configuration cannot be null"); Validate.notNull(templateData, "Template Resolution cannot be null"); Validate.notNull(queue, "Event queue cannot be null"); Validate.isTrue(queue.length >= 2, "At least TemplateStart/TemplateEnd events must be added to a TemplateModel"); Validate.isTrue(queue[0] == TemplateStart.TEMPLATE_START_INSTANCE, "First event in queue is not TemplateStart"); Validate.isTrue(queue[queue.length - 1] == TemplateEnd.TEMPLATE_END_INSTANCE, "Last event in queue is not TemplateEnd"); this.configuration = configuration; this.templateData = templateData; this.queue = queue; } public final TemplateData getTemplateData() { return this.templateData; } public final IEngineConfiguration getConfiguration() { return this.configuration; } public final TemplateMode getTemplateMode() { return this.templateData.getTemplateMode(); } public final int size() { return this.queue.length; } public final ITemplateEvent get(final int pos) { return this.queue[pos]; } public final void add(final ITemplateEvent event) { immutableModelException(); } public final void insert(final int pos, final ITemplateEvent event) { immutableModelException(); } public final void replace(final int pos, final ITemplateEvent event) { immutableModelException(); } public final void addModel(final IModel model) { immutableModelException(); } public final void insertModel(final int pos, final IModel model) { immutableModelException(); } public final void remove(final int pos) { immutableModelException(); } public final void reset() { immutableModelException(); } void process(final ITemplateHandler handler) { for (int i = 0; i < this.queue.length; i++) { this.queue[i].beHandled(handler); } } int process(final ITemplateHandler handler, final int offset, final TemplateFlowController controller) { if (controller == null) { process(handler); return this.queue.length; } if (this.queue.length == 0 || offset >= this.queue.length) { return 0; } int processed = 0; for (int i = offset; i < this.queue.length && !controller.stopProcessing; i++) { this.queue[i].beHandled(handler); processed++; } return processed; } public final IModel cloneModel() { return new Model(this); } public final void write(final Writer writer) throws IOException { for (int i = 0; i < this.queue.length; i++) { this.queue[i].write(writer); } } public void accept(final IModelVisitor visitor) { for (int i = 0; i < this.queue.length; i++) { // We will execute the visitor on the Immutable events, that we need to create during the visit this.queue[i].accept(visitor); } } @Override public final String toString() { try { final Writer writer = new FastStringWriter(); write(writer); return writer.toString(); } catch (final IOException e) { throw new TemplateProcessingException( "Error while creating String representation of model"); } } private static void immutableModelException() {<FILL_FUNCTION_BODY>} }
throw new UnsupportedOperationException( "Modifications are not allowed on immutable model objects. This model object is an immutable " + "implementation of the " + IModel.class.getName() + " interface, and no modifications are allowed in " + "order to keep cache consistency and improve performance. To modify model events, convert first your " + "immutable model object to a mutable one by means of the " + IModel.class.getName() + "#cloneModel() method");
1,135
117
1,252
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TemplateStart.java
TemplateStart
write
class TemplateStart extends AbstractTemplateEvent implements ITemplateStart, IEngineTemplateEvent { final static TemplateStart TEMPLATE_START_INSTANCE = new TemplateStart(); private TemplateStart() { super(); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException {<FILL_FUNCTION_BODY>} // Meant to be called only from within the engine static TemplateStart asEngineTemplateStart(final ITemplateStart templateStart) { return TEMPLATE_START_INSTANCE; } @Override public void beHandled(final ITemplateHandler handler) { handler.handleTemplateStart(this); } @Override public final String toString() { return ""; } }
// Nothing to be done here -- template start events are not writable to output!
230
22
252
<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/Text.java
Text
asEngineText
class Text extends AbstractTextualTemplateEvent implements IText { Text(final CharSequence text) { super(text); } Text(final CharSequence text, final String templateName, final int line, final int col) { super(text, templateName, line, col); } public String getText() { return getContentText(); } public int length() { return getContentLength(); } public char charAt(final int index) { return charAtContent(index); } public CharSequence subSequence(final int start, final int end) { return contentSubSequence(start, end); } public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writeContent(writer); } // Meant to be called only from within the engine static Text asEngineText(final IText text) {<FILL_FUNCTION_BODY>} @Override public void beHandled(final ITemplateHandler handler) { handler.handleText(this); } @Override public String toString() { return getText(); } }
if (text instanceof Text) { return (Text) text; } return new Text(text.getText(), text.getTemplateName(), text.getLine(), text.getCol());
339
49
388
<methods>public java.lang.String toString() ,public final void writeContent(java.io.Writer) throws java.io.IOException<variables>private volatile java.lang.Boolean computedContentIsInlineable,private volatile java.lang.Boolean computedContentIsWhitespace,private volatile int computedContentLength,private volatile java.lang.String computedContentStr,private final non-sealed java.lang.CharSequence contentCharSeq,private final non-sealed int contentLength,private final non-sealed java.lang.String contentStr
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TextAttributeName.java
TextAttributeName
forName
class TextAttributeName extends AttributeName { final String completeNamespacedAttributeName; static TextAttributeName forName(final String prefix, final String attributeName) {<FILL_FUNCTION_BODY>} private TextAttributeName( final String prefix, final String attributeName, final String completeNamespacedAttributeName, final String[] completeAttributeNames) { super(prefix, attributeName, completeAttributeNames); this.completeNamespacedAttributeName = completeNamespacedAttributeName; } public String getCompleteNamespacedAttributeName() { return this.completeNamespacedAttributeName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; final String completeNamespacedAttributeName; final String[] completeAttributeNames; if (hasPrefix) { completeNamespacedAttributeName = prefix + ":" + attributeName; completeAttributeNames = new String[] { completeNamespacedAttributeName }; } else { completeNamespacedAttributeName = attributeName; completeAttributeNames = new String[] { attributeName }; } return new TextAttributeName( prefix, attributeName, completeNamespacedAttributeName, completeAttributeNames);
166
154
320
<methods>public boolean equals(java.lang.Object) ,public java.lang.String getAttributeName() ,public java.lang.String[] getCompleteAttributeNames() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String attributeName,protected final non-sealed java.lang.String[] completeAttributeNames,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TextElementName.java
TextElementName
forName
class TextElementName extends ElementName { final String completeNamespacedElementName; static TextElementName forName(final String prefix, final String elementName) {<FILL_FUNCTION_BODY>} private TextElementName( final String prefix, final String elementName, final String completeNamespacedElementName, final String[] completeElementNames) { super(prefix, elementName, completeElementNames); this.completeNamespacedElementName = completeNamespacedElementName; } public String getCompleteNamespacedElementName() { return this.completeNamespacedElementName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; final String completeNamespacedElementName; final String[] completeElementNames; if (hasPrefix) { completeNamespacedElementName = prefix + ":" + elementName; completeElementNames = new String[] { completeNamespacedElementName }; } else { completeNamespacedElementName = elementName; completeElementNames = new String[] { elementName }; } return new TextElementName( prefix, elementName, completeNamespacedElementName, completeElementNames);
166
154
320
<methods>public boolean equals(java.lang.Object) ,public java.lang.String[] getCompleteElementNames() ,public java.lang.String getElementName() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String[] completeElementNames,protected final non-sealed java.lang.String elementName,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/TextStructureHandler.java
TextStructureHandler
reset
class TextStructureHandler implements ITextStructureHandler { boolean setText; CharSequence setTextValue; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeText; TextStructureHandler() { super(); reset(); } public void setText(final CharSequence text) { reset(); Validate.notNull(text, "Text cannot be null"); this.setText = true; this.setTextValue = text; } public void replaceWith(final IModel model, final boolean processable) { reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable; } public void removeText() { reset(); this.removeText = true; } public void reset() {<FILL_FUNCTION_BODY>} }
this.setText = false; this.setTextValue = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeText = false;
271
66
337
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/ThrottledTemplateWriter.java
ThrottledTemplateWriter
setOutput
class ThrottledTemplateWriter extends Writer implements IThrottledTemplateWriterControl { private final String templateName; private final TemplateFlowController flowController; private IThrottledTemplateWriterAdapter adapter; private Writer writer; private boolean flushable; ThrottledTemplateWriter(final String templateName, final TemplateFlowController flowController) { super(); this.templateName = templateName; this.flowController = flowController; this.adapter = null; this.writer = null; this.flushable = false; } void setOutput(final Writer writer) { if (this.adapter != null && this.adapter instanceof ThrottledTemplateWriterOutputStreamAdapter) { throw new TemplateOutputException( "The throttled processor has already been initialized to use byte-based output (OutputStream), " + "but a Writer has been specified.", this.templateName, -1, -1, null); } if (this.adapter == null) { this.adapter = new ThrottledTemplateWriterWriterAdapter(this.templateName, this.flowController); this.writer = ((ThrottledTemplateWriterWriterAdapter)this.adapter); } ((ThrottledTemplateWriterWriterAdapter)this.adapter).setWriter(writer); } void setOutput(final OutputStream outputStream, final Charset charset, final int maxOutputInBytes) {<FILL_FUNCTION_BODY>} public boolean isOverflown() throws IOException { if (this.flushable) { // We need this flushing because OutputStreamWriter bufferizes, and given we might be taking account of // the output bytes at an OutputStream implementation in a level below this OutputStreamWriter, we could // have the wrong figures until we flush contents. this.flush(); this.flushable = false; } return this.adapter.isOverflown(); } public boolean isStopped() throws IOException { if (this.flushable) { // We need this flushing because OutputStreamWriter bufferizes, and given we might be taking account of // the output bytes at an OutputStream implementation in a level below this OutputStreamWriter, we could // have the wrong figures until we flush contents. this.flush(); this.flushable = false; } return this.adapter.isStopped(); } public int getWrittenCount() { return this.adapter.getWrittenCount(); } public int getMaxOverflowSize() { return this.adapter.getMaxOverflowSize(); } public int getOverflowGrowCount() { return this.adapter.getOverflowGrowCount(); } void allow(final int limit) { this.adapter.allow(limit); } @Override public void write(final int c) throws IOException { this.flushable = true; this.writer.write(c); } @Override public void write(final String str) throws IOException { this.flushable = true; this.writer.write(str); } @Override public void write(final String str, final int off, final int len) throws IOException { this.flushable = true; this.writer.write(str, off, len); } @Override public void write(final char[] cbuf) throws IOException { this.flushable = true; this.writer.write(cbuf); } @Override public void write(final char[] cbuf, final int off, final int len) throws IOException { this.flushable = true; this.writer.write(cbuf, off, len); } @Override public void flush() throws IOException { this.writer.flush(); } @Override public void close() throws IOException { this.writer.close(); } interface IThrottledTemplateWriterAdapter { boolean isOverflown(); boolean isStopped(); int getWrittenCount(); int getMaxOverflowSize(); int getOverflowGrowCount(); void allow(final int limit); } }
if (this.adapter != null && this.adapter instanceof ThrottledTemplateWriterWriterAdapter) { throw new TemplateOutputException( "The throttled processor has already been initialized to use char-based output (Writer), " + "but an OutputStream has been specified.", this.templateName, -1, -1, null); } if (this.adapter == null) { final int adapterOverflowBufferIncrementBytes = (maxOutputInBytes == Integer.MAX_VALUE? 128 : // output size could be too small, so we will set a minimum of 16b, and max of 128b Math.min(128, Math.max(16, maxOutputInBytes / 8))); this.adapter = new ThrottledTemplateWriterOutputStreamAdapter(this.templateName, this.flowController, adapterOverflowBufferIncrementBytes); // We cannot directly use a java.io.OutputStreamWriter here because that class uses a CharsetEncoder // underneath that always creates a 8192byte (8KB) buffer, and there is no way to configure that. // // The problem with such buffer is that we are counting the number of output bytes at the OutputStream // wrapper (the adapter we just created), which is set as the output of the OutputStreamWriter, and which // does not receive any bytes until the OutputStreamWriter flushes its 8KB buffer. But in a scenario in // which, for instance, we only need 100 bytes to complete our output chunk, this would mean we would still // have an overflow of more than 8,000 bytes. And that basically renders this whole template throttling // mechanism useless. // // So we will use an alternative construct to OutputStreamWriter, based on a WritableByteChannel. This // will basically work in the same way as an OutputStreamWriter, but by building it manually we will be // able to specify the size of the buffer to be used. // // And we do not want the buffer at the Writer -> OutputStream converter to completely disappear, because // it actually improves the performance of the converter. So we will use the maxOutputInBytes (the size // of the output to be obtained from the throttled template the first time) as an approximate measure // of what we will need in subsequent calls, and we will to try to adjust the size of the buffer so // that we make the most use of it without needing to flush too often, nor 'losing' chars in the buffer. // // Last, note that in order to avoid this 'loss of chars' we will combine this with 'flush' calls at the // 'isOverflown()' and 'isStopped()' calls. final CharsetEncoder charsetEncoder = charset.newEncoder(); int channelBufferSize = (maxOutputInBytes == Integer.MAX_VALUE? 1024 : // Buffers of CharsetEncoders behave strangely (even hanging) when the buffers being // set are too small to house the encoding of some elements (e.g. 1 or 2 bytes). So we // will set a minimum of 64b and a max of 512b. Math.min(512, Math.max(64, adapterOverflowBufferIncrementBytes * 2))); final WritableByteChannel channel = Channels.newChannel((ThrottledTemplateWriterOutputStreamAdapter)this.adapter); this.writer = Channels.newWriter(channel, charsetEncoder, channelBufferSize); // Use of a wrapping BufferedWriter is recommended by OutputStreamWriter javadoc for improving efficiency, // avoiding frequent converter invocations (note that the character converter also has its own buffer). //this.writer = new BufferedWriter(new OutputStreamWriter((ThrottledTemplateWriterOutputStreamAdapter)this.adapter, charset)); } ((ThrottledTemplateWriterOutputStreamAdapter)this.adapter).setOutputStream(outputStream);
1,083
963
2,046
<methods>public java.io.Writer append(java.lang.CharSequence) throws java.io.IOException,public java.io.Writer append(char) throws java.io.IOException,public java.io.Writer append(java.lang.CharSequence, int, int) throws java.io.IOException,public abstract void close() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public static java.io.Writer nullWriter() ,public void write(int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public abstract void write(char[], int, int) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException<variables>private static final int WRITE_BUFFER_SIZE,protected java.lang.Object lock,private char[] writeBuffer
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/XMLAttributeName.java
XMLAttributeName
forName
class XMLAttributeName extends AttributeName { final String completeNamespacedAttributeName; static XMLAttributeName forName(final String prefix, final String attributeName) {<FILL_FUNCTION_BODY>} private XMLAttributeName( final String prefix, final String attributeName, final String completeNamespacedAttributeName, final String[] completeAttributeNames) { super(prefix, attributeName, completeAttributeNames); this.completeNamespacedAttributeName = completeNamespacedAttributeName; } public String getCompleteNamespacedAttributeName() { return this.completeNamespacedAttributeName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; final String completeNamespacedAttributeName; final String[] completeAttributeNames; if (hasPrefix) { completeNamespacedAttributeName = prefix + ":" + attributeName; completeAttributeNames = new String[] { completeNamespacedAttributeName }; } else { completeNamespacedAttributeName = attributeName; completeAttributeNames = new String[] { attributeName }; } return new XMLAttributeName( prefix, attributeName, completeNamespacedAttributeName, completeAttributeNames);
175
157
332
<methods>public boolean equals(java.lang.Object) ,public java.lang.String getAttributeName() ,public java.lang.String[] getCompleteAttributeNames() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String attributeName,protected final non-sealed java.lang.String[] completeAttributeNames,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/XMLDeclaration.java
XMLDeclaration
computeXmlDeclaration
class XMLDeclaration extends AbstractTemplateEvent implements IXMLDeclaration, IEngineTemplateEvent { // XML Declaration nodes do not exist in text parsing, so we are safe expliciting markup structures here public static final String DEFAULT_KEYWORD = "xml"; public static final String DEFAULT_VERSION = "1.0"; public static final String ATTRIBUTE_NAME_VERSION = "version"; public static final String ATTRIBUTE_NAME_ENCODING = "encoding"; public static final String ATTRIBUTE_NAME_STANDALONE = "standalone"; private final String keyword; private final String version; private final String encoding; private final String standalone; private final String xmlDeclaration; XMLDeclaration(final String encoding) { this(DEFAULT_KEYWORD, DEFAULT_VERSION, encoding, null); } XMLDeclaration( final String keyword, final String version, final String encoding, final String standalone) { super(); this.keyword = keyword; this.version = version; this.encoding = encoding; this.standalone = standalone; this.xmlDeclaration = computeXmlDeclaration(); } XMLDeclaration( final String xmlDeclaration, final String keyword, final String version, final String encoding, final String standalone, final String templateName, final int line, final int col) { super(templateName, line, col); this.keyword = keyword; this.version = version; this.encoding = encoding; this.standalone = standalone; this.xmlDeclaration = (xmlDeclaration != null? xmlDeclaration : computeXmlDeclaration()); } public String getKeyword() { return this.keyword; } public String getVersion() { return this.version; } public String getEncoding() { return this.encoding; } public String getStandalone() { return this.standalone; } public String getXmlDeclaration() { return this.xmlDeclaration; } private String computeXmlDeclaration() {<FILL_FUNCTION_BODY>} public void accept(final IModelVisitor visitor) { visitor.visit(this); } public void write(final Writer writer) throws IOException { writer.write(this.xmlDeclaration); } static XMLDeclaration asEngineXMLDeclaration(final IXMLDeclaration xmlDeclaration) { if (xmlDeclaration instanceof XMLDeclaration) { return (XMLDeclaration) xmlDeclaration; } return new XMLDeclaration( null, xmlDeclaration.getKeyword(), xmlDeclaration.getVersion(), xmlDeclaration.getEncoding(), xmlDeclaration.getStandalone(), xmlDeclaration.getTemplateName(), xmlDeclaration.getLine(), xmlDeclaration.getCol()); } @Override public void beHandled(final ITemplateHandler handler) { handler.handleXMLDeclaration(this); } @Override public String toString() { return getXmlDeclaration(); } }
final StringBuilder strBuilder = new StringBuilder(40); strBuilder.append("<?"); strBuilder.append(this.keyword); if (this.version != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_VERSION); strBuilder.append("=\""); strBuilder.append(this.version); strBuilder.append('"'); } if (this.encoding != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_ENCODING); strBuilder.append("=\""); strBuilder.append(this.encoding); strBuilder.append('"'); } if (this.standalone != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_STANDALONE); strBuilder.append("=\""); strBuilder.append(this.standalone); strBuilder.append('"'); } strBuilder.append("?>"); return strBuilder.toString();
787
285
1,072
<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/XMLDeclarationStructureHandler.java
XMLDeclarationStructureHandler
replaceWith
class XMLDeclarationStructureHandler implements IXMLDeclarationStructureHandler { boolean setXMLDeclaration; String setXMLDeclarationKeyword; String setXMLDeclarationVersion; String setXMLDeclarationEncoding; String setXMLDeclarationStandalone; boolean replaceWithModel; IModel replaceWithModelValue; boolean replaceWithModelProcessable; boolean removeXMLDeclaration; XMLDeclarationStructureHandler() { super(); reset(); } public void setXMLDeclaration( final String keyword, final String version, final String encoding, final String standalone) { reset(); Validate.notNull(keyword, "Keyword cannot be null"); this.setXMLDeclaration = true; this.setXMLDeclarationKeyword = keyword; this.setXMLDeclarationVersion = version; this.setXMLDeclarationEncoding = encoding; this.setXMLDeclarationStandalone = standalone; } public void replaceWith(final IModel model, final boolean processable) {<FILL_FUNCTION_BODY>} public void removeXMLDeclaration() { reset(); this.removeXMLDeclaration = true; } public void reset() { this.setXMLDeclaration = false; this.setXMLDeclarationKeyword = null; this.setXMLDeclarationVersion = null; this.setXMLDeclarationEncoding = null; this.setXMLDeclarationStandalone = null; this.replaceWithModel = false; this.replaceWithModelValue = null; this.replaceWithModelProcessable = false; this.removeXMLDeclaration = false; } }
reset(); Validate.notNull(model, "Model cannot be null"); this.replaceWithModel = true; this.replaceWithModelValue = model; this.replaceWithModelProcessable = processable;
410
57
467
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/engine/XMLElementName.java
XMLElementName
forName
class XMLElementName extends ElementName { final String completeNamespacedElementName; static XMLElementName forName(final String prefix, final String elementName) {<FILL_FUNCTION_BODY>} private XMLElementName( final String prefix, final String elementName, final String completeNamespacedElementName, final String[] completeElementNames) { super(prefix, elementName, completeElementNames); this.completeNamespacedElementName = completeNamespacedElementName; } public String getCompleteNamespacedElementName() { return this.completeNamespacedElementName; } }
final boolean hasPrefix = prefix != null && prefix.length() > 0; final String completeNamespacedElementName; final String[] completeElementNames; if (hasPrefix) { completeNamespacedElementName = prefix + ":" + elementName; completeElementNames = new String[] { completeNamespacedElementName }; } else { completeNamespacedElementName = elementName; completeElementNames = new String[] { elementName }; } return new XMLElementName( prefix, elementName, completeNamespacedElementName, completeElementNames);
172
156
328
<methods>public boolean equals(java.lang.Object) ,public java.lang.String[] getCompleteElementNames() ,public java.lang.String getElementName() ,public java.lang.String getPrefix() ,public int hashCode() ,public boolean isPrefixed() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.String[] completeElementNames,protected final non-sealed java.lang.String elementName,private final non-sealed int h,protected final non-sealed java.lang.String prefix
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/exceptions/TemplateAssertionException.java
TemplateAssertionException
createMessage
class TemplateAssertionException extends RuntimeException { private static final long serialVersionUID = -2261382147273524844L; private static final String ASSERTION_MESSAGE = "Assertion '%s' not valid in template '%s'"; private static final String ASSERTION_MESSAGE_LINE_COL = "Assertion '%s' not valid in template '%s', line %d col %d"; public TemplateAssertionException(final String assertionExpression, final String templateName, final int line, final int col) { super(createMessage(assertionExpression, templateName, Integer.valueOf(line), Integer.valueOf(col))); } public TemplateAssertionException(final String assertionExpression, final String templateName) { super(createMessage(assertionExpression, templateName, null, null)); } private static String createMessage(final String assertionExpression, final String templateName, final Integer line, final Integer col) {<FILL_FUNCTION_BODY>} }
if (line == null || col == null) { return String.format(ASSERTION_MESSAGE, assertionExpression, templateName); } return String.format(ASSERTION_MESSAGE_LINE_COL, assertionExpression, templateName, line, col);
261
69
330
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/Bools.java
Bools
arrayAnd
class Bools { public Bools() { super(); } public Boolean isTrue(final Object target) { return Boolean.valueOf(EvaluationUtils.evaluateAsBoolean(target)); } public Boolean[] arrayIsTrue(final Object[] target) { Validate.notNull(target, "Target cannot be null"); final Boolean[] result = new Boolean[target.length]; for (int i = 0; i < target.length; i++) { result[i] = isTrue(target[i]); } return result; } public List<Boolean> listIsTrue(final List<?> target) { Validate.notNull(target, "Target cannot be null"); final List<Boolean> result = new ArrayList<Boolean>(target.size() + 2); for (final Object element : target) { result.add(isTrue(element)); } return result; } public Set<Boolean> setIsTrue(final Set<?> target) { Validate.notNull(target, "Target cannot be null"); final Set<Boolean> result = new LinkedHashSet<Boolean>(target.size() + 2); for (final Object element : target) { result.add(isTrue(element)); } return result; } public Boolean isFalse(final Object target) { return Boolean.valueOf(!EvaluationUtils.evaluateAsBoolean(target)); } public Boolean[] arrayIsFalse(final Object[] target) { Validate.notNull(target, "Target cannot be null"); final Boolean[] result = new Boolean[target.length]; for (int i = 0; i < target.length; i++) { result[i] = isFalse(target[i]); } return result; } public List<Boolean> listIsFalse(final List<?> target) { Validate.notNull(target, "Target cannot be null"); final List<Boolean> result = new ArrayList<Boolean>(target.size() + 2); for (final Object element : target) { result.add(isFalse(element)); } return result; } public Set<Boolean> setIsFalse(final Set<?> target) { Validate.notNull(target, "Target cannot be null"); final Set<Boolean> result = new LinkedHashSet<Boolean>(target.size() + 2); for (final Object element : target) { result.add(isFalse(element)); } return result; } public Boolean arrayAnd(final Object[] target) {<FILL_FUNCTION_BODY>} public Boolean listAnd(final List<?> target) { Validate.notNull(target, "Target cannot be null"); for (final Object element : target) { if (!isTrue(element).booleanValue()) { return Boolean.FALSE; } } return Boolean.TRUE; } public Boolean setAnd(final Set<?> target) { Validate.notNull(target, "Target cannot be null"); for (final Object element : target) { if (!isTrue(element).booleanValue()) { return Boolean.FALSE; } } return Boolean.TRUE; } public Boolean arrayOr(final Object[] target) { Validate.notNull(target, "Target cannot be null"); for (final Object aTarget : target) { if (isTrue(aTarget).booleanValue()) { return Boolean.TRUE; } } return Boolean.FALSE; } public Boolean listOr(final List<?> target) { Validate.notNull(target, "Target cannot be null"); for (final Object element : target) { if (isTrue(element).booleanValue()) { return Boolean.TRUE; } } return Boolean.FALSE; } public Boolean setOr(final Set<?> target) { Validate.notNull(target, "Target cannot be null"); for (final Object element : target) { if (isTrue(element).booleanValue()) { return Boolean.TRUE; } } return Boolean.FALSE; } }
Validate.notNull(target, "Target cannot be null"); for (final Object aTarget : target) { if (!isTrue(aTarget).booleanValue()) { return Boolean.FALSE; } } return Boolean.TRUE;
1,105
65
1,170
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/Conversions.java
Conversions
convert
class Conversions { private final IExpressionContext context; public Conversions(final IExpressionContext context) { super(); Validate.notNull(context, "Context cannot be null"); this.context = context; } public Object convert(final Object target, final String className) {<FILL_FUNCTION_BODY>} public Object convert(final Object target, final Class<?> clazz) { final IStandardConversionService conversionService = StandardExpressions.getConversionService(this.context.getConfiguration()); return conversionService.convert(this.context, target, clazz); } }
try { final Class<?> clazz = ClassLoaderUtils.loadClass(className); return convert(target, clazz); } catch (final ClassNotFoundException e) { try { final Class<?> clazz = ClassLoaderUtils.loadClass("java.lang." + className); return convert(target, clazz); } catch (final ClassNotFoundException ex) { throw new IllegalArgumentException("Cannot convert to class '" + className + "'", e); } }
168
125
293
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/ExecutionInfo.java
ExecutionInfo
getTemplateModes
class ExecutionInfo { private final ITemplateContext context; private final Calendar now; public ExecutionInfo(final ITemplateContext context) { super(); this.context = context; this.now = Calendar.getInstance(context.getLocale()); } /** * <p> * Returns the template name (of the leaf template). * </p> * <p> * Note that the template name returned here corresponds with origin of the elements or nodes being * currently processed. This is, if a processor is being executed for an element inserted from an external * template (via a {@code th:insert}, for example), then this method will return the template mode * for the template in which the inserted fragment lives, not the one it was inserted into. * </p> * * @return the template name */ public String getTemplateName() { return this.context.getTemplateData().getTemplate(); } /** * <p> * Returns the template mode ({@link TemplateMode}) (of the leaf template). * </p> * <p> * Note that the {@link TemplateMode} returned here corresponds with origin of the elements or nodes being * currently processed. This is, if a processor is being executed for an element inserted from an external * template (via a {@code th:insert}, for example), then this method will return the template mode * for the template in which the inserted fragment lives, not the one it was inserted into. * </p> * * @return the template mode */ public TemplateMode getTemplateMode() { return this.context.getTemplateData().getTemplateMode(); } /** * <p> * Returns the template name of the first-level template. * </p> * <p> * Note this template name refers to the first-level one, the one used to call the TemplateEngine itself, even * if by the moment this method is called the engine is processing a fragment inserted from the first-level * template (or at any other level in the hierarchy). * </p> * * @return the template name */ public String getProcessedTemplateName() { return this.context.getTemplateStack().get(0).getTemplate(); } /** * <p> * Returns the template mode ({@link TemplateMode}) of the first-level template. * </p> * <p> * Note this template mode refers to the first-level one, the one used to call the TemplateEngine itself, even * if by the moment this method is called the engine is processing a fragment inserted from the first-level * template (or at any other level in the hierarchy). * </p> * * @return the template mode */ public TemplateMode getProcessedTemplateMode() { return this.context.getTemplateStack().get(0).getTemplateMode(); } /** * <p> * Returns the names of all the stack of templates appliable to the current point * of execution. This will depend on which templates are inserted inside wich. * </p> * <p> * The first-level template will appear first, and the most specific template will appear last. * </p> * * @return the stack of template names */ public List<String> getTemplateNames() { final List<TemplateData> templateStack = this.context.getTemplateStack(); final List<String> templateNameStack = new ArrayList<String>(templateStack.size()); for (final TemplateData templateData : templateStack) { templateNameStack.add(templateData.getTemplate()); } return templateNameStack; } /** * <p> * Returns the {@link TemplateMode}s of all the stack of templates appliable to the current point * of execution. This will depend on which templates are inserted inside wich. * </p> * <p> * The first-level template will appear first, and the most specific template will appear last. * </p> * * @return the stack of template modes */ public List<TemplateMode> getTemplateModes() {<FILL_FUNCTION_BODY>} /** * <p> * Returns the <em>template stack</em>, containing the metadata for the first-level template being * processed and also any fragments that might have been nested up to the current execution point. * </p> * <p> * The result of this method actually corresponds to the result of {@link ITemplateContext#getTemplateStack()}. * </p> * * @return the stack of {@link TemplateData} objects */ public List<TemplateData> getTemplateStack() { return this.context.getTemplateStack(); } /** * <p> * Returns the current date and time (from the moment of template execution). * </p> * * @return the current date and time, as a Calendar */ public Calendar getNow() { return this.now; } }
final List<TemplateData> templateStack = this.context.getTemplateStack(); final List<TemplateMode> templateModeStack = new ArrayList<TemplateMode>(templateStack.size()); for (final TemplateData templateData : templateStack) { templateModeStack.add(templateData.getTemplateMode()); } return templateModeStack;
1,326
85
1,411
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/ExpressionObjects.java
ExpressionObjects
getObject
class ExpressionObjects implements IExpressionObjects { /* * Making room for 3 expression objects should be enough for most cases, given these maps will be * created for each IProcessingContext (i.e. for each template processing request) */ private static final int EXPRESSION_OBJECT_MAP_DEFAULT_SIZE = 3; private final IExpressionContext context; private final IExpressionObjectFactory expressionObjectFactory; private final Set<String> expressionObjectNames; private Map<String,Object> objects; public ExpressionObjects( final IExpressionContext context, final IExpressionObjectFactory expressionObjectFactory) { super(); Validate.notNull(context, "Context cannot be null"); Validate.notNull(expressionObjectFactory, "Expression Object Factory cannot be null"); this.context = context; this.expressionObjectFactory = expressionObjectFactory; this.expressionObjectNames = this.expressionObjectFactory.getAllExpressionObjectNames(); } public int size() { return this.expressionObjectNames.size(); } public boolean containsObject(final String name) { return this.expressionObjectNames.contains(name); } public Set<String> getObjectNames() { return this.expressionObjectNames; } public Object getObject(final String name) {<FILL_FUNCTION_BODY>} }
/* * First, a quick attempt to resolve from the object cache */ if (this.objects != null && this.objects.containsKey(name)) { return this.objects.get(name); } /* * If the object is not provided by the factory, simply return null */ if (!this.expressionObjectNames.contains(name)) { return null; } /* * Have the factory build the object */ final Object object = this.expressionObjectFactory.buildObject(this.context, name); /* * If the object is not cacheable, we will just return it */ if (!this.expressionObjectFactory.isCacheable(name)) { return object; } /* * The object is cacheable, so we will need to use the objects map in order to perform such caching, and * first of all we must ensure it (the cache) exists */ if (this.objects == null) { this.objects = new HashMap<String, Object>(EXPRESSION_OBJECT_MAP_DEFAULT_SIZE); } /* * Put into cache and return */ this.objects.put(name, object); return object;
355
314
669
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/Ids.java
Ids
seq
class Ids { private final ITemplateContext context; public String seq(final Object id) {<FILL_FUNCTION_BODY>} public String next(final Object id) { Validate.notNull(id, "ID cannot be null"); final String str = id.toString(); return str + this.context.getIdentifierSequences().getNextIDSeq(str); } public String prev(final Object id) { Validate.notNull(id, "ID cannot be null"); final String str = id.toString(); return str + this.context.getIdentifierSequences().getPreviousIDSeq(str); } public Ids(final ITemplateContext context) { super(); Validate.notNull(context, "Context cannot be null"); this.context = context; } }
Validate.notNull(id, "ID cannot be null"); final String str = id.toString(); return str + this.context.getIdentifierSequences().getAndIncrementIDSeq(str);
226
54
280
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/expression/Objects.java
Objects
setNullSafe
class Objects { public <T> T nullSafe(final T target, final T defaultValue) { return ObjectUtils.nullSafe(target, defaultValue); } public <T> T[] arrayNullSafe(final T[] target, final T defaultValue) { Validate.notNull(target, "Target cannot be null"); final T[] result = target.clone(); for (int i = 0; i < target.length; i++) { result[i] = nullSafe(target[i], defaultValue); } return result; } public <T> List<T> listNullSafe(final List<T> target, final T defaultValue) { Validate.notNull(target, "Target cannot be null"); final List<T> result = new ArrayList<T>(target.size() + 2); for (final T element : target) { result.add(nullSafe(element, defaultValue)); } return result; } public <T> Set<T> setNullSafe(final Set<T> target, final T defaultValue) {<FILL_FUNCTION_BODY>} public Objects() { super(); } }
Validate.notNull(target, "Target cannot be null"); final Set<T> result = new LinkedHashSet<T>(target.size() + 2); for (final T element : target) { result.add(nullSafe(element, defaultValue)); } return result;
311
76
387
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/inline/NoOpInliner.java
NoOpInliner
inline
class NoOpInliner implements IInliner { public static final NoOpInliner INSTANCE = new NoOpInliner(); private NoOpInliner() { super(); } public String getName() { return "NOOP"; } public CharSequence inline(final ITemplateContext context, final IText text) { // Nothing to do. Anyway, this should never end up being executed... return null; } public CharSequence inline(final ITemplateContext context, final ICDATASection cdataSection) { // Nothing to do. Anyway, this should never end up being executed... return null; } public CharSequence inline(final ITemplateContext context, final IComment comment) {<FILL_FUNCTION_BODY>} }
// Nothing to do. Anyway, this should never end up being executed... return null;
206
26
232
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/model/AbstractModelVisitor.java
AbstractModelVisitor
visit
class AbstractModelVisitor implements IModelVisitor { public void visit(final ITemplateStart templateStart) { // Nothing to be done here - just an empty default implementation } public void visit(final ITemplateEnd templateEnd) { // Nothing to be done here - just an empty default implementation } public void visit(final IXMLDeclaration xmlDeclaration) { // Nothing to be done here - just an empty default implementation } public void visit(final IDocType docType) { // Nothing to be done here - just an empty default implementation } public void visit(final ICDATASection cdataSection) { // Nothing to be done here - just an empty default implementation } public void visit(final IComment comment) { // Nothing to be done here - just an empty default implementation } public void visit(final IText text) { // Nothing to be done here - just an empty default implementation } public void visit(final IStandaloneElementTag standaloneElementTag) { // Nothing to be done here - just an empty default implementation } public void visit(final IOpenElementTag openElementTag) {<FILL_FUNCTION_BODY>} public void visit(final ICloseElementTag closeElementTag) { // Nothing to be done here - just an empty default implementation } public void visit(final IProcessingInstruction processingInstruction) { // Nothing to be done here - just an empty default implementation } }
// Nothing to be done here - just an empty default implementation
377
17
394
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/cdatasection/AbstractCDATASectionProcessor.java
AbstractCDATASectionProcessor
process
class AbstractCDATASectionProcessor extends AbstractProcessor implements ICDATASectionProcessor { public AbstractCDATASectionProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final ICDATASection cdataSection, final ICDATASectionStructureHandler structureHandler); }
try { doProcess(context, cdataSection, structureHandler); } catch (final TemplateProcessingException e) { if (cdataSection.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(cdataSection.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(cdataSection.getLine(), cdataSection.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", cdataSection.getTemplateName(), cdataSection.getLine(), cdataSection.getCol(), e); }
159
194
353
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/comment/AbstractCommentProcessor.java
AbstractCommentProcessor
process
class AbstractCommentProcessor extends AbstractProcessor implements ICommentProcessor { public AbstractCommentProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IComment comment, final ICommentStructureHandler structureHandler); }
try { doProcess(context, comment, structureHandler); } catch (final TemplateProcessingException e) { if (comment.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(comment.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(comment.getLine(), comment.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", comment.getTemplateName(), comment.getLine(), comment.getCol(), e); }
134
178
312
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/doctype/AbstractDocTypeProcessor.java
AbstractDocTypeProcessor
process
class AbstractDocTypeProcessor extends AbstractProcessor implements IDocTypeProcessor { public AbstractDocTypeProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final IDocType docType, final IDocTypeStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IDocType docType, final IDocTypeStructureHandler structureHandler); }
try { doProcess(context, docType, structureHandler); } catch (final TemplateProcessingException e) { if (docType.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(docType.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(docType.getLine(), docType.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", docType.getTemplateName(), docType.getLine(), docType.getCol(), e); }
143
186
329
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/AbstractAttributeModelProcessor.java
AbstractAttributeModelProcessor
doProcess
class AbstractAttributeModelProcessor extends AbstractElementModelProcessor { private final boolean removeAttribute; protected AbstractAttributeModelProcessor( final TemplateMode templateMode, final String dialectPrefix, final String elementName, final boolean prefixElementName, final String attributeName, final boolean prefixAttributeName, final int precedence, final boolean removeAttribute) { super(templateMode, dialectPrefix, elementName, prefixElementName, attributeName, prefixAttributeName, precedence); this.removeAttribute = removeAttribute; } @Override protected final void doProcess( final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IModel model, final AttributeName attributeName, final String attributeValue, final IElementModelStructureHandler structureHandler); private static int locateFirstEventInModel(final IModel model, final ITemplateEvent firstEvent) { final int modelSize = model.size(); // First we will try to locate the exact same event in the model for (int i = 0; i < modelSize; i++) { // We can (should, actually) use reference equality here if (firstEvent == model.get(i)) { return i; } } // We weren't able to locate the exact same event, so we will just consider the first one, if it can contain attrs if (modelSize > 0 && model.get(0) instanceof IProcessableElementTag) { return 0; } return -1; } }
AttributeName attributeName = null; IProcessableElementTag firstEvent = null; try { attributeName = getMatchingAttributeName().getMatchingAttributeName(); firstEvent = (IProcessableElementTag) model.get(0); final String attributeValue = EscapedAttributeUtils.unescapeAttribute(context.getTemplateMode(), firstEvent.getAttributeValue(attributeName)); doProcess(context, model, attributeName, attributeValue, structureHandler); if (this.removeAttribute) { final int firstEventLocation = locateFirstEventInModel(model, firstEvent); if (firstEventLocation >= 0) { firstEvent = (IProcessableElementTag) model.get(firstEventLocation); final IModelFactory modelFactory = context.getModelFactory(); final IProcessableElementTag newFirstEvent = modelFactory.removeAttribute(firstEvent,attributeName); if (newFirstEvent != firstEvent) { model.replace(firstEventLocation, newFirstEvent); } } } } catch (final TemplateProcessingException e) { // We will try to add all information possible to the exception report (template name, line, col) if (firstEvent != null) { String attributeTemplateName = firstEvent.getTemplateName(); final IAttribute attribute = firstEvent.getAttribute(attributeName); int attributeLine = (attribute != null? attribute.getLine() : -1); int attributeCol = (attribute != null? attribute.getCol() : -1); if (attributeTemplateName != null) { if (!e.hasTemplateName()) { e.setTemplateName(attributeTemplateName); } } if (attributeLine != -1 && attributeCol != -1) { if (!e.hasLineAndCol()) { e.setLineAndCol(attributeLine, attributeCol); } } } throw e; } catch (final Exception e) { // We will try to add all information possible to the exception report (template name, line, col) String attributeTemplateName = null; int attributeLine = -1; int attributeCol = -1; if (firstEvent != null) { attributeTemplateName = firstEvent.getTemplateName(); final IAttribute attribute = firstEvent.getAttribute(attributeName); attributeLine = (attribute != null? attribute.getLine() : -1); attributeCol = (attribute != null? attribute.getCol() : -1); } throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", attributeTemplateName, attributeLine, attributeCol, e); }
418
678
1,096
<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.IModel, org.thymeleaf.processor.element.IElementModelStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/AbstractAttributeTagProcessor.java
AbstractAttributeTagProcessor
doProcess
class AbstractAttributeTagProcessor extends AbstractElementTagProcessor { private final boolean removeAttribute; protected AbstractAttributeTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String elementName, final boolean prefixElementName, final String attributeName, final boolean prefixAttributeName, final int precedence, final boolean removeAttribute) { super(templateMode, dialectPrefix, elementName, prefixElementName, attributeName, prefixAttributeName, precedence); Validate.notEmpty(attributeName, "Attribute name cannot be null or empty in Attribute Tag Processor"); this.removeAttribute = removeAttribute; } @Override protected final void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler); }
AttributeName attributeName = null; try { attributeName = getMatchingAttributeName().getMatchingAttributeName(); final String attributeValue = EscapedAttributeUtils.unescapeAttribute(context.getTemplateMode(), tag.getAttributeValue(attributeName)); doProcess( context, tag, attributeName, attributeValue, structureHandler); if (this.removeAttribute) { structureHandler.removeAttribute(attributeName); } } catch (final TemplateProcessingException e) { // This is a nice moment to check whether the execution raised an error and, if so, add location information // Note this is similar to what is done at the superclass AbstractElementTagProcessor, but we can be more // specific because we know exactly what attribute was being executed and caused the error if (tag.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(tag.getTemplateName()); } if (!e.hasLineAndCol()) { if (attributeName == null) { // We don't have info about the specific attribute provoking the error e.setLineAndCol(tag.getLine(), tag.getCol()); } else { final IAttribute attribute = tag.getAttribute(attributeName); if (attribute != null) { e.setLineAndCol(attribute.getLine(), attribute.getCol()); } } } } throw e; } catch (final Exception e) { int line = tag.getLine(); int col = tag.getCol(); if (attributeName != null) { // We don't have info about the specific attribute provoking the error final IAttribute attribute = tag.getAttribute(attributeName); if (attribute != null) { line = attribute.getLine(); col = attribute.getCol(); } } throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", tag.getTemplateName(), line, col, e); }
269
516
785
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/AbstractElementModelProcessor.java
AbstractElementModelProcessor
process
class AbstractElementModelProcessor extends AbstractProcessor implements IElementModelProcessor { private final String dialectPrefix; private final MatchingElementName matchingElementName; private final MatchingAttributeName matchingAttributeName; public AbstractElementModelProcessor( final TemplateMode templateMode, final String dialectPrefix, final String elementName, final boolean prefixElementName, final String attributeName, final boolean prefixAttributeName, final int precedence) { super(templateMode, precedence); this.dialectPrefix = dialectPrefix; this.matchingElementName = (elementName == null? null : MatchingElementName.forElementName( templateMode, ElementNames.forName(templateMode, (prefixElementName? this.dialectPrefix : null), elementName))); this.matchingAttributeName = (attributeName == null? null : MatchingAttributeName.forAttributeName( templateMode, AttributeNames.forName(templateMode, (prefixAttributeName? this.dialectPrefix : null), attributeName))); } protected final String getDialectPrefix() { return this.dialectPrefix; } public final MatchingElementName getMatchingElementName() { return this.matchingElementName; } public final MatchingAttributeName getMatchingAttributeName() { return this.matchingAttributeName; } public final void process( final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler); }
ITemplateEvent firstEvent = null; try { firstEvent = model.get(0); doProcess(context, model, structureHandler); } catch (final TemplateProcessingException e) { // We will try to add all information possible to the exception report (template name, line, col) if (firstEvent != null) { String modelTemplateName = firstEvent.getTemplateName(); int modelLine = firstEvent.getLine(); int modelCol = firstEvent.getCol(); if (modelTemplateName != null) { if (!e.hasTemplateName()) { e.setTemplateName(modelTemplateName); } } if (modelLine != -1 && modelCol != -1) { if (!e.hasLineAndCol()) { e.setLineAndCol(modelLine, modelCol); } } } throw e; } catch (final Exception e) { // We will try to add all information possible to the exception report (template name, line, col) String modelTemplateName = null; int modelLine = -1; int modelCol = -1; if (firstEvent != null) { modelTemplateName = firstEvent.getTemplateName(); modelLine = firstEvent.getLine(); modelCol = firstEvent.getCol(); } throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", modelTemplateName, modelLine, modelCol, e); }
437
397
834
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/AbstractElementTagProcessor.java
AbstractElementTagProcessor
process
class AbstractElementTagProcessor extends AbstractProcessor implements IElementTagProcessor { private final String dialectPrefix; private final MatchingElementName matchingElementName; private final MatchingAttributeName matchingAttributeName; public AbstractElementTagProcessor( final TemplateMode templateMode, final String dialectPrefix, final String elementName, final boolean prefixElementName, final String attributeName, final boolean prefixAttributeName, final int precedence) { super(templateMode, precedence); this.dialectPrefix = dialectPrefix; this.matchingElementName = (elementName == null? null : MatchingElementName.forElementName( templateMode, ElementNames.forName(templateMode, (prefixElementName? this.dialectPrefix : null), elementName))); this.matchingAttributeName = (attributeName == null? null : MatchingAttributeName.forAttributeName( templateMode, AttributeNames.forName(templateMode, (prefixAttributeName? this.dialectPrefix : null), attributeName))); } protected final String getDialectPrefix() { return this.dialectPrefix; } public final MatchingElementName getMatchingElementName() { return this.matchingElementName; } public final MatchingAttributeName getMatchingAttributeName() { return this.matchingAttributeName; } public final void process( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler); }
try { doProcess(context, tag, structureHandler); } catch (final TemplateProcessingException e) { // This is a nice moment to check whether the execution raised an error and, if so, add location information if (tag.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(tag.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(tag.getLine(), tag.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", tag.getTemplateName(), tag.getLine(), tag.getCol(), e); }
448
202
650
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/MatchingAttributeName.java
MatchingAttributeName
forAllAttributesWithPrefix
class MatchingAttributeName { private final TemplateMode templateMode; private final AttributeName matchingAttributeName; private final String matchingAllAttributesWithPrefix; private final boolean matchingAllAttributes; public static MatchingAttributeName forAttributeName(final TemplateMode templateMode, final AttributeName matchingAttributeName) { Validate.notNull(templateMode, "Template mode cannot be null"); Validate.notNull(matchingAttributeName, "Matching attribute name cannot be null"); if (templateMode == TemplateMode.HTML && !(matchingAttributeName instanceof HTMLAttributeName)) { throw new IllegalArgumentException("Attribute names for HTML template mode must be of class " + HTMLAttributeName.class.getName()); } else if (templateMode == TemplateMode.XML && !(matchingAttributeName instanceof XMLAttributeName)) { throw new IllegalArgumentException("Attribute names for XML template mode must be of class " + XMLAttributeName.class.getName()); } else if (templateMode.isText() && !(matchingAttributeName instanceof TextAttributeName)) { throw new IllegalArgumentException("Attribute names for any text template modes must be of class " + TextAttributeName.class.getName()); } return new MatchingAttributeName(templateMode, matchingAttributeName, null, false); } public static MatchingAttributeName forAllAttributesWithPrefix(final TemplateMode templateMode, final String matchingAllAttributesWithPrefix) {<FILL_FUNCTION_BODY>} public static MatchingAttributeName forAllAttributes(final TemplateMode templateMode) { Validate.notNull(templateMode, "Template mode cannot be null"); return new MatchingAttributeName(templateMode, null, null, true); } private MatchingAttributeName( final TemplateMode templateMode, final AttributeName matchingAttributeName, final String matchingAllAttributesWithPrefix, final boolean matchingAllAttributes) { super(); this.templateMode = templateMode; this.matchingAttributeName = matchingAttributeName; this.matchingAllAttributesWithPrefix = matchingAllAttributesWithPrefix; this.matchingAllAttributes = matchingAllAttributes; } public TemplateMode getTemplateMode() { return this.templateMode; } public AttributeName getMatchingAttributeName() { return this.matchingAttributeName; } public String getMatchingAllAttributesWithPrefix() { return this.matchingAllAttributesWithPrefix; } public boolean isMatchingAllAttributes() { return this.matchingAllAttributes; } public boolean matches(final AttributeName attributeName) { Validate.notNull(attributeName, "Attributes name cannot be null"); if (this.matchingAttributeName == null) { if (this.templateMode == TemplateMode.HTML && !(attributeName instanceof HTMLAttributeName)) { return false; } else if (this.templateMode == TemplateMode.XML && !(attributeName instanceof XMLAttributeName)) { return false; } else if (this.templateMode.isText() && !(attributeName instanceof TextAttributeName)) { return false; } if (this.matchingAllAttributes) { return true; } if (this.matchingAllAttributesWithPrefix == null) { return attributeName.getPrefix() == null; } final String attributeNamePrefix = attributeName.getPrefix(); if (attributeNamePrefix == null) { return false; // we already checked we are not matching nulls } return TextUtils.equals(this.templateMode.isCaseSensitive(), this.matchingAllAttributesWithPrefix, attributeNamePrefix); } return this.matchingAttributeName.equals(attributeName); } @Override public String toString() { if (this.matchingAttributeName == null) { if (this.matchingAllAttributes) { return "*"; } if (this.matchingAllAttributesWithPrefix == null) { return "[^:]*"; } return this.matchingAllAttributesWithPrefix + ":*"; } return matchingAttributeName.toString(); } }
Validate.notNull(templateMode, "Template mode cannot be null"); // Prefix can actually be null -> match all attributes with no prefix return new MatchingAttributeName(templateMode, null, matchingAllAttributesWithPrefix, false);
1,046
60
1,106
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/MatchingElementName.java
MatchingElementName
forElementName
class MatchingElementName { private final TemplateMode templateMode; private final ElementName matchingElementName; private final String matchingAllElementsWithPrefix; private final boolean matchingAllElements; public static MatchingElementName forElementName(final TemplateMode templateMode, final ElementName matchingElementName) {<FILL_FUNCTION_BODY>} public static MatchingElementName forAllElementsWithPrefix(final TemplateMode templateMode, final String matchingAllElementsWithPrefix) { Validate.notNull(templateMode, "Template mode cannot be null"); // Prefix can actually be null -> match all elements with no prefix return new MatchingElementName(templateMode, null, matchingAllElementsWithPrefix, false); } public static MatchingElementName forAllElements(final TemplateMode templateMode) { Validate.notNull(templateMode, "Template mode cannot be null"); return new MatchingElementName(templateMode, null, null, true); } private MatchingElementName( final TemplateMode templateMode, final ElementName matchingElementName, final String matchingAllElementsWithPrefix, final boolean matchingAllElements) { super(); this.templateMode = templateMode; this.matchingElementName = matchingElementName; this.matchingAllElementsWithPrefix = matchingAllElementsWithPrefix; this.matchingAllElements = matchingAllElements; } public TemplateMode getTemplateMode() { return this.templateMode; } public ElementName getMatchingElementName() { return this.matchingElementName; } public String getMatchingAllElementsWithPrefix() { return this.matchingAllElementsWithPrefix; } public boolean isMatchingAllElements() { return this.matchingAllElements; } public boolean matches(final ElementName elementName) { Validate.notNull(elementName, "Element name cannot be null"); if (this.matchingElementName == null) { if (this.templateMode == TemplateMode.HTML && !(elementName instanceof HTMLElementName)) { return false; } else if (this.templateMode == TemplateMode.XML && !(elementName instanceof XMLElementName)) { return false; } else if (this.templateMode.isText() && !(elementName instanceof TextElementName)) { return false; } if (this.matchingAllElements) { return true; } if (this.matchingAllElementsWithPrefix == null) { return elementName.getPrefix() == null; } final String elementNamePrefix = elementName.getPrefix(); if (elementNamePrefix == null) { return false; // we already checked we are not matching nulls } return TextUtils.equals(this.templateMode.isCaseSensitive(), this.matchingAllElementsWithPrefix, elementNamePrefix); } return this.matchingElementName.equals(elementName); } @Override public String toString() { if (this.matchingElementName == null) { if (this.matchingAllElements) { return "*"; } if (this.matchingAllElementsWithPrefix == null) { return "[^:]*"; } return this.matchingAllElementsWithPrefix + ":*"; } return matchingElementName.toString(); } }
Validate.notNull(templateMode, "Template mode cannot be null"); Validate.notNull(matchingElementName, "Matching element name cannot be null"); if (templateMode == TemplateMode.HTML && !(matchingElementName instanceof HTMLElementName)) { throw new IllegalArgumentException("Element names for HTML template mode must be of class " + HTMLElementName.class.getName()); } else if (templateMode == TemplateMode.XML && !(matchingElementName instanceof XMLElementName)) { throw new IllegalArgumentException("Element names for XML template mode must be of class " + XMLElementName.class.getName()); } else if (templateMode.isText() && !(matchingElementName instanceof TextElementName)) { throw new IllegalArgumentException("Element names for any text template modes must be of class " + TextElementName.class.getName()); } return new MatchingElementName(templateMode, matchingElementName, null, false);
864
231
1,095
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/processinginstruction/AbstractProcessingInstructionProcessor.java
AbstractProcessingInstructionProcessor
process
class AbstractProcessingInstructionProcessor extends AbstractProcessor implements IProcessingInstructionProcessor { public AbstractProcessingInstructionProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final IProcessingInstruction processingInstruction, final IProcessingInstructionStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IProcessingInstruction processingInstruction, final IProcessingInstructionStructureHandler structureHandler); }
try { doProcess(context, processingInstruction, structureHandler); } catch (final TemplateProcessingException e) { if (processingInstruction.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(processingInstruction.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(processingInstruction.getLine(), processingInstruction.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", processingInstruction.getTemplateName(), processingInstruction.getLine(), processingInstruction.getCol(), e); }
158
194
352
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/templateboundaries/AbstractTemplateBoundariesProcessor.java
AbstractTemplateBoundariesProcessor
processTemplateEnd
class AbstractTemplateBoundariesProcessor extends AbstractProcessor implements ITemplateBoundariesProcessor { public AbstractTemplateBoundariesProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void processTemplateStart( final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler) { try { doProcessTemplateStart(context, templateStart, structureHandler); } catch (final TemplateProcessingException e) { if (templateStart.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(templateStart.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(templateStart.getLine(), templateStart.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", templateStart.getTemplateName(), templateStart.getLine(), templateStart.getCol(), e); } } public final void processTemplateEnd( final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} public abstract void doProcessTemplateStart( final ITemplateContext context, final ITemplateStart templateStart, final ITemplateBoundariesStructureHandler structureHandler); public abstract void doProcessTemplateEnd( final ITemplateContext context, final ITemplateEnd templateEnd, final ITemplateBoundariesStructureHandler structureHandler); }
try { doProcessTemplateEnd(context, templateEnd, structureHandler); } catch (final TemplateProcessingException e) { if (templateEnd.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(templateEnd.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(templateEnd.getLine(), templateEnd.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", templateEnd.getTemplateName(), templateEnd.getLine(), templateEnd.getCol(), e); }
435
188
623
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/text/AbstractTextProcessor.java
AbstractTextProcessor
process
class AbstractTextProcessor extends AbstractProcessor implements ITextProcessor { public AbstractTextProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IText text, final ITextStructureHandler structureHandler); }
try { doProcess(context, text, structureHandler); } catch (final TemplateProcessingException e) { if (text.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(text.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(text.getLine(), text.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", text.getTemplateName(), text.getLine(), text.getCol(), e); }
134
178
312
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/xmldeclaration/AbstractXMLDeclarationProcessor.java
AbstractXMLDeclarationProcessor
process
class AbstractXMLDeclarationProcessor extends AbstractProcessor implements IXMLDeclarationProcessor { public AbstractXMLDeclarationProcessor(final TemplateMode templateMode, final int precedence) { super(templateMode, precedence); } public final void process( final ITemplateContext context, final IXMLDeclaration xmlDeclaration, final IXMLDeclarationStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IXMLDeclaration xmlDeclaration, final IXMLDeclarationStructureHandler structureHandler); }
try { doProcess(context, xmlDeclaration, structureHandler); } catch (final TemplateProcessingException e) { if (xmlDeclaration.hasLocation()) { if (!e.hasTemplateName()) { e.setTemplateName(xmlDeclaration.getTemplateName()); } if (!e.hasLineAndCol()) { e.setLineAndCol(xmlDeclaration.getLine(), xmlDeclaration.getCol()); } } throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", xmlDeclaration.getTemplateName(), xmlDeclaration.getLine(), xmlDeclaration.getCol(), e); }
143
186
329
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, int) ,public final int getPrecedence() ,public final org.thymeleaf.templatemode.TemplateMode getTemplateMode() <variables>private final non-sealed int precedence,private final non-sealed org.thymeleaf.templatemode.TemplateMode templateMode
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AbstractStandardConversionService.java
AbstractStandardConversionService
convert
class AbstractStandardConversionService implements IStandardConversionService { protected AbstractStandardConversionService() { super(); } public final <T> T convert( final IExpressionContext context, final Object object, final Class<T> targetClass) {<FILL_FUNCTION_BODY>} protected String convertToString( final IExpressionContext context, final Object object) { if (object == null) { return null; } return object.toString(); } protected <T> T convertOther( final IExpressionContext context, final Object object, final Class<T> targetClass) { throw new IllegalArgumentException("No available conversion for target class \"" + targetClass.getName() + "\""); } }
Validate.notNull(targetClass, "Target class cannot be null"); /* * CONVERSIONS TO String (will be 99% of executions) */ if (targetClass.equals(String.class)) { if (object == null || object instanceof String) { return (T) object; } return (T) convertToString(context, object); } /* * OTHER CONVERSIONS */ return convertOther(context, object, targetClass);
204
131
335
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AdditionExpression.java
AdditionExpression
executeAddition
class AdditionExpression extends AdditionSubtractionExpression { private static final long serialVersionUID = -971366486450425605L; private static final Logger logger = LoggerFactory.getLogger(AdditionExpression.class); public AdditionExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(ADDITION_OPERATOR); } static Object executeAddition( final IExpressionContext context, final AdditionExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating addition expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final IStandardVariableExpressionEvaluator expressionEvaluator = StandardExpressions.getVariableExpressionEvaluator(context.getConfiguration()); final IStandardExpression leftExpr = expression.getLeft(); final IStandardExpression rightExpr = expression.getRight(); // We try use the Expression.execute methods directly if possible, because we cannot allow the results // to be literal-unwrapped (if literal unwrap takes place, '.' + 3 + 2 = 2.3 instead of '.32' as it should be). // Note this is only needed in AdditionExpression, because '+' is the only overloaded operator Object leftValue; if (leftExpr instanceof Expression) { // This avoids literal-unwrap leftValue = Expression.execute(context, (Expression)leftExpr, expressionEvaluator, expContext); } else{ leftValue = leftExpr.execute(context, expContext); } Object rightValue; if (rightExpr instanceof Expression) { // This avoids literal-unwrap rightValue = Expression.execute(context, (Expression)rightExpr, expressionEvaluator, expContext); } else{ rightValue = rightExpr.execute(context, expContext); } if (leftValue == null) { leftValue = "null"; } if (rightValue == null) { rightValue = "null"; } final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); if (leftNumberValue != null) { final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (rightNumberValue != null) { // Addition will act as a mathematical 'plus' return leftNumberValue.add(rightNumberValue); } } return new LiteralValue(LiteralValue.unwrap(leftValue).toString() + (LiteralValue.unwrap(rightValue).toString()));
204
536
740
<methods><variables>protected static final java.lang.String ADDITION_OPERATOR,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,protected static final java.lang.String SUBTRACTION_OPERATOR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AdditionSubtractionExpression.java
AdditionSubtractionExpression
isLeftAllowed
class AdditionSubtractionExpression extends BinaryOperationExpression { private static final long serialVersionUID = -7977102096580376925L; protected static final String ADDITION_OPERATOR = "+"; protected static final String SUBTRACTION_OPERATOR = "-"; static final String[] OPERATORS = new String[] { ADDITION_OPERATOR, SUBTRACTION_OPERATOR }; private static final boolean[] LENIENCIES = new boolean[] { false, true }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { AdditionExpression.class, SubtractionExpression.class }; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = AdditionSubtractionExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = AdditionSubtractionExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } protected AdditionSubtractionExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } static boolean isRightAllowed(final IStandardExpression right) { return right != null && !(right instanceof Token && !(right instanceof NumberTokenExpression || right instanceof GenericTokenExpression)); } static boolean isLeftAllowed(final IStandardExpression left) {<FILL_FUNCTION_BODY>} static ExpressionParsingState composeAdditionSubtractionExpression( final ExpressionParsingState state, final int nodeIndex) { return composeBinaryOperationExpression( state, nodeIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD); } }
return left != null && !(left instanceof Token && !(left instanceof NumberTokenExpression || left instanceof GenericTokenExpression));
578
33
611
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AndExpression.java
AndExpression
composeAndExpression
class AndExpression extends BinaryOperationExpression { private static final long serialVersionUID = -6085038102412415337L; private static final Logger logger = LoggerFactory.getLogger(AndExpression.class); private static final String OPERATOR = "and"; static final String[] OPERATORS = new String[] {OPERATOR}; private static final boolean[] LENIENCIES = new boolean[] { false }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { AndExpression.class }; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = AndExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = AndExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } public AndExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(OPERATOR); } static boolean isRightAllowed(final IStandardExpression right) { return right != null && !(right instanceof Token && !(right instanceof BooleanTokenExpression)); } static boolean isLeftAllowed(final IStandardExpression left) { return left != null && !(left instanceof Token && !(left instanceof BooleanTokenExpression)); } static ExpressionParsingState composeAndExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} static Object executeAnd( final IExpressionContext context, final AndExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating AND expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final Object leftValue = expression.getLeft().execute(context, expContext); // Short circuit final boolean leftBooleanValue = EvaluationUtils.evaluateAsBoolean(leftValue); if (!leftBooleanValue) { return Boolean.FALSE; } final Object rightValue = expression.getRight().execute(context, expContext); final boolean rightBooleanValue = EvaluationUtils.evaluateAsBoolean(rightValue); return Boolean.valueOf(rightBooleanValue); } }
return composeBinaryOperationExpression( state, nodeIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD);
747
58
805
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/Assignation.java
Assignation
getStringRepresentation
class Assignation implements Serializable { private static final long serialVersionUID = -20278893925937213L; private final IStandardExpression left; private final IStandardExpression right; Assignation(final IStandardExpression left, final IStandardExpression right) { super(); Validate.notNull(left, "Assignation left side cannot be null"); this.left = left; this.right = right; } public IStandardExpression getLeft() { return this.left; } public IStandardExpression getRight() { return this.right; } public String getStringRepresentation() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getStringRepresentation(); } }
final StringBuilder strBuilder = new StringBuilder(); strBuilder.append(this.left.getStringRepresentation()); if (this.right != null) { strBuilder.append('='); if (this.right instanceof ComplexExpression) { strBuilder.append('('); strBuilder.append(this.right.getStringRepresentation()); strBuilder.append(')'); } else { strBuilder.append(this.right.getStringRepresentation()); } } return strBuilder.toString();
228
134
362
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AssignationSequence.java
AssignationSequence
getStringRepresentation
class AssignationSequence implements Iterable<Assignation>, Serializable { private static final long serialVersionUID = -4915282307441011014L; private final List<Assignation> assignations; AssignationSequence(final List<Assignation> assignations) { super(); Validate.notNull(assignations, "Assignation list cannot be null"); Validate.containsNoNulls(assignations, "Assignation list cannot contain any nulls"); this.assignations = Collections.unmodifiableList(assignations); } public List<Assignation> getAssignations() { return this.assignations; } public int size() { return this.assignations.size(); } public Iterator<Assignation> iterator() { return this.assignations.iterator(); } public String getStringRepresentation() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getStringRepresentation(); } }
final StringBuilder sb = new StringBuilder(); if (this.assignations.size() > 0) { sb.append(this.assignations.get(0)); for (int i = 1; i < this.assignations.size(); i++) { sb.append(','); sb.append(this.assignations.get(i)); } } return sb.toString();
291
102
393
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/AssignationUtils.java
AssignationUtils
composeAssignation
class AssignationUtils { public static AssignationSequence parseAssignationSequence( final IExpressionContext context, final String input, final boolean allowParametersWithoutValue) { Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); final String preprocessedInput = StandardExpressionPreprocessor.preprocess(context, input); final IEngineConfiguration configuration = context.getConfiguration(); if (configuration != null) { final AssignationSequence cachedAssignationSequence = ExpressionCache.getAssignationSequenceFromCache(configuration, preprocessedInput); if (cachedAssignationSequence != null) { return cachedAssignationSequence; } } final AssignationSequence assignationSequence = internalParseAssignationSequence(preprocessedInput.trim(), allowParametersWithoutValue); if (assignationSequence == null) { throw new TemplateProcessingException("Could not parse as assignation sequence: \"" + input + "\""); } if (configuration != null) { ExpressionCache.putAssignationSequenceIntoCache(configuration, preprocessedInput, assignationSequence); } return assignationSequence; } static AssignationSequence internalParseAssignationSequence(final String input, final boolean allowParametersWithoutValue) { if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final ExpressionParsingState decomposition = ExpressionParsingUtil.decompose(input); if (decomposition == null) { return null; } return composeSequence(decomposition, 0, allowParametersWithoutValue); } private static AssignationSequence composeSequence( final ExpressionParsingState state, final int nodeIndex, final boolean allowParametersWithoutValue) { if (state == null || nodeIndex >= state.size()) { return null; } if (state.hasExpressionAt(nodeIndex)) { if (!allowParametersWithoutValue) { return null; } // could happen if we are traversing pointers recursively, so we will consider it a sequence containing // only one, no-value assignation (though we will let the Assignation.compose(...) method do the job. final Assignation assignation = composeAssignation(state, nodeIndex, allowParametersWithoutValue); if (assignation == null) { return null; } final List<Assignation> assignations = new ArrayList<Assignation>(2); assignations.add(assignation); return new AssignationSequence(assignations); } final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // First, check whether we are just dealing with a pointer input final int pointer = ExpressionParsingUtil.parseAsSimpleIndexPlaceholder(input); if (pointer != -1) { return composeSequence(state, pointer, allowParametersWithoutValue); } final String[] inputParts = StringUtils.split(input, ","); for (final String inputPart : inputParts) { // We create new String parsing nodes for all of the elements // We add all nodes first so that we know the exact indexes in which they are // (composing assignations here can modify the size of the state object without we noticing) state.addNode(inputPart.trim()); } final List<Assignation> assignations = new ArrayList<Assignation>(4); final int startIndex = state.size() - inputParts.length; final int endIndex = state.size(); for (int i = startIndex; i < endIndex; i++) { final Assignation assignation = composeAssignation(state, i, allowParametersWithoutValue); if (assignation == null) { return null; } assignations.add(assignation); } return new AssignationSequence(assignations); } static Assignation composeAssignation( final ExpressionParsingState state, final int nodeIndex, final boolean allowParametersWithoutValue) {<FILL_FUNCTION_BODY>} private AssignationUtils() { super(); } }
if (state == null || nodeIndex >= state.size()) { return null; } if (state.hasExpressionAt(nodeIndex)) { if (!allowParametersWithoutValue) { return null; } // could happen if we are traversing pointers recursively, so we will consider it a no-value assignation return new Assignation(state.get(nodeIndex).getExpression(),null); } final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // First, check whether we are just dealing with a pointer input final int pointer = ExpressionParsingUtil.parseAsSimpleIndexPlaceholder(input); if (pointer != -1) { return composeAssignation(state, pointer, allowParametersWithoutValue); } final int inputLen = input.length(); final int operatorPos = input.indexOf('='); final String leftInput = (operatorPos == -1? input.trim() : input.substring(0,operatorPos).trim()); final String rightInput = (operatorPos == -1 || operatorPos == (inputLen - 1) ? null : input.substring(operatorPos + 1).trim()); if (StringUtils.isEmptyOrWhitespace(leftInput)) { return null; } final Expression leftExpr = ExpressionParsingUtil.parseAndCompose(state, leftInput); if (leftExpr == null) { return null; } final Expression rightExpr; if (!StringUtils.isEmptyOrWhitespace(rightInput)) { rightExpr = ExpressionParsingUtil.parseAndCompose(state, rightInput); if (rightExpr == null) { return null; } } else if (!allowParametersWithoutValue) { return null; } else { rightExpr = null; } return new Assignation(leftExpr, rightExpr);
1,094
505
1,599
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/BinaryOperationExpression.java
BinaryOperationExpression
doComposeBinaryOperationExpression
class BinaryOperationExpression extends ComplexExpression { private static final long serialVersionUID = 7524261639178859585L; private final IStandardExpression left; private final IStandardExpression right; protected BinaryOperationExpression(final IStandardExpression left, final IStandardExpression right) { super(); Validate.notNull(left, "Left-side expression cannot be null"); Validate.notNull(right, "Right-side expression cannot be null"); this.left = left; this.right = right; } public IStandardExpression getLeft() { return this.left; } public IStandardExpression getRight() { return this.right; } protected String getStringRepresentation(final String operator) { final StringBuilder sb = new StringBuilder(); if (this.left instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.left); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.left); } sb.append(' '); sb.append(operator); sb.append(' '); if (this.right instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.right); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.right); } return sb.toString(); } protected static ExpressionParsingState composeBinaryOperationExpression( final ExpressionParsingState state, final int nodeIndex, final String[] operators, final boolean[] leniencies, final Class<? extends BinaryOperationExpression>[] operationClasses, final Method leftAllowedMethod, final Method rightAllowedMethod) { // Returning "state" means "try next in chain" or "success" // Returning "null" means parsing error // // "Lenient" means that if the last operator occurrence found does not result // in a valid parse result, the previous-to-last (and all previous to that) // should also be tried in sequence (this is mainly to avoid "-" symbols from // minus operators getting in the way of subtraction operations). final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } String scannedInput = input.toLowerCase(); do { int operatorIndex = -1; int operatorPosFrom = -1; int operatorPosTo = Integer.MAX_VALUE; int operatorLen = 0; for (int i = 0; i < operators.length; i++) { // Trying to fail quickly... final int currentOperatorPosFrom = scannedInput.lastIndexOf(operators[i]); if (currentOperatorPosFrom != -1) { final int currentOperatorLen = operators[i].length(); final int currentOperatorPosTo = currentOperatorPosFrom + currentOperatorLen; if (operatorPosFrom == -1 || operatorPosTo < currentOperatorPosFrom || (currentOperatorLen > operatorLen && currentOperatorPosTo >= operatorPosTo)) { // the last condition is for allowing "<=" not to be confused with "<" or "neq" with "eq" operatorPosFrom = currentOperatorPosFrom; operatorLen = operators[i].length(); operatorPosTo = currentOperatorPosFrom + operatorLen; operatorIndex = i; } } } if (operatorPosFrom == -1) { return state; } if (doComposeBinaryOperationExpression( state, nodeIndex, operators[operatorIndex], operationClasses[operatorIndex], leftAllowedMethod, rightAllowedMethod, input, operatorPosFrom) == null) { if (leniencies[operatorIndex]) { scannedInput = scannedInput.substring(0, operatorPosFrom); } else { return null; } } else { return state; } } while (true); } private static ExpressionParsingState doComposeBinaryOperationExpression( final ExpressionParsingState state, final int nodeIndex, final String operator, final Class<? extends BinaryOperationExpression> operationClass, final Method leftAllowedMethod, final Method rightAllowedMethod, final String input, final int operatorPos) {<FILL_FUNCTION_BODY>} }
final String leftStr = input.substring(0, operatorPos).trim(); final String rightStr = input.substring(operatorPos + operator.length()).trim(); if (leftStr.length() == 0 || rightStr.length() == 0) { return null; } final Expression leftExpr = ExpressionParsingUtil.parseAndCompose(state, leftStr); try { if (leftExpr == null || !((Boolean)leftAllowedMethod.invoke(null,leftExpr)).booleanValue()) { return null; } } catch (final IllegalAccessException e) { // Should never happen, would be a programming error throw new TemplateProcessingException("Error invoking operand validation in binary operation", e); } catch (final InvocationTargetException e) { // Should never happen, would be a programming error throw new TemplateProcessingException("Error invoking operand validation in binary operation", e); } final Expression rightExpr = ExpressionParsingUtil.parseAndCompose(state, rightStr); try { if (rightExpr == null || !((Boolean)rightAllowedMethod.invoke(null,rightExpr)).booleanValue()) { return null; } } catch (final IllegalAccessException e) { // Should never happen, would be a programming error throw new TemplateProcessingException("Error invoking operand validation in binary operation", e); } catch (final InvocationTargetException e) { // Should never happen, would be a programming error throw new TemplateProcessingException("Error invoking operand validation in binary operation", e); } try { final BinaryOperationExpression operationExpression = operationClass.getDeclaredConstructor(IStandardExpression.class, IStandardExpression.class). newInstance(leftExpr, rightExpr); state.setNode(nodeIndex, operationExpression); } catch (final TemplateProcessingException e) { throw e; } catch (final Exception e) { throw new TemplateProcessingException( "Error during creation of Binary Operation expression for operator: \"" + operator + "\"", e); } return state;
1,178
534
1,712
<methods><variables>private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/BooleanTokenExpression.java
BooleanTokenExpression
parseBooleanTokenExpression
class BooleanTokenExpression extends Token { private static final Logger logger = LoggerFactory.getLogger(BooleanTokenExpression.class); private static final long serialVersionUID = 7003426193298054476L; public BooleanTokenExpression(final String value) { super(Boolean.valueOf(value)); } public BooleanTokenExpression(final Boolean value) { super(value); } static BooleanTokenExpression parseBooleanTokenExpression(final String input) {<FILL_FUNCTION_BODY>} static Object executeBooleanTokenExpression( final IExpressionContext context, final BooleanTokenExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating boolean token: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return expression.getValue(); } }
if ("true".equalsIgnoreCase(input) || "false".equalsIgnoreCase(input)) { return new BooleanTokenExpression(input); } return null;
259
44
303
<methods>public java.lang.String getStringRepresentation() ,public java.lang.Object getValue() ,public static boolean isTokenChar(java.lang.String, int) ,public java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object value
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ComplexExpression.java
ComplexExpression
executeComplex
class ComplexExpression extends Expression { private static final long serialVersionUID = -3807499386899890260L; protected ComplexExpression() { super(); } static Object executeComplex( final IExpressionContext context, final ComplexExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (expression instanceof AdditionExpression) { return AdditionExpression.executeAddition(context, (AdditionExpression)expression, expContext); } if (expression instanceof SubtractionExpression) { return SubtractionExpression.executeSubtraction(context, (SubtractionExpression)expression, expContext); } if (expression instanceof MultiplicationExpression) { return MultiplicationExpression.executeMultiplication(context, (MultiplicationExpression)expression, expContext); } if (expression instanceof DivisionExpression) { return DivisionExpression.executeDivision(context, (DivisionExpression)expression, expContext); } if (expression instanceof RemainderExpression) { return RemainderExpression.executeRemainder(context, (RemainderExpression)expression, expContext); } if (expression instanceof ConditionalExpression) { return ConditionalExpression.executeConditional(context, (ConditionalExpression)expression, expContext); } if (expression instanceof DefaultExpression) { return DefaultExpression.executeDefault(context, (DefaultExpression)expression, expContext); } if (expression instanceof MinusExpression) { return MinusExpression.executeMinus(context, (MinusExpression)expression, expContext); } if (expression instanceof NegationExpression) { return NegationExpression.executeNegation(context, (NegationExpression)expression, expContext); } if (expression instanceof AndExpression) { return AndExpression.executeAnd(context, (AndExpression)expression, expContext); } if (expression instanceof OrExpression) { return OrExpression.executeOr(context, (OrExpression)expression, expContext); } if (expression instanceof EqualsExpression) { return EqualsExpression.executeEquals(context, (EqualsExpression)expression, expContext); } if (expression instanceof NotEqualsExpression) { return NotEqualsExpression.executeNotEquals(context, (NotEqualsExpression)expression, expContext); } if (expression instanceof GreaterThanExpression) { return GreaterThanExpression.executeGreaterThan(context, (GreaterThanExpression)expression, expContext); } if (expression instanceof GreaterOrEqualToExpression) { return GreaterOrEqualToExpression.executeGreaterOrEqualTo(context, (GreaterOrEqualToExpression)expression, expContext); } if (expression instanceof LessThanExpression) { return LessThanExpression.executeLessThan(context, (LessThanExpression)expression, expContext); } if (expression instanceof LessOrEqualToExpression) { return LessOrEqualToExpression.executeLessOrEqualTo(context, (LessOrEqualToExpression)expression, expContext); } throw new TemplateProcessingException("Unrecognized complex expression: " + expression.getClass().getName());
120
689
809
<methods>public java.lang.Object execute(org.thymeleaf.context.IExpressionContext) ,public java.lang.Object execute(org.thymeleaf.context.IExpressionContext, org.thymeleaf.standard.expression.StandardExpressionExecutionContext) ,public abstract java.lang.String getStringRepresentation() ,public java.lang.String toString() <variables>public static final char NESTING_END_CHAR,public static final char NESTING_START_CHAR,public static final char PARSING_PLACEHOLDER_CHAR,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ConditionalExpression.java
ConditionalExpression
composeConditionalExpression
class ConditionalExpression extends ComplexExpression { private static final Logger logger = LoggerFactory.getLogger(ConditionalExpression.class); private static final long serialVersionUID = -6966177717462316363L; private static final char CONDITION_SUFFIX_CHAR = '?'; private static final char CONDITION_THENELSE_SEPARATOR_CHAR = ':'; // These are all the tokens registered by this expression static final String[] OPERATORS = new String[] {String.valueOf(CONDITION_SUFFIX_CHAR), String.valueOf(CONDITION_THENELSE_SEPARATOR_CHAR)}; private final Expression conditionExpression; private final Expression thenExpression; private final Expression elseExpression; public ConditionalExpression(final Expression conditionExpression, final Expression thenExpression, final Expression elseExpression) { super(); Validate.notNull(conditionExpression, "Condition expression cannot be null"); Validate.notNull(thenExpression, "Then expression cannot be null"); Validate.notNull(elseExpression, "Else expression cannot be null"); this.conditionExpression = conditionExpression; this.thenExpression = thenExpression; this.elseExpression = elseExpression; } public Expression getConditionExpression() { return this.conditionExpression; } public Expression getThenExpression() { return this.thenExpression; } public Expression getElseExpression() { return this.elseExpression; } @Override public String getStringRepresentation() { final StringBuilder sb = new StringBuilder(); if (this.conditionExpression instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.conditionExpression); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.conditionExpression); } sb.append(CONDITION_SUFFIX_CHAR); sb.append(' '); if (this.thenExpression instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.thenExpression); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.thenExpression); } sb.append(' '); sb.append(CONDITION_THENELSE_SEPARATOR_CHAR); sb.append(' '); if (this.elseExpression instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.elseExpression); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.elseExpression); } return sb.toString(); } static ExpressionParsingState composeConditionalExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} static Object executeConditional( final IExpressionContext context, final ConditionalExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating conditional expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final Object condObj = expression.getConditionExpression().execute(context, expContext); final boolean cond = EvaluationUtils.evaluateAsBoolean(condObj); if (cond) { return expression.getThenExpression().execute(context, expContext); } return expression.getElseExpression().execute(context, expContext); } }
// Returning "state" means "try next in chain" or "success" // Returning "null" means parsing error final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // Trying to fail quickly... final int condSuffixPos = input.indexOf(CONDITION_SUFFIX_CHAR); if (condSuffixPos == -1) { return state; } final String condStr = input.substring(0, condSuffixPos); final String remainder = input.substring(condSuffixPos + 1); if (remainder.indexOf(CONDITION_SUFFIX_CHAR) != -1) { // There are two "?" symbols return null; } final int thenElseSepPos = remainder.indexOf(CONDITION_THENELSE_SEPARATOR_CHAR); if (remainder.lastIndexOf(CONDITION_THENELSE_SEPARATOR_CHAR) != thenElseSepPos) { // There are two ":" symbols return null; } String thenStr = null; String elseStr = null; if (thenElseSepPos != -1) { if (thenElseSepPos == 0) { // Maybe it is a default operation return state; } thenStr = remainder.substring(0, thenElseSepPos); elseStr = remainder.substring(thenElseSepPos + 1); } else { thenStr = remainder; } final Expression condExpr = ExpressionParsingUtil.parseAndCompose(state, condStr); if (condExpr == null) { return null; } final Expression thenExpr = ExpressionParsingUtil.parseAndCompose(state, thenStr); if (thenExpr == null) { return null; } Expression elseExpr = VariableExpression.NULL_VALUE; if (elseStr != null) { elseExpr = ExpressionParsingUtil.parseAndCompose(state, elseStr); if (elseExpr == null) { return null; } } final ConditionalExpression conditionalExpressionResult = new ConditionalExpression(condExpr, thenExpr, elseExpr); state.setNode(nodeIndex,conditionalExpressionResult); return state;
969
629
1,598
<methods><variables>private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/DefaultExpression.java
DefaultExpression
composeDefaultExpression
class DefaultExpression extends ComplexExpression { private static final Logger logger = LoggerFactory.getLogger(DefaultExpression.class); private static final long serialVersionUID = 1830867943963082362L; private static final String OPERATOR = "?:"; // Future proof, just in case in the future we add other tokens as operators static final String[] OPERATORS = new String[] {String.valueOf(OPERATOR)}; private final Expression queriedExpression; private final Expression defaultExpression; public DefaultExpression(final Expression queriedExpression, final Expression defaultExpression) { super(); Validate.notNull(queriedExpression, "Queried expression cannot be null"); Validate.notNull(defaultExpression, "Default expression cannot be null"); this.queriedExpression = queriedExpression; this.defaultExpression = defaultExpression; } public Expression getQueriedExpression() { return this.queriedExpression; } public Expression getDefaultExpression() { return this.defaultExpression; } @Override public String getStringRepresentation() { final StringBuilder sb = new StringBuilder(); if (this.queriedExpression instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.queriedExpression); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.queriedExpression); } sb.append(' '); sb.append(OPERATOR); sb.append(' '); if (this.defaultExpression instanceof ComplexExpression) { sb.append(Expression.NESTING_START_CHAR); sb.append(this.defaultExpression); sb.append(Expression.NESTING_END_CHAR); } else { sb.append(this.defaultExpression); } return sb.toString(); } static ExpressionParsingState composeDefaultExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} static Object executeDefault( final IExpressionContext context, final DefaultExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating default expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } final Object queriedValue = expression.getQueriedExpression().execute(context, expContext); if (queriedValue == null) { return expression.getDefaultExpression().execute(context, expContext); } return queriedValue; } }
// Returning "state" means "try next in chain" or "success" // Returning "null" means parsing error final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // Trying to fail quickly... final int defaultOperatorPos = input.indexOf(OPERATOR); if (defaultOperatorPos == -1) { return state; } final String queriedStr = input.substring(0, defaultOperatorPos); final String defaultStr = input.substring(defaultOperatorPos + 2); if (defaultStr.contains(OPERATOR)) { // There are two "?:" operators return null; } final Expression queriedExpr = ExpressionParsingUtil.parseAndCompose(state, queriedStr); if (queriedExpr == null) { return null; } final Expression defaultExpr = ExpressionParsingUtil.parseAndCompose(state, defaultStr); if (defaultExpr == null) { return null; } final DefaultExpression defaultExpressionResult = new DefaultExpression(queriedExpr, defaultExpr); state.setNode(nodeIndex, defaultExpressionResult); return state;
728
336
1,064
<methods><variables>private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/DivisionExpression.java
DivisionExpression
executeDivision
class DivisionExpression extends MultiplicationDivisionRemainderExpression { private static final long serialVersionUID = -6480768503994179971L; private static final Logger logger = LoggerFactory.getLogger(DivisionExpression.class); public DivisionExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(DIVISION_OPERATOR); } static Object executeDivision( final IExpressionContext context, final DivisionExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating division expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null) { leftValue = "null"; } if (rightValue == null) { rightValue = "null"; } final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { try { return leftNumberValue.divide(rightNumberValue); } catch (final ArithmeticException ignored) { // Result has a non-terminating decimal expansion (like 100/3), so // we just use a minimum arbitrary scale (10) and HALF_UP rounding mode return leftNumberValue.divide( rightNumberValue, Math.max(Math.max(leftNumberValue.scale(),rightNumberValue.scale()), 10), RoundingMode.HALF_UP); } } throw new TemplateProcessingException( "Cannot execute division: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\"");
207
397
604
<methods><variables>protected static final java.lang.String DIVISION_OPERATOR,protected static final java.lang.String DIVISION_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String MULTIPLICATION_OPERATOR,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,protected static final java.lang.String REMAINDER_OPERATOR,protected static final java.lang.String REMAINDER_OPERATOR_2,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/Each.java
Each
getStringRepresentation
class Each implements Serializable { private static final long serialVersionUID = -4085690403057997591L; private final IStandardExpression iterVar; private final IStandardExpression statusVar; private final IStandardExpression iterable; public Each(final IStandardExpression iterVar, final IStandardExpression statusVar, final IStandardExpression iterable) { super(); Validate.notNull(iterVar, "Iteration variable cannot be null"); Validate.notNull(iterable, "Iterable cannot be null"); this.iterVar = iterVar; this.statusVar = statusVar; this.iterable = iterable; } public IStandardExpression getIterVar() { return this.iterVar; } public boolean hasStatusVar() { return this.statusVar != null; } public IStandardExpression getStatusVar() { return this.statusVar; } public IStandardExpression getIterable() { return this.iterable; } public String getStringRepresentation() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getStringRepresentation(); } }
final StringBuilder sb = new StringBuilder(); sb.append(this.iterVar); if (hasStatusVar()) { sb.append(','); sb.append(this.statusVar); } sb.append(" : "); sb.append(this.iterable); return sb.toString();
336
82
418
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/EachUtils.java
EachUtils
parseEach
class EachUtils { private static final String OPERATOR = ":"; private static final String STAT_SEPARATOR = ","; public static Each parseEach( final IExpressionContext context, final String input) {<FILL_FUNCTION_BODY>} static Each internalParseEach(final String input) { if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final ExpressionParsingState decomposition = ExpressionParsingUtil.decompose(input); if (decomposition == null) { return null; } return composeEach(decomposition, 0); } private static Each composeEach(final ExpressionParsingState state, final int nodeIndex) { if (state == null || nodeIndex >= state.size()) { return null; } if (state.hasExpressionAt(nodeIndex)) { // shouldn't happen in this case (ExpressionSequences are not Expressions). We need a string to parse! return null; } final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // First, check whether we are just dealing with a pointer input final int pointer = ExpressionParsingUtil.parseAsSimpleIndexPlaceholder(input); if (pointer != -1) { return composeEach(state, pointer); } final int inputLen = input.length(); final int operatorLen = OPERATOR.length(); final int operatorPos = input.indexOf(OPERATOR); if (operatorPos == -1 || operatorPos == 0 || operatorPos >= (inputLen - operatorLen)) { return null; } final String left = input.substring(0,operatorPos).trim(); final String iterableStr = input.substring(operatorPos + operatorLen).trim(); final int statPos = left.indexOf(STAT_SEPARATOR); final String iterVarStr; final String statusVarStr; if (statPos == -1) { iterVarStr = left; statusVarStr = null; } else { if (statPos == 0 || statPos >= (left.length() - operatorLen)) { return null; } iterVarStr = left.substring(0, statPos); statusVarStr = left.substring(statPos + operatorLen); } final Expression iterVarExpr = ExpressionParsingUtil.parseAndCompose(state, iterVarStr); if (iterVarStr == null) { return null; } final Expression statusVarExpr; if (statusVarStr != null) { statusVarExpr = ExpressionParsingUtil.parseAndCompose(state, statusVarStr); if (statusVarExpr == null) { return null; } } else { statusVarExpr = null; } final Expression iterableExpr = ExpressionParsingUtil.parseAndCompose(state, iterableStr); if (iterableExpr == null) { return null; } return new Each(iterVarExpr,statusVarExpr,iterableExpr); } private EachUtils() { super(); } }
Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); final String preprocessedInput = StandardExpressionPreprocessor.preprocess(context, input); final IEngineConfiguration configuration = context.getConfiguration(); if (configuration != null) { final Each cachedEach = ExpressionCache.getEachFromCache(configuration, preprocessedInput); if (cachedEach != null) { return cachedEach; } } final Each each = internalParseEach(preprocessedInput.trim()); if (each == null) { throw new TemplateProcessingException("Could not parse as each: \"" + input + "\""); } if (configuration != null) { ExpressionCache.putEachIntoCache(configuration, preprocessedInput, each); } return each;
855
228
1,083
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/EqualsExpression.java
EqualsExpression
executeEquals
class EqualsExpression extends EqualsNotEqualsExpression { private static final long serialVersionUID = -3223406642461547141L; private static final Logger logger = LoggerFactory.getLogger(EqualsExpression.class); public EqualsExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(EQUALS_OPERATOR); } @SuppressWarnings({"unchecked","null"}) static Object executeEquals( final IExpressionContext context, final EqualsExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); if (leftValue == null) { return Boolean.valueOf(rightValue == null); } Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) == 0); } else { if (leftValue instanceof Character) { leftValue = leftValue.toString(); // Just a character, no need to use conversionService here } if (rightValue != null && rightValue instanceof Character) { rightValue = rightValue.toString(); // Just a character, no need to use conversionService here } if (rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) == 0); } else { result = Boolean.valueOf(leftValue.equals(rightValue)); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating EQUALS expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
217
487
704
<methods><variables>protected static final java.lang.String EQUALS_OPERATOR,protected static final java.lang.String EQUALS_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String NOT_EQUALS_OPERATOR,protected static final java.lang.String NOT_EQUALS_OPERATOR_2,protected static final java.lang.String NOT_EQUALS_OPERATOR_3,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/EqualsNotEqualsExpression.java
EqualsNotEqualsExpression
composeEqualsNotEqualsExpression
class EqualsNotEqualsExpression extends BinaryOperationExpression { private static final long serialVersionUID = -8648395536336588140L; protected static final String EQUALS_OPERATOR = "=="; protected static final String EQUALS_OPERATOR_2 = "eq"; protected static final String NOT_EQUALS_OPERATOR = "!="; protected static final String NOT_EQUALS_OPERATOR_2 = "neq"; protected static final String NOT_EQUALS_OPERATOR_3 = "ne"; static final String[] OPERATORS = new String[] { EQUALS_OPERATOR, NOT_EQUALS_OPERATOR, EQUALS_OPERATOR_2, NOT_EQUALS_OPERATOR_2, NOT_EQUALS_OPERATOR_3 }; private static final boolean[] LENIENCIES = new boolean[] { false, false, false, false, false }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { EqualsExpression.class, NotEqualsExpression.class, EqualsExpression.class, NotEqualsExpression.class, NotEqualsExpression.class }; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = EqualsNotEqualsExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = EqualsNotEqualsExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } protected EqualsNotEqualsExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } static boolean isRightAllowed(final IStandardExpression right) { return true; } static boolean isLeftAllowed(final IStandardExpression left) { return true; } protected static ExpressionParsingState composeEqualsNotEqualsExpression( final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} }
return composeBinaryOperationExpression( state, nodeIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD);
642
58
700
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/Expression.java
Expression
parse
class Expression implements IStandardExpression, Serializable { private static final long serialVersionUID = 1608378943284014151L; public static final char PARSING_PLACEHOLDER_CHAR = '\u00A7'; public static final char NESTING_START_CHAR = '('; public static final char NESTING_END_CHAR = ')'; protected Expression() { super(); } public abstract String getStringRepresentation(); @Override public String toString() { return getStringRepresentation(); } static Expression parse(final String input) {<FILL_FUNCTION_BODY>} static Object execute( final IExpressionContext context, final Expression expression, final IStandardVariableExpressionEvaluator expressionEvaluator, final StandardExpressionExecutionContext expContext) { if (expression instanceof SimpleExpression) { return SimpleExpression.executeSimple(context, (SimpleExpression)expression, expressionEvaluator, expContext); } if (expression instanceof ComplexExpression) { return ComplexExpression.executeComplex(context, (ComplexExpression)expression, expContext); } throw new TemplateProcessingException("Unrecognized expression: " + expression.getClass().getName()); } public Object execute( final IExpressionContext context) { return execute(context, StandardExpressionExecutionContext.NORMAL); } public Object execute( final IExpressionContext context, final StandardExpressionExecutionContext expContext) { Validate.notNull(context, "Context cannot be null"); final IStandardVariableExpressionEvaluator variableExpressionEvaluator = StandardExpressions.getVariableExpressionEvaluator(context.getConfiguration()); final Object result = execute(context, this, variableExpressionEvaluator, expContext); return LiteralValue.unwrap(result); } }
Validate.notNull(input, "Input cannot be null"); /* * PHASE 01: Decomposition (including unnesting parenthesis) */ final ExpressionParsingState decomposition = ExpressionParsingUtil.decompose(input); if (decomposition == null) { return null; } /* * PHASE 02: Composition */ final ExpressionParsingState result = ExpressionParsingUtil.compose(decomposition); if (result == null || !result.hasExpressionAt(0)) { return null; } return result.get(0).getExpression();
530
173
703
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ExpressionCache.java
ExpressionCache
removeFromCache
class ExpressionCache { private static final String EXPRESSION_CACHE_TYPE_STANDARD_EXPRESSION = "expr"; private static final String EXPRESSION_CACHE_TYPE_ASSIGNATION_SEQUENCE = "aseq"; private static final String EXPRESSION_CACHE_TYPE_EXPRESSION_SEQUENCE = "eseq"; private static final String EXPRESSION_CACHE_TYPE_EACH = "each"; private static final String EXPRESSION_CACHE_TYPE_FRAGMENT_SIGNATURE = "fsig"; private ExpressionCache() { super(); } static Object getFromCache(final IEngineConfiguration configuration, final String input, final String type) { final ICacheManager cacheManager = configuration.getCacheManager(); if (cacheManager != null) { final ICache<ExpressionCacheKey,Object> cache = cacheManager.getExpressionCache(); if (cache != null) { return cache.get(new ExpressionCacheKey(type,input)); } } return null; } static <V> void putIntoCache(final IEngineConfiguration configuration, final String input, final V value, final String type) { final ICacheManager cacheManager = configuration.getCacheManager(); if (cacheManager != null) { final ICache<ExpressionCacheKey,Object> cache = cacheManager.getExpressionCache(); if (cache != null) { cache.put(new ExpressionCacheKey(type,input), value); } } } static <V> void removeFromCache(final IEngineConfiguration configuration, final String input, final String type) {<FILL_FUNCTION_BODY>} static IStandardExpression getExpressionFromCache(final IEngineConfiguration configuration, final String input) { return (IStandardExpression) getFromCache(configuration, input, EXPRESSION_CACHE_TYPE_STANDARD_EXPRESSION); } static void putExpressionIntoCache(final IEngineConfiguration configuration, final String input, final IStandardExpression value) { putIntoCache(configuration, input, value, EXPRESSION_CACHE_TYPE_STANDARD_EXPRESSION); } static AssignationSequence getAssignationSequenceFromCache(final IEngineConfiguration configuration, final String input) { return (AssignationSequence) getFromCache(configuration, input, EXPRESSION_CACHE_TYPE_ASSIGNATION_SEQUENCE); } static void putAssignationSequenceIntoCache(final IEngineConfiguration configuration, final String input, final AssignationSequence value) { putIntoCache(configuration, input, value, EXPRESSION_CACHE_TYPE_ASSIGNATION_SEQUENCE); } static ExpressionSequence getExpressionSequenceFromCache(final IEngineConfiguration configuration, final String input) { return (ExpressionSequence) getFromCache(configuration, input, EXPRESSION_CACHE_TYPE_EXPRESSION_SEQUENCE); } static void putExpressionSequenceIntoCache(final IEngineConfiguration configuration, final String input, final ExpressionSequence value) { putIntoCache(configuration, input, value, EXPRESSION_CACHE_TYPE_EXPRESSION_SEQUENCE); } static Each getEachFromCache(final IEngineConfiguration configuration, final String input) { return (Each) getFromCache(configuration, input, EXPRESSION_CACHE_TYPE_EACH); } static void putEachIntoCache(final IEngineConfiguration configuration, final String input, final Each value) { putIntoCache(configuration, input, value, EXPRESSION_CACHE_TYPE_EACH); } static FragmentSignature getFragmentSignatureFromCache(final IEngineConfiguration configuration, final String input) { return (FragmentSignature) getFromCache(configuration, input, EXPRESSION_CACHE_TYPE_FRAGMENT_SIGNATURE); } static void putFragmentSignatureIntoCache(final IEngineConfiguration configuration, final String input, final FragmentSignature value) { putIntoCache(configuration, input, value, EXPRESSION_CACHE_TYPE_FRAGMENT_SIGNATURE); } }
final ICacheManager cacheManager = configuration.getCacheManager(); if (cacheManager != null) { final ICache<ExpressionCacheKey,Object> cache = cacheManager.getExpressionCache(); if (cache != null) { cache.clearKey(new ExpressionCacheKey(type,input)); } }
1,053
83
1,136
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ExpressionParsingNode.java
ExpressionParsingNode
toString
class ExpressionParsingNode { private final String input; private final Expression expression; ExpressionParsingNode(final String input) { super(); // INPUT SHOULD NEVER BE NULL!!! this.input = input.trim(); this.expression = null; } ExpressionParsingNode(final Expression expression) { super(); this.expression = expression; this.input = null; } boolean isInput() { return this.input != null; } boolean isExpression() { return this.expression != null; } boolean isSimpleExpression() { return this.expression != null && this.expression instanceof SimpleExpression; } boolean ComplexExpression() { return this.expression != null && this.expression instanceof ComplexExpression; } String getInput() { return this.input; } Expression getExpression() { return this.expression; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return (isExpression()? "[" + this.expression.getStringRepresentation() + "]" : this.input);
291
34
325
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ExpressionSequence.java
ExpressionSequence
getStringRepresentation
class ExpressionSequence implements Iterable<IStandardExpression>, Serializable { private static final long serialVersionUID = -6069208208568731809L; private final List<IStandardExpression> expressions; public ExpressionSequence(final List<? extends IStandardExpression> expressions) { super(); Validate.notNull(expressions, "Expression list cannot be null"); Validate.containsNoNulls(expressions, "Expression list cannot contain any nulls"); this.expressions = Collections.unmodifiableList(expressions); } public List<IStandardExpression> getExpressions() { return this.expressions; } public int size() { return this.expressions.size(); } public Iterator<IStandardExpression> iterator() { return this.expressions.iterator(); } public String getStringRepresentation() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getStringRepresentation(); } }
final StringBuilder sb = new StringBuilder(); if (this.expressions.size() > 0) { sb.append(this.expressions.get(0)); for (int i = 1; i < this.expressions.size(); i++) { sb.append(','); sb.append(this.expressions.get(i)); } } return sb.toString();
287
102
389
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/ExpressionSequenceUtils.java
ExpressionSequenceUtils
composeSequence
class ExpressionSequenceUtils { public static ExpressionSequence parseExpressionSequence( final IExpressionContext context, final String input) { Validate.notNull(context, "Context cannot be null"); Validate.notNull(input, "Input cannot be null"); final String preprocessedInput = StandardExpressionPreprocessor.preprocess(context, input); final IEngineConfiguration configuration = context.getConfiguration(); if (configuration != null) { final ExpressionSequence cachedExpressionSequence = ExpressionCache.getExpressionSequenceFromCache(configuration, preprocessedInput); if (cachedExpressionSequence != null) { return cachedExpressionSequence; } } final ExpressionSequence expressionSequence = internalParseExpressionSequence(preprocessedInput.trim()); if (expressionSequence == null) { throw new TemplateProcessingException("Could not parse as expression sequence: \"" + input + "\""); } if (configuration != null) { ExpressionCache.putExpressionSequenceIntoCache(configuration, preprocessedInput, expressionSequence); } return expressionSequence; } static ExpressionSequence internalParseExpressionSequence(final String input) { if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final ExpressionParsingState decomposition = ExpressionParsingUtil.decompose(input); if (decomposition == null) { return null; } return composeSequence(decomposition, 0); } private static ExpressionSequence composeSequence(final ExpressionParsingState state, final int nodeIndex) {<FILL_FUNCTION_BODY>} private ExpressionSequenceUtils() { super(); } }
if (state == null || nodeIndex >= state.size()) { return null; } if (state.hasExpressionAt(nodeIndex)) { // could happen if we are traversing pointers recursively, so we will consider an expression sequence // with one expression only final List<IStandardExpression> expressions = new ArrayList<IStandardExpression>(2); expressions.add(state.get(nodeIndex).getExpression()); return new ExpressionSequence(expressions); } final String input = state.get(nodeIndex).getInput(); if (StringUtils.isEmptyOrWhitespace(input)) { return null; } // First, check whether we are just dealing with a pointer input final int pointer = ExpressionParsingUtil.parseAsSimpleIndexPlaceholder(input); if (pointer != -1) { return composeSequence(state, pointer); } final String[] inputParts = StringUtils.split(input, ","); final List<IStandardExpression> expressions = new ArrayList<IStandardExpression>(4); for (final String inputPart : inputParts) { final Expression expression = ExpressionParsingUtil.parseAndCompose(state, inputPart); if (expression == null) { return null; } expressions.add(expression); } return new ExpressionSequence(expressions);
460
351
811
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/Fragment.java
Fragment
toString
class Fragment { public static final Fragment EMPTY_FRAGMENT = new Fragment(); private final TemplateModel templateModel; private final Map<String,Object> parameters; private final boolean syntheticParameters; public Fragment( final TemplateModel templateModel, final Map<String, Object> parameters, final boolean syntheticParameters) { super(); Validate.notNull(templateModel, "Template model cannot be null"); this.templateModel = templateModel; this.parameters = parameters != null ? Collections.unmodifiableMap(parameters) : null; this.syntheticParameters = (this.parameters != null && this.parameters.size() > 0 && syntheticParameters); } // Creates the empty Fragment private Fragment() { super(); this.templateModel = null; this.parameters = null; this.syntheticParameters = false; } public TemplateModel getTemplateModel() { return this.templateModel; } public Map<String, Object> getParameters() { return this.parameters; } public boolean hasSyntheticParameters() { return this.syntheticParameters; } public void write(final Writer writer) throws IOException { if (this.templateModel != null) { this.templateModel.write(writer); } } @Override public 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();
377
68
445
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/FragmentSignature.java
FragmentSignature
getStringRepresentation
class FragmentSignature implements Serializable { private static final long serialVersionUID = 6847640942405961705L; private static final char FRAGMENT_SIGNATURE_PARAMETERS_START = '('; private static final char FRAGMENT_SIGNATURE_PARAMETERS_END = ')'; private final String fragmentName; private final List<String> parameterNames; public FragmentSignature(final String fragmentName, final List<String> parameterNames) { super(); Validate.notEmpty(fragmentName, "Fragment name cannot be null or empty"); this.fragmentName = fragmentName; this.parameterNames = parameterNames; } public String getFragmentName() { return this.fragmentName; } public boolean hasParameters() { return this.parameterNames != null && this.parameterNames.size() > 0; } public List<String> getParameterNames() { return this.parameterNames; } public String getStringRepresentation() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getStringRepresentation(); } }
if (this.parameterNames == null || this.parameterNames.size() == 0) { return this.fragmentName; } return this.fragmentName + " " + FRAGMENT_SIGNATURE_PARAMETERS_START + StringUtils.join(this.parameterNames, ',') + FRAGMENT_SIGNATURE_PARAMETERS_END;
323
94
417
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/FragmentSignatureUtils.java
FragmentSignatureUtils
processParameters
class FragmentSignatureUtils { private static final char FRAGMENT_SIGNATURE_PARAMETERS_START = '('; private static final char FRAGMENT_SIGNATURE_PARAMETERS_END = ')'; public static FragmentSignature parseFragmentSignature(final IEngineConfiguration configuration, final String input) { Validate.notNull(configuration, "Configuration cannot be null"); // Processing context CAN (and many times will, in fact) be null! - no variables can be used in signatures. Validate.notNull(input, "Input cannot be null"); // No need to preprocess, also no need to have a context, because fragment signatures are // token-only based (no expressions allowed). if (configuration != null) { final FragmentSignature cachedFragmentSignature = ExpressionCache.getFragmentSignatureFromCache(configuration, input); if (cachedFragmentSignature != null) { return cachedFragmentSignature; } } final FragmentSignature fragmentSignature = FragmentSignatureUtils.internalParseFragmentSignature(input.trim()); if (fragmentSignature == null) { throw new TemplateProcessingException("Could not parse as fragment signature: \"" + input + "\""); } if (configuration != null) { ExpressionCache.putFragmentSignatureIntoCache(configuration, input, fragmentSignature); } return fragmentSignature; } static FragmentSignature internalParseFragmentSignature(final String input) { if (StringUtils.isEmptyOrWhitespace(input)) { return null; } final int parameterStart = input.lastIndexOf(FRAGMENT_SIGNATURE_PARAMETERS_START); final int parameterEnd = input.lastIndexOf(FRAGMENT_SIGNATURE_PARAMETERS_END); if (parameterStart != -1 && parameterStart >= parameterEnd) { return null; } final String fragmentName = (parameterStart == -1? input.trim() : input.substring(0, parameterStart).trim()); final String parameters = (parameterStart == -1? null : input.substring(parameterStart + 1, input.length() - 1)); final List<String> parameterNames; if (parameters != null) { final String[] parameterArray = StringUtils.split(parameters, ","); if (parameterArray.length == 0) { parameterNames = null; } else { parameterNames = new ArrayList<String>(parameterArray.length + 2); for (final String parameter : parameterArray) { parameterNames.add(parameter.trim()); } } } else { parameterNames = null; } return new FragmentSignature(fragmentName, parameterNames); } /** * <p> * Processes a set of parameters that have been specified for a fragment signature. * </p> * <p> * This processing matches the specified parameters against the ones in the signature, allowing the specified * ones (usually coming from a fragment selection like {@code th:include}) to be nameless, so that their values * are matched to their corresponding variable name during this parameter processing operation. * </p> * <p> * The resulting processed parameters are typically applied as local variables to the nodes of a * selected fragment. * </p> * * @param fragmentSignature the signature parameters should be processed against * @param specifiedParameters the set of specified parameters * @param parametersAreSynthetic whether the parameter names in the specifiedParameters map are synthetic or not * @return the processed set of parameters, ready to be applied as local variables to the fragment's nodes. */ public static Map<String,Object> processParameters( final FragmentSignature fragmentSignature, final Map<String, Object> specifiedParameters, final boolean parametersAreSynthetic) {<FILL_FUNCTION_BODY>} static String getSyntheticParameterNameForIndex(final int i) { return FragmentExpression.UNNAMED_PARAMETERS_PREFIX + i; } private FragmentSignatureUtils() { super(); } }
Validate.notNull(fragmentSignature, "Fragment signature cannot be null"); if (specifiedParameters == null || specifiedParameters.size() == 0) { if (fragmentSignature.hasParameters()) { // Fragment signature requires parameters, but we haven't specified them! throw new TemplateProcessingException( "Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " + "declares parameters, but fragment selection did not specify any parameters."); } return null; } if (parametersAreSynthetic && !fragmentSignature.hasParameters()) { throw new TemplateProcessingException( "Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " + "declares no parameters, but fragment selection did specify parameters in a synthetic manner " + "(without names), which is not correct due to the fact parameters cannot be assigned names " + "unless signature specifies these names."); } if (parametersAreSynthetic) { // No need to match parameter names, just apply the ones from the signature final List<String> signatureParameterNames = fragmentSignature.getParameterNames(); if (signatureParameterNames.size() != specifiedParameters.size()) { throw new TemplateProcessingException( "Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " + "declares " + signatureParameterNames.size() + " parameters, but fragment selection specifies " + specifiedParameters.size() + " parameters. Fragment selection does not correctly match."); } final Map<String,Object> processedParameters = new HashMap<String, Object>(signatureParameterNames.size() + 1, 1.0f); int index = 0; for (final String parameterName : signatureParameterNames) { final String syntheticParameterName = getSyntheticParameterNameForIndex(index++); final Object parameterValue = specifiedParameters.get(syntheticParameterName); processedParameters.put(parameterName, parameterValue); } return processedParameters; } if (!fragmentSignature.hasParameters()) { // Parameters in fragment selection are not synthetic, and fragment signature has no parameters, // so we just use the "specified parameters". return specifiedParameters; } // Parameters are not synthetic and signature does specify parameters, so their names should match (all // the parameters specified at the fragment signature should be specified at the fragment selection, // though fragment selection can specify more parameters, not present at the signature. final List<String> parameterNames = fragmentSignature.getParameterNames(); for (final String parameterName : parameterNames) { if (!specifiedParameters.containsKey(parameterName)) { throw new TemplateProcessingException( "Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " + "declares parameter \"" + parameterName + "\", which is not specified at the fragment " + "selection."); } } return specifiedParameters;
1,064
742
1,806
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/GenericTokenExpression.java
GenericTokenExpression
parseGenericTokenExpression
class GenericTokenExpression extends Token { private static final Logger logger = LoggerFactory.getLogger(GenericTokenExpression.class); private static final long serialVersionUID = 7913229642187691263L; GenericTokenExpression(final String value) { super(value); } @Override public String toString() { return getStringRepresentation(); } public static GenericTokenExpression parseGenericTokenExpression(final String input) {<FILL_FUNCTION_BODY>} static Object executeGenericTokenExpression( final IExpressionContext context, final GenericTokenExpression expression, final StandardExpressionExecutionContext expContext) { if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating generic token: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } return expression.getValue(); } }
if (input == null) { return null; } final int inputLen = input.length(); for (int i = 0; i < inputLen; i++) { if (!isTokenChar(input, i)) { return null; } } return new GenericTokenExpression(input);
263
84
347
<methods>public java.lang.String getStringRepresentation() ,public java.lang.Object getValue() ,public static boolean isTokenChar(java.lang.String, int) ,public java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object value
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/GreaterLesserExpression.java
GreaterLesserExpression
isLeftAllowed
class GreaterLesserExpression extends BinaryOperationExpression { private static final long serialVersionUID = 3488922833645278122L; protected static final String GREATER_THAN_OPERATOR = ">"; protected static final String GREATER_OR_EQUAL_TO_OPERATOR = ">="; protected static final String LESS_THAN_OPERATOR = "<"; protected static final String LESS_OR_EQUAL_TO_OPERATOR = "<="; protected static final String GREATER_THAN_OPERATOR_2 = "gt"; protected static final String GREATER_OR_EQUAL_TO_OPERATOR_2 = "ge"; protected static final String LESS_THAN_OPERATOR_2 = "lt"; protected static final String LESS_OR_EQUAL_TO_OPERATOR_2 = "le"; static final String[] OPERATORS = new String[] { GREATER_THAN_OPERATOR, GREATER_OR_EQUAL_TO_OPERATOR, LESS_THAN_OPERATOR, LESS_OR_EQUAL_TO_OPERATOR, GREATER_THAN_OPERATOR_2, GREATER_OR_EQUAL_TO_OPERATOR_2, LESS_THAN_OPERATOR_2, LESS_OR_EQUAL_TO_OPERATOR_2}; private static final boolean[] LENIENCIES = new boolean[] { false, false, false, false, false, false, false, false }; @SuppressWarnings("unchecked") private static final Class<? extends BinaryOperationExpression>[] OPERATOR_CLASSES = (Class<? extends BinaryOperationExpression>[]) new Class<?>[] { GreaterThanExpression.class, GreaterOrEqualToExpression.class, LessThanExpression.class, LessOrEqualToExpression.class, GreaterThanExpression.class, GreaterOrEqualToExpression.class, LessThanExpression.class, LessOrEqualToExpression.class}; private static final Method LEFT_ALLOWED_METHOD; private static final Method RIGHT_ALLOWED_METHOD; static { try { LEFT_ALLOWED_METHOD = GreaterLesserExpression.class.getDeclaredMethod("isLeftAllowed", IStandardExpression.class); RIGHT_ALLOWED_METHOD = GreaterLesserExpression.class.getDeclaredMethod("isRightAllowed", IStandardExpression.class); } catch (final NoSuchMethodException e) { throw new ExceptionInInitializerError(e); } } protected GreaterLesserExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } static boolean isRightAllowed(final IStandardExpression right) { return right != null && !(right instanceof Token && !(right instanceof NumberTokenExpression || right instanceof GenericTokenExpression)); } static boolean isLeftAllowed(final IStandardExpression left) {<FILL_FUNCTION_BODY>} protected static ExpressionParsingState composeGreaterLesserExpression( final ExpressionParsingState state, final int nodeIndex) { return composeBinaryOperationExpression( state, nodeIndex, OPERATORS, LENIENCIES, OPERATOR_CLASSES, LEFT_ALLOWED_METHOD, RIGHT_ALLOWED_METHOD); } }
return left != null && !(left instanceof Token && !(left instanceof NumberTokenExpression || left instanceof GenericTokenExpression));
904
33
937
<methods>public org.thymeleaf.standard.expression.IStandardExpression getLeft() ,public org.thymeleaf.standard.expression.IStandardExpression getRight() <variables>private final non-sealed org.thymeleaf.standard.expression.IStandardExpression left,private final non-sealed org.thymeleaf.standard.expression.IStandardExpression right,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/GreaterOrEqualToExpression.java
GreaterOrEqualToExpression
executeGreaterOrEqualTo
class GreaterOrEqualToExpression extends GreaterLesserExpression { private static final long serialVersionUID = 4318966518910979010L; private static final Logger logger = LoggerFactory.getLogger(GreaterOrEqualToExpression.class); public GreaterOrEqualToExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(GREATER_OR_EQUAL_TO_OPERATOR); } @SuppressWarnings("unchecked") static Object executeGreaterOrEqualTo( final IExpressionContext context, final GreaterOrEqualToExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) != -1); } else { if (leftValue != null && rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) >= 0); } else { throw new TemplateProcessingException( "Cannot execute GREATER OR EQUAL TO from Expression \"" + expression.getStringRepresentation() + "\". Left is \"" + leftValue + "\", right is \"" + rightValue + "\""); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating GREATER OR EQUAL TO expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
236
439
675
<methods><variables>protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String GREATER_THAN_OPERATOR,protected static final java.lang.String GREATER_THAN_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String LESS_THAN_OPERATOR,protected static final java.lang.String LESS_THAN_OPERATOR_2,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/GreaterThanExpression.java
GreaterThanExpression
executeGreaterThan
class GreaterThanExpression extends GreaterLesserExpression { private static final long serialVersionUID = -1416343400122380675L; private static final Logger logger = LoggerFactory.getLogger(GreaterThanExpression.class); public GreaterThanExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(GREATER_THAN_OPERATOR); } @SuppressWarnings("unchecked") static Object executeGreaterThan( final IExpressionContext context, final GreaterThanExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating GREATER THAN expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null || rightValue == null) { throw new TemplateProcessingException( "Cannot execute GREATER THAN comparison: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\""); } leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) == 1); } else { if (leftValue != null && rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) > 0); } else { throw new TemplateProcessingException( "Cannot execute GREATER THAN from Expression \"" + expression.getStringRepresentation() + "\". Left is \"" + leftValue + "\", right is \"" + rightValue + "\""); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating GREATER THAN expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
227
566
793
<methods><variables>protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String GREATER_THAN_OPERATOR,protected static final java.lang.String GREATER_THAN_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String LESS_THAN_OPERATOR,protected static final java.lang.String LESS_THAN_OPERATOR_2,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/LessOrEqualToExpression.java
LessOrEqualToExpression
executeLessOrEqualTo
class LessOrEqualToExpression extends GreaterLesserExpression { private static final long serialVersionUID = 7042174616566611488L; private static final Logger logger = LoggerFactory.getLogger(LessOrEqualToExpression.class); public LessOrEqualToExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(LESS_OR_EQUAL_TO_OPERATOR); } @SuppressWarnings("unchecked") static Object executeLessOrEqualTo( final IExpressionContext context, final LessOrEqualToExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating LESS OR EQUAL TO expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null || rightValue == null) { throw new TemplateProcessingException( "Cannot execute LESS OR EQUAL TO comparison: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\""); } leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) != 1); } else { if (leftValue != null && rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) <= 0); } else { throw new TemplateProcessingException( "Cannot execute LESS OR EQUAL TO from Expression \"" + expression.getStringRepresentation() + "\". Left is \"" + leftValue + "\", right is \"" + rightValue + "\""); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating LESS OR EQUAL TO expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
237
575
812
<methods><variables>protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String GREATER_THAN_OPERATOR,protected static final java.lang.String GREATER_THAN_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String LESS_THAN_OPERATOR,protected static final java.lang.String LESS_THAN_OPERATOR_2,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/LessThanExpression.java
LessThanExpression
executeLessThan
class LessThanExpression extends GreaterLesserExpression { private static final long serialVersionUID = 6097188129113613164L; private static final Logger logger = LoggerFactory.getLogger(LessThanExpression.class); public LessThanExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(LESS_THAN_OPERATOR); } @SuppressWarnings("unchecked") static Object executeLessThan( final IExpressionContext context, final LessThanExpression expression, final StandardExpressionExecutionContext expContext) {<FILL_FUNCTION_BODY>} }
if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating LESS THAN expression: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation()); } Object leftValue = expression.getLeft().execute(context, expContext); Object rightValue = expression.getRight().execute(context, expContext); if (leftValue == null || rightValue == null) { throw new TemplateProcessingException( "Cannot execute LESS THAN comparison: operands are \"" + LiteralValue.unwrap(leftValue) + "\" and \"" + LiteralValue.unwrap(rightValue) + "\""); } leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtils.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtils.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) == -1); } else { if (leftValue != null && rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) < 0); } else { throw new TemplateProcessingException( "Cannot execute LESS THAN from Expression \"" + expression.getStringRepresentation() + "\". Left is \"" + leftValue + "\", right is \"" + rightValue + "\""); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating LESS THAN expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result;
224
563
787
<methods><variables>protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String GREATER_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String GREATER_THAN_OPERATOR,protected static final java.lang.String GREATER_THAN_OPERATOR_2,private static final non-sealed java.lang.reflect.Method LEFT_ALLOWED_METHOD,private static final boolean[] LENIENCIES,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR,protected static final java.lang.String LESS_OR_EQUAL_TO_OPERATOR_2,protected static final java.lang.String LESS_THAN_OPERATOR,protected static final java.lang.String LESS_THAN_OPERATOR_2,static final java.lang.String[] OPERATORS,private static final Class<? extends org.thymeleaf.standard.expression.BinaryOperationExpression>[] OPERATOR_CLASSES,private static final non-sealed java.lang.reflect.Method RIGHT_ALLOWED_METHOD,private static final long serialVersionUID
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/LiteralSubstitutionUtil.java
LiteralSubstitutionUtil
performLiteralSubstitution
class LiteralSubstitutionUtil { private static final char LITERAL_SUBSTITUTION_DELIMITER = '|'; /* * The goal here is to convert literal substitution expressions (|...|) into a concatenation of variable and/or * literal expressions. * * Example: * * # ------------------------------------------------------------ * %CONTEXT * onevar = 'Hello' * twovar = 'World' * # ------------------------------------------------------------ * %INPUT * <p th:text="|${onevar} ${twovar}|">...</p> * # ------------------------------------------------------------ * %OUTPUT * <p>Hello World</p> * # ------------------------------------------------------------ * * For this, the input text is scanned before simple expressions are decomposed and they are replaced by a series * of concatenations of literals and variables. * * So: |${onevar} ${twovar}| --> ${onevar} + ' ' + ${twovar} * * NOTE literal substitution expressions do not allow literals, numeric/boolean tokens, conditional expressions, etc. * */ static String performLiteralSubstitution(final String input) {<FILL_FUNCTION_BODY>} private LiteralSubstitutionUtil() { super(); } }
if (input == null) { return null; } StringBuilder strBuilder = null; boolean inLiteralSubstitution = false; boolean inLiteralSubstitutionInsertion = false; int literalSubstitutionIndex = -1; int expLevel = 0; boolean inLiteral = false; boolean inNothing = true; final int inputLen = input.length(); for (int i = 0; i < inputLen; i++) { final char c = input.charAt(i); if (c == LITERAL_SUBSTITUTION_DELIMITER && !inLiteralSubstitution && inNothing) { if (strBuilder == null) { strBuilder = new StringBuilder(inputLen + 20); strBuilder.append(input,0,i); } inLiteralSubstitution = true; literalSubstitutionIndex = i; } else if (c == LITERAL_SUBSTITUTION_DELIMITER && inLiteralSubstitution && inNothing) { if ((i - literalSubstitutionIndex) == 1) { // This was an empty literal substitution, which we are not going to process so that it // cannot be used to mangle in the parsing, interpretation and validity checks of other // expressions. strBuilder .append(LITERAL_SUBSTITUTION_DELIMITER) .append(LITERAL_SUBSTITUTION_DELIMITER); } else if (inLiteralSubstitutionInsertion) { strBuilder.append('\''); inLiteralSubstitutionInsertion = false; } inLiteralSubstitution = false; literalSubstitutionIndex = -1; } else if (inNothing && (c == VariableExpression.SELECTOR || c == SelectionVariableExpression.SELECTOR || c == MessageExpression.SELECTOR || c == LinkExpression.SELECTOR) && (i + 1 < inputLen && input.charAt(i+1) == SimpleExpression.EXPRESSION_START_CHAR)) { // We are opening an expression if (inLiteralSubstitution && inLiteralSubstitutionInsertion) { strBuilder.append("\' + "); inLiteralSubstitutionInsertion = false; } else if (inLiteralSubstitution && i > 0 && input.charAt(i - 1) == SimpleExpression.EXPRESSION_END_CHAR) { // This expression is right after another one, with no characters between them strBuilder.append(" + \'\' + "); } if (strBuilder != null) { strBuilder.append(c); strBuilder.append(SimpleExpression.EXPRESSION_START_CHAR); } expLevel = 1; i++; // This avoids the following '{', which we already know is there, to increment expLevel twice inNothing = false; } else if (expLevel == 1 && c == SimpleExpression.EXPRESSION_END_CHAR) { // We are closing an expression if (strBuilder != null) { strBuilder.append(SimpleExpression.EXPRESSION_END_CHAR); } expLevel = 0; inNothing = true; } else if (expLevel > 0 && c == SimpleExpression.EXPRESSION_START_CHAR) { // We are in an expression. This is needed for correct nesting/unnesting of expressions if (strBuilder != null) { strBuilder.append(SimpleExpression.EXPRESSION_START_CHAR); } expLevel++; } else if (expLevel > 1 && c == SimpleExpression.EXPRESSION_END_CHAR) { // We are in an expression. This is needed for correct nesting/unnesting of expressions if (strBuilder != null) { strBuilder.append(SimpleExpression.EXPRESSION_END_CHAR); } expLevel--; } else if (expLevel > 0) { // We are in an expression and not closing it, so just add the char if (strBuilder != null) { strBuilder.append(c); } } else if (inNothing && !inLiteralSubstitution && c == TextLiteralExpression.DELIMITER && !TextLiteralExpression.isDelimiterEscaped(input, i)) { // We enter a first-level text literal. We should not process any |'s inside inNothing = false; inLiteral = true; if (strBuilder != null) { strBuilder.append(c); } } else if (inLiteral && !inLiteralSubstitution && c == TextLiteralExpression.DELIMITER && !TextLiteralExpression.isDelimiterEscaped(input, i)) { inLiteral = false; inNothing = true; if (strBuilder != null) { strBuilder.append(c); } } else if (inLiteralSubstitution && inNothing) { // This char is not starting an expresion, but it is inside a literal substitution, so add it // (and start an insertion if needed) if (!inLiteralSubstitutionInsertion) { if (input.charAt(i - 1) != LITERAL_SUBSTITUTION_DELIMITER) { strBuilder.append(" + "); } strBuilder.append('\''); inLiteralSubstitutionInsertion = true; } if (c == TextLiteralExpression.DELIMITER) { strBuilder.append('\\'); } else if (c == TextLiteralExpression.ESCAPE_PREFIX) { strBuilder.append('\\'); } strBuilder.append(c); } else { // No literal substitution or anything. Just add the char if (strBuilder != null) { strBuilder.append(c); } } } if (strBuilder == null) { return input; } return strBuilder.toString();
354
1,514
1,868
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/standard/expression/LiteralValue.java
LiteralValue
unwrap
class LiteralValue implements Serializable { /* * This class is internally used during expression parsing in order to avoid * the interpretation of text literals like '4' or '2.' as numbers in * arithmetic operations. */ private static final long serialVersionUID = -4769586410724418224L; private final String value; public LiteralValue(final String value) { super(); this.value = value; } public String getValue() { return this.value; } public static Object unwrap(final Object obj) {<FILL_FUNCTION_BODY>} }
if (obj == null) { return null; } if (obj instanceof LiteralValue) { return ((LiteralValue)obj).getValue(); } return obj;
190
50
240
<no_super_class>