/* istanbul ignore file */

/**
 * This example shows how to read and write large flowfiles without facing out
 * of memory errors by reading/writing/processing the flowfile content in chunks
 * instead of loading the entire flowfile content to the memory at once
 *
 * In this example, we convert the flowfile content to uppercase
 * To show a more complex example, we destroy the consumed flowfile
 * and create a new one instead of replacing the input flowfile content
 */

import { getInputStreamAsGenerator } from '~/nifi/flowfile-io';
import { drop, getOne, transferToSuccess } from '~/nifi/flowfile-lifecycle';

const StandardCharsets = Java.type('java.nio.charset.StandardCharsets');
const OutputStreamCallback = Java.type('org.apache.nifi.processor.io.OutputStreamCallback');

const flowFile = getOne();
if (flowFile) {
  const inputStream = session.read(flowFile);
  const iterator = getInputStreamAsGenerator(inputStream, 5);

  let newFlowFile = session.create();
  newFlowFile = session.write(
    newFlowFile,
    new OutputStreamCallback(function (outputStream) {
      for (const contentChunk of iterator) {
        const upperCaseContent = contentChunk.toUpperCase();
        outputStream.write(upperCaseContent.getBytes(StandardCharsets.UTF_8));
      }
    }),
  );

  inputStream.close();
  drop(flowFile);
  transferToSuccess(newFlowFile);
}
