This is an automated email from the ASF dual-hosted git repository.
exceptionfactory pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/main by this push:
new 14a79448b5e NIFI-13591 Added support for JSON Lines to
JSLTTransformJSON (#11141)
14a79448b5e is described below
commit 14a79448b5eb612d9a19b2029ccf6a618ebcfd4a
Author: dan-s1 <[email protected]>
AuthorDate: Tue Apr 21 14:57:53 2026 -0400
NIFI-13591 Added support for JSON Lines to JSLTTransformJSON (#11141)
Signed-off-by: David Handermann <[email protected]>
---
.../nifi/processors/jslt/JSLTTransformJSON.java | 248 +++++++++++++--------
.../processors/jslt/TestJSLTTransformJSON.java | 76 +++++--
2 files changed, 218 insertions(+), 106 deletions(-)
diff --git
a/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/main/java/org/apache/nifi/processors/jslt/JSLTTransformJSON.java
b/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/main/java/org/apache/nifi/processors/jslt/JSLTTransformJSON.java
index acd1fe7b2e6..191a465b44f 100644
---
a/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/main/java/org/apache/nifi/processors/jslt/JSLTTransformJSON.java
+++
b/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/main/java/org/apache/nifi/processors/jslt/JSLTTransformJSON.java
@@ -65,6 +65,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -72,8 +73,6 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
-import static
org.apache.nifi.processors.jslt.JSLTTransformJSON.TransformationStrategy.EACH_OBJECT;
-import static
org.apache.nifi.processors.jslt.JSLTTransformJSON.TransformationStrategy.ENTIRE_FLOWFILE;
@SideEffectFree
@SupportsBatching
@@ -86,6 +85,63 @@ import static
org.apache.nifi.processors.jslt.JSLTTransformJSON.TransformationSt
+ "fails, the original FlowFile is routed to the 'failure'
relationship.")
public class JSLTTransformJSON extends AbstractProcessor {
+ enum InputFormat implements DescribedValue {
+ FLOW_FILE("FlowFile", "Transformation applied to FlowFile content
containing JSON"),
+ JSON_LINES("JSON Lines", "Transformation applied to each line of
FlowFile content containing JSON Lines or NDJSON");
+
+ private final String displayName;
+ private final String description;
+
+ InputFormat(final String displayName, final String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ @Override
+ public String getValue() {
+ return name();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ enum TransformationStrategy implements DescribedValue {
+ ENTIRE_FLOWFILE("Entire FlowFile", "Apply transformation to entire
FlowFile content JSON"),
+ EACH_OBJECT("Each JSON Object", "Apply transformation to each JSON
object in an array");
+
+ private final String displayName;
+
+ private final String description;
+
+ TransformationStrategy(final String displayName, final String
description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ @Override
+ public String getValue() {
+ return name();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+ }
+
public static final String JSLT_FILTER_DEFAULT = ". != null and . != {}
and . != []";
public static final PropertyDescriptor JSLT_TRANSFORM = new
PropertyDescriptor.Builder()
@@ -98,12 +154,21 @@ public class JSLTTransformJSON extends AbstractProcessor {
.required(true)
.build();
+ public static final PropertyDescriptor INPUT_FORMAT = new
PropertyDescriptor.Builder()
+ .name("Input Format")
+ .description("Specifies the expected format of FlowFile content
containing one or more JSON elements")
+ .allowableValues(InputFormat.class)
+ .defaultValue(InputFormat.FLOW_FILE)
+ .required(true)
+ .build();
+
public static final PropertyDescriptor TRANSFORMATION_STRATEGY = new
PropertyDescriptor.Builder()
.name("Transformation Strategy")
.description("Whether to apply the JSLT transformation to the
entire FlowFile contents or each JSON object in the root-level array")
.required(true)
.allowableValues(TransformationStrategy.class)
- .defaultValue(EACH_OBJECT.getValue())
+ .defaultValue(TransformationStrategy.EACH_OBJECT)
+ .dependsOn(INPUT_FORMAT, InputFormat.FLOW_FILE)
.build();
public static final PropertyDescriptor PRETTY_PRINT = new
PropertyDescriptor.Builder()
@@ -112,6 +177,7 @@ public class JSLTTransformJSON extends AbstractProcessor {
.required(true)
.allowableValues("true", "false")
.defaultValue("false")
+ .dependsOn(INPUT_FORMAT, InputFormat.FLOW_FILE)
.build();
public static final PropertyDescriptor TRANSFORM_CACHE_SIZE = new
PropertyDescriptor.Builder()
@@ -146,6 +212,7 @@ public class JSLTTransformJSON extends AbstractProcessor {
private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS =
List.of(
JSLT_TRANSFORM,
+ INPUT_FORMAT,
TRANSFORMATION_STRATEGY,
PRETTY_PRINT,
TRANSFORM_CACHE_SIZE,
@@ -237,71 +304,19 @@ public class JSLTTransformJSON extends AbstractProcessor {
return;
}
- final TransformationStrategy transformationStrategy =
TransformationStrategy.valueOf(context.getProperty(TRANSFORMATION_STRATEGY).getValue());
- final StopWatch stopWatch = new StopWatch(true);
-
final PropertyValue transformProperty =
context.getProperty(JSLT_TRANSFORM);
+ final String transform = readTransform(transformProperty, original);
final PropertyValue filterProperty =
context.getProperty(RESULT_FILTER);
- FlowFile transformed;
- final JsonFactory jsonFactory = new JsonFactory();
+ final Expression jsltExpression = transformCache.get(transform,
currString -> getJstlExpression(transform, filterProperty.getValue()));
+ final InputFormat inputFormat =
context.getProperty(INPUT_FORMAT).asAllowableValue(InputFormat.class);
+ final StopWatch stopWatch = new StopWatch(true);
try {
- final String transform = readTransform(transformProperty,
original);
- final Expression jsltExpression = transformCache.get(transform,
currString -> getJstlExpression(transform, filterProperty.getValue()));
- final boolean prettyPrint =
context.getProperty(PRETTY_PRINT).asBoolean();
-
- transformed = session.write(original, (inputStream, outputStream)
-> {
- boolean topLevelArray = false;
- JsonParser jsonParser;
- JsonNode firstJsonNode;
- if (EACH_OBJECT.equals(transformationStrategy)) {
- jsonParser = jsonFactory.createParser(inputStream);
- jsonParser.setCodec(JSON_OBJECT_MAPPER);
-
- JsonToken token = jsonParser.nextToken();
- if (token == JsonToken.START_ARRAY) {
- token = jsonParser.nextToken(); // advance to
START_OBJECT token
- topLevelArray = true;
- }
- if (token == JsonToken.START_OBJECT) { // could be
END_ARRAY also
- firstJsonNode = jsonParser.readValueAsTree();
- } else {
- firstJsonNode = null;
- }
- } else {
- firstJsonNode = readJson(inputStream);
- jsonParser = null; // This will not be used when applying
the transform to the entire FlowFile
- }
-
- final ObjectWriter writer = prettyPrint ?
JSON_OBJECT_MAPPER.writerWithDefaultPrettyPrinter() :
JSON_OBJECT_MAPPER.writer();
- final JsonGenerator jsonGenerator =
writer.createGenerator(outputStream);
-
- Object outputObject;
- JsonNode nextNode;
+ final FlowFile transformed = switch (inputFormat) {
+ case FLOW_FILE -> transformFlowFile(jsltExpression, original,
context, session);
+ case JSON_LINES -> transformJsonLines(jsltExpression,
original, session);
+ };
- if (topLevelArray) {
- jsonGenerator.writeStartArray();
- }
- nextNode = firstJsonNode;
- do {
- final JsonNode transformedJson =
jsltExpression.apply(nextNode);
- if (transformedJson == null || transformedJson.isNull()) {
- getLogger().warn("JSLT Transform resulted in no data
{}", original);
- outputObject = null;
- } else {
- outputObject = transformedJson;
- }
- if (outputObject != null) {
- jsonGenerator.writeObject(outputObject);
- }
- } while ((nextNode = getNextJsonNode(transformationStrategy,
jsonParser)) != null);
- if (topLevelArray) {
- jsonGenerator.writeEndArray();
- }
- jsonGenerator.flush();
- });
-
- transformed = session.putAttribute(transformed,
CoreAttributes.MIME_TYPE.key(), "application/json");
session.transfer(transformed, REL_SUCCESS);
session.getProvenanceReporter().modifyContent(transformed,
"Modified With " + transform, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
stopWatch.stop();
@@ -312,6 +327,66 @@ public class JSLTTransformJSON extends AbstractProcessor {
}
}
+ private FlowFile transformFlowFile(final Expression jsltExpression, final
FlowFile original, final ProcessContext context, final ProcessSession session) {
+ final TransformationStrategy transformationStrategy =
TransformationStrategy.valueOf(context.getProperty(TRANSFORMATION_STRATEGY).getValue());
+ final boolean prettyPrint =
context.getProperty(PRETTY_PRINT).asBoolean();
+ final JsonFactory jsonFactory = new JsonFactory();
+
+ FlowFile transformed = session.write(original, (inputStream,
outputStream) -> {
+ boolean topLevelArray = false;
+ JsonParser jsonParser;
+ JsonNode firstJsonNode;
+ if
(TransformationStrategy.EACH_OBJECT.equals(transformationStrategy)) {
+ jsonParser = jsonFactory.createParser(inputStream);
+ jsonParser.setCodec(JSON_OBJECT_MAPPER);
+
+ JsonToken token = jsonParser.nextToken();
+ if (token == JsonToken.START_ARRAY) {
+ token = jsonParser.nextToken(); // advance to START_OBJECT
token
+ topLevelArray = true;
+ }
+ if (token == JsonToken.START_OBJECT) { // could be END_ARRAY
also
+ firstJsonNode = jsonParser.readValueAsTree();
+ } else {
+ firstJsonNode = null;
+ }
+ } else {
+ firstJsonNode = readJson(inputStream);
+ jsonParser = null; // This will not be used when applying the
transform to the entire FlowFile
+ }
+
+ final ObjectWriter writer = prettyPrint ?
JSON_OBJECT_MAPPER.writerWithDefaultPrettyPrinter() :
JSON_OBJECT_MAPPER.writer();
+ final JsonGenerator jsonGenerator =
writer.createGenerator(outputStream);
+
+ Object outputObject;
+ JsonNode nextNode;
+
+ if (topLevelArray) {
+ jsonGenerator.writeStartArray();
+ }
+ nextNode = firstJsonNode;
+ do {
+ final JsonNode transformedJson =
jsltExpression.apply(nextNode);
+ if (transformedJson == null || transformedJson.isNull()) {
+ getLogger().warn("JSLT Transform resulted in no data {}",
original);
+ outputObject = null;
+ } else {
+ outputObject = transformedJson;
+ }
+ if (outputObject != null) {
+ jsonGenerator.writeObject(outputObject);
+ }
+ } while ((nextNode = getNextJsonNode(transformationStrategy,
jsonParser)) != null);
+ if (topLevelArray) {
+ jsonGenerator.writeEndArray();
+ }
+ jsonGenerator.flush();
+ });
+
+ transformed = session.putAttribute(transformed,
CoreAttributes.MIME_TYPE.key(), "application/json");
+ return transformed;
+ }
+
@OnStopped
@OnShutdown
public void onStopped() {
@@ -361,9 +436,9 @@ public class JSLTTransformJSON extends AbstractProcessor {
}
}
- protected JsonNode getNextJsonNode(final TransformationStrategy
transformationStrategy, final JsonParser jsonParser) throws IOException {
+ private JsonNode getNextJsonNode(final TransformationStrategy
transformationStrategy, final JsonParser jsonParser) throws IOException {
- if (ENTIRE_FLOWFILE.equals(transformationStrategy)) {
+ if
(TransformationStrategy.ENTIRE_FLOWFILE.equals(transformationStrategy)) {
return null;
}
return getJsonNode(jsonParser);
@@ -389,32 +464,25 @@ public class JSLTTransformJSON extends AbstractProcessor {
}
}
- enum TransformationStrategy implements DescribedValue {
- ENTIRE_FLOWFILE("Entire FlowFile", "Apply transformation to entire
FlowFile content JSON"),
- EACH_OBJECT("Each JSON Object", "Apply transformation each JSON Object
in an array");
-
- private final String displayName;
-
- private final String description;
-
- TransformationStrategy(final String displayName, final String
description) {
- this.displayName = displayName;
- this.description = description;
- }
-
- @Override
- public String getValue() {
- return name();
- }
+ private FlowFile transformJsonLines(final Expression jsltExpression, final
FlowFile original, final ProcessSession session) {
+ final ObjectWriter writer =
JSON_OBJECT_MAPPER.writer().withRootValueSeparator("\n");
+ FlowFile transformed = session.write(original, (inputStream,
outputStream) -> {
+ try (final BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream, StandardCharsets.UTF_8));
+ final JsonGenerator jsonGenerator =
writer.createGenerator(outputStream)) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (line.isBlank()) {
+ continue;
+ }
- @Override
- public String getDisplayName() {
- return displayName;
- }
+ final JsonNode jsonNode =
JSON_OBJECT_MAPPER.readTree(line);
+ final JsonNode transformedJson =
jsltExpression.apply(jsonNode);
+ jsonGenerator.writeObject(transformedJson);
+ }
+ }
+ });
- @Override
- public String getDescription() {
- return description;
- }
+ transformed = session.putAttribute(transformed,
CoreAttributes.MIME_TYPE.key(), "application/jsonl");
+ return transformed;
}
}
diff --git
a/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/test/java/org/apache/nifi/processors/jslt/TestJSLTTransformJSON.java
b/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/test/java/org/apache/nifi/processors/jslt/TestJSLTTransformJSON.java
index 12180b7da52..d7adf7f2df8 100644
---
a/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/test/java/org/apache/nifi/processors/jslt/TestJSLTTransformJSON.java
+++
b/nifi-extension-bundles/nifi-jslt-bundle/nifi-jslt-processors/src/test/java/org/apache/nifi/processors/jslt/TestJSLTTransformJSON.java
@@ -18,21 +18,26 @@ package org.apache.nifi.processors.jslt;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.nifi.stream.io.StreamUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
+import java.util.stream.Stream;
import static
org.apache.nifi.processors.jslt.JSLTTransformJSON.TransformationStrategy.ENTIRE_FLOWFILE;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -40,12 +45,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestJSLTTransformJSON {
private TestRunner runner = TestRunners.newTestRunner(new
JSLTTransformJSON());
-
- private static final ObjectMapper objectMapper = new ObjectMapper();
+ private static final Path RESOURCE_DIR = Paths.get("src/test/resources");
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@BeforeEach
public void setup() {
- runner = TestRunners.newTestRunner(new JSLTTransformJSON());
+ runner = TestRunners.newTestRunner(JSLTTransformJSON.class);
}
@Test
@@ -64,7 +69,6 @@ public class TestJSLTTransformJSON {
@Test
public void testInvalidJSLTTransform() {
- final TestRunner runner = TestRunners.newTestRunner(new
JSLTTransformJSON());
final String invalidTransform = "invalid";
runner.setProperty(JSLTTransformJSON.JSLT_TRANSFORM, invalidTransform);
runner.assertNotValid();
@@ -169,6 +173,42 @@ public class TestJSLTTransformJSON {
runTransform("inputWithNull.json", "simpleTransform.json",
"simpleOutputWithNull.json");
}
+ @ParameterizedTest
+ @MethodSource("multilineArgs")
+ public void testSimpleJSLTOnMultilineJson(String singleJsonFile, String
transformFile, String expectedOutFile) throws IOException {
+ final String newLine = "\n";
+ final String singleLine = minifyJson(singleJsonFile);
+ final int numberOfLines = 3;
+ final String multilineJson = String.join(newLine,
Collections.nCopies(numberOfLines, singleLine));
+ final String transform = getResource(transformFile);
+ runner.setProperty(JSLTTransformJSON.JSLT_TRANSFORM, transform);
+ runner.setProperty(JSLTTransformJSON.INPUT_FORMAT,
JSLTTransformJSON.InputFormat.JSON_LINES);
+ runner.enqueue(multilineJson);
+
+ runner.run();
+ runner.assertTransferCount(JSLTTransformJSON.REL_SUCCESS, 1);
+ runner.assertTransferCount(JSLTTransformJSON.REL_FAILURE, 0);
+
+ final String expectedLine = minifyJson(expectedOutFile);
+ final MockFlowFile flowFile =
runner.getFlowFilesForRelationship(JSLTTransformJSON.REL_SUCCESS).getFirst();
+
+ final String[] lines = flowFile.getContent().split(newLine);
+ assertEquals(numberOfLines, lines.length);
+
+ for (String line : lines) {
+ final JsonNode actual = OBJECT_MAPPER.readTree(line);
+ final JsonNode expected = OBJECT_MAPPER.readTree(expectedLine);
+ assertEquals(expected, actual);
+ }
+ }
+
+ private static Stream<Arguments> multilineArgs() {
+ return Stream.of(
+ Arguments.argumentSet("JSON Object", "input.json",
"simpleTransform.json", "simpleOutput.json"),
+ Arguments.argumentSet("JSON Array", "inputArray.json",
"arrayTransform.json", "arrayOutput.json")
+ );
+ }
+
// This test verifies transformCache cleanup does not throw an exception
@Test
public void testShutdown() {
@@ -186,8 +226,8 @@ public class TestJSLTTransformJSON {
private void assertContentEquals(final MockFlowFile flowFile, final String
expectedJson) {
try {
- final JsonNode flowFileNode =
objectMapper.readTree(flowFile.getContent());
- final JsonNode expectedNode = objectMapper.readTree(expectedJson);
+ final JsonNode flowFileNode =
OBJECT_MAPPER.readTree(flowFile.getContent());
+ final JsonNode expectedNode = OBJECT_MAPPER.readTree(expectedJson);
assertEquals(expectedNode, flowFileNode);
} catch (final IOException e) {
throw new UncheckedIOException(e);
@@ -210,14 +250,18 @@ public class TestJSLTTransformJSON {
return
runner.getFlowFilesForRelationship(JSLTTransformJSON.REL_SUCCESS).getFirst();
}
+ private String minifyJson(final String fileName) throws IOException {
+ final String originalJson = getResource(fileName);
+ final Object jsonObject = OBJECT_MAPPER.readValue(originalJson,
Object.class);
+ final String minifiedJson =
OBJECT_MAPPER.writeValueAsString(jsonObject);
+
+ return minifiedJson;
+ }
+
private String getResource(final String fileName) {
- final String path = String.format("/%s", fileName);
- try (
- final InputStream inputStream =
Objects.requireNonNull(getClass().getResourceAsStream(path), "Resource not
found");
- final ByteArrayOutputStream outputStream = new
ByteArrayOutputStream()
- ) {
- StreamUtils.copy(inputStream, outputStream);
- return outputStream.toString();
+ final Path resource = RESOURCE_DIR.resolve(fileName);
+ try {
+ return Files.readString(resource);
} catch (final IOException e) {
throw new UncheckedIOException(e);
}