ottobackwards commented on a change in pull request #3850: NIFI-6398 Added the
'replace first' and 'replace all' strategy to ReplaceText
URL: https://github.com/apache/nifi/pull/3850#discussion_r340660981
##########
File path:
nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ReplaceText.java
##########
@@ -673,6 +689,63 @@ public boolean isAllDataBufferedForEntireText() {
}
}
+ /**
+ * Replaces the first occurrence of a search value within a flow file with
the given replacement value. It can
+ * either be done line by line, meaning that the first occurrence within a
line gets replaced, or for the entire
+ * text, where only the very first occurrence is replaced.
+ */
+ private class ReplaceFirst implements ReplacementStrategyExecutor {
+ @Override
+ public FlowFile replace(FlowFile flowFile, ProcessSession session,
ProcessContext context, String evaluateMode,
+ Charset charset, int maxBufferSize) {
+ final String replacementValue =
context.getProperty(REPLACEMENT_VALUE)
+ .evaluateAttributeExpressions(flowFile).getValue();
+ final AttributeValueDecorator quotedAttributeDecorator =
Pattern::quote;
+ final String searchValue = context.getProperty(SEARCH_VALUE)
+ .evaluateAttributeExpressions(flowFile,
quotedAttributeDecorator).getValue();
+
+ if (evaluateMode.equalsIgnoreCase(ENTIRE_TEXT)) {
+ flowFile = session.write(flowFile, (in, out) -> out.write(new
String(IOUtils.toByteArray(in))
+ .replaceFirst(searchValue,
replacementValue).getBytes(charset)));
+ } else {
+ flowFile = session.write(flowFile, new
StreamReplaceCallback(charset, maxBufferSize,
+
context.getProperty(LINE_BY_LINE_EVALUATION_MODE).getValue(),
+ (bw, oneLine) ->
bw.write(oneLine.replaceFirst(searchValue, replacementValue))));
+ }
+
+ return flowFile;
+ }
+
+ @Override
+ public boolean isAllDataBufferedForEntireText() {
+ return true;
+ }
+ }
+
+ /**
+ * Replaces all occurrences of a search value within a flow file with the
given replacement value.
+ * The evaluation mode doesn't matter, because the result would be the
same for both line-by-line or entire text.
+ */
+ private class ReplaceAll implements ReplacementStrategyExecutor {
+ @Override
+ public FlowFile replace(FlowFile flowFile, ProcessSession session,
ProcessContext context, String evaluateMode,
+ Charset charset, int maxBufferSize) {
+ final String replacementValue =
context.getProperty(REPLACEMENT_VALUE)
+ .evaluateAttributeExpressions(flowFile).getValue();
Review comment:
According to the java documentation, you may need to quote the replacement
text as well.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services