├── README.md ├── JSON ├── SplitByFlatRecord │ ├── example │ │ ├── out │ │ │ ├── flowfile4.json │ │ │ ├── flowfile3.json │ │ │ ├── flowfile2.json │ │ │ └── flowfile1.json │ │ └── in │ │ │ └── flowfile.json │ ├── readme.md │ └── split.groovy ├── Compare │ ├── nifi_sample.png │ ├── readme.md │ ├── compare2json.groovy │ └── compare2json.xml ├── UnescapeJson │ ├── example │ │ ├── out │ │ │ └── flowfile.json │ │ └── in │ │ │ └── flowfile.json │ ├── readme.md │ └── script.groovy └── ConvertJsonFieldToString │ ├── example │ ├── out │ │ └── flowfile.json │ └── in │ │ └── flowfile.json │ ├── readme.md │ └── escape_json_tree.groovy ├── Convert ├── date_time │ ├── sample.jpg │ └── dt.groovy ├── xls-to-csv │ ├── TestWB.xls │ ├── readme.md │ ├── xls-to-csv.groovy │ └── xls-to-csv.xml ├── Encoding │ ├── nifi_sample.png │ ├── readme.md │ ├── UTF-16LE_with_BOM.groovy │ └── UTF-16LE_with_BOM.xml └── dbf-to-csv │ ├── nifi_sample.png │ ├── readme.md │ ├── db-to-csv.groovy │ └── dbf-to-csv.xml ├── Files └── flowfile_to_file_uppend │ ├── nifi_sample.png │ ├── readme.md │ ├── flowfile_to_file_uppend.groovy │ └── flowfile_to_file_uppend.xml ├── SYSTEM ├── get_group_id │ └── get_group_id.groovy ├── work_with_durations │ ├── readme.md │ └── filter_files_on_duration.groovy └── batch_transfer │ ├── readme.md │ └── batch_transfer.groovy ├── ScripterTransformRecord └── SplitRecordByFields │ ├── readme.md │ └── SplitRecord.groovy ├── Databases └── PostgreSQL │ ├── readme.md │ └── PGCopyScript.groovy └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # nifi-scripts 2 | Scripts for use with nifi Groovy 3 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/example/out/flowfile4.json: -------------------------------------------------------------------------------- 1 | {"id":"1","type":"cost","value":1000} 2 | -------------------------------------------------------------------------------- /Convert/date_time/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/Convert/date_time/sample.jpg -------------------------------------------------------------------------------- /Convert/xls-to-csv/TestWB.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/Convert/xls-to-csv/TestWB.xls -------------------------------------------------------------------------------- /JSON/Compare/nifi_sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/JSON/Compare/nifi_sample.png -------------------------------------------------------------------------------- /Convert/Encoding/nifi_sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/Convert/Encoding/nifi_sample.png -------------------------------------------------------------------------------- /Convert/dbf-to-csv/nifi_sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/Convert/dbf-to-csv/nifi_sample.png -------------------------------------------------------------------------------- /JSON/UnescapeJson/example/out/flowfile.json: -------------------------------------------------------------------------------- 1 | [{"name1":"KIM Ltd.","forma":[{"key0":"val0","key1":"val1","key2":"val2"}],"name2":""}] -------------------------------------------------------------------------------- /JSON/UnescapeJson/example/in/flowfile.json: -------------------------------------------------------------------------------- 1 | [{"name1":"KIM Ltd.","forma":"[{\"key0\":\"val0\",\"key1\":\"val1\",\"key2\":\"val2\"}]","name2":""}] -------------------------------------------------------------------------------- /Files/flowfile_to_file_uppend/nifi_sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nifi-core-team/nifi-scripts/HEAD/Files/flowfile_to_file_uppend/nifi_sample.png -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/example/out/flowfile3.json: -------------------------------------------------------------------------------- 1 | {"parent_id":"1","main_id":"1","name":"Johnson","type":"seller"} 2 | {"parent_id":"1","main_id":"1","name":"Simpson","type":"buyer"} 3 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/example/out/flowfile2.json: -------------------------------------------------------------------------------- 1 | {"parent_id":"1","main_id":"1","id":1,"description":"field1","value":100} 2 | {"parent_id":"1","main_id":"1","id":2,"description":"field2","value":900} 3 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/example/out/flowfile1.json: -------------------------------------------------------------------------------- 1 | {"parent_id":"1","main_id":"1","name":"item"} 2 | {"parent_id":"1","main_id":"1","name":"valuable"} 3 | {"parent_id":"1","main_id":"1","name":"item"} 4 | {"parent_id":"1","main_id":"1","name":"valuable"} 5 | -------------------------------------------------------------------------------- /SYSTEM/get_group_id/get_group_id.groovy: -------------------------------------------------------------------------------- 1 | def flowFile = session.get() 2 | if(!flowFile) return 3 | processGroupId = context.procNode?.processGroupIdentifier ?: 'unknown' 4 | flowFile = session.putAttribute(flowFile, 'processGroupId', processGroupId) 5 | session.transfer(flowFile, REL_SUCCESS) 6 | -------------------------------------------------------------------------------- /Files/flowfile_to_file_uppend/readme.md: -------------------------------------------------------------------------------- 1 | ## Сохранение содержимого (текстового) flowfile в файл 2 | Данный скрипт позволяет содержимое flowfile дописать в файл заданный в атрибутах file_name и file_path. 3 | Может пригодиться при логировании. 4 | 5 | ![](https://github.com/vomikan/nifi-scripts/blob/main/Files/flowfile_to_file_uppend/nifi_sample.png?raw=true) 6 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/example/in/flowfile.json: -------------------------------------------------------------------------------- 1 | {"id": "1", "type": "cost", "value": 1000, "lines": [{"id":1,"description": "field1","value": 100,"types": [{"name":"item"},{"name": "valuable"}]},{"id":2,"description": "field2","value": 900,"types": [{"name":"item"},{"name": "valuable"}]}], "persons": [{"name": "Johnson","type": "seller"},{"name": "Simpson","type": "buyer"}]} 2 | -------------------------------------------------------------------------------- /Convert/Encoding/readme.md: -------------------------------------------------------------------------------- 1 | ## Преобразование кодировки flowfile 2 | 3 | Изначально формируется CSV файл с фейковыми персональными данными на русском языке. 4 | После преобразования flowfile данным скриптом, итоговый файл (после сохранения) будет корректно открываться в Excel через Open. 5 | Итоговая кодировка UTF-16LE with BOM. 6 | 7 | ![](https://github.com/vomikan/nifi-scripts/blob/main/Convert/Encoding/nifi_sample.png?raw=true) 8 | -------------------------------------------------------------------------------- /Convert/Encoding/UTF-16LE_with_BOM.groovy: -------------------------------------------------------------------------------- 1 | def ff = session.get() 2 | if(!ff)return 3 | ff = session.write(ff, {rawIn, rawOut-> 4 | // ## transform streams into reader and writer 5 | rawIn.withReader("UTF-8"){reader-> 6 | rawOut.withWriter("UTF-16LE"){writer-> 7 | //transfer reader UTF-8 to writer UTF-16LE 8 | writer.write("\ufeff"); 9 | writer << reader 10 | } 11 | } 12 | } as StreamCallback) 13 | session.transfer(ff, REL_SUCCESS) 14 | -------------------------------------------------------------------------------- /SYSTEM/work_with_durations/readme.md: -------------------------------------------------------------------------------- 1 | # Фильтруем файлы по времени 2 | Выбираем из очереди все файлы которые лежат в ней больше минуты при условии что обработка по исходному файлу, 3 | из которого получился наш файл началась не больше чем час назад. Такие файлы готовы к дальнейшей обработке их пропускаем дальше 4 | Файлы работа с которыми инициирована час назад (первый файл в цепочке процессоров создан больше часа назад) 5 | устарели (мы не успели их обработать) их откидываем в Failure для дальнешего разбора. 6 | 7 | -------------------------------------------------------------------------------- /ScripterTransformRecord/SplitRecordByFields/readme.md: -------------------------------------------------------------------------------- 1 | # Код для процессора ScroptedTransformRecord/ 2 | Скрипт преобразут входящую запись в набор записей, каждая из которых содержит только одно поле из оригинальной записи, все остальные значение проставляются NULL. 3 | 4 | # Применеие 5 | 6 | Если запись не лезет в БД, например изменилась длина поля на источнике, иногда сходу не удается вычленить, кто именно не входит. Ставим в целевой таблице все поля в null, и разбираем запись на еденичные поля и проверяем, кто не влез. -------------------------------------------------------------------------------- /SYSTEM/batch_transfer/readme.md: -------------------------------------------------------------------------------- 1 | (EN) Transfer all files at once 2 | =============================== 3 | Just ad ExecuteGroovyScriptProcessor, set it shedule to value you need to aggregate batch or cron based schedule and all files in upstream queue will be transfered to success relation at one run of proc. 4 | 5 | (RU) Перенос всех файл за один запуск 6 | ===================================== 7 | Добавьте процессор ExecuteGroovyScript с этим скриптом, установите расписание в нужный период, или на нужное время по крону и файлы будут перенесены за один запуск в очередь success 8 | 9 | -------------------------------------------------------------------------------- /ScripterTransformRecord/SplitRecordByFields/SplitRecord.groovy: -------------------------------------------------------------------------------- 1 | results = [] 2 | 3 | fields = record.getRawFieldNames() 4 | schema = record.getSchema() 5 | fields.each{key -> { 6 | log.debug("Got key: ${key}") 7 | nMap = new java.util.HashMap() 8 | log.debug("create map") 9 | nMap.put(key,record.getValue(key)) 10 | log.debug("Put to map value") 11 | newrecord = new org.apache.nifi.serialization.record.MapRecord(schema, nMap) 12 | log.debug("Сreate new record with field ${key}") 13 | results.add(newrecord) 14 | }} 15 | 16 | results -------------------------------------------------------------------------------- /SYSTEM/batch_transfer/batch_transfer.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.nifi.flowfile.FlowFile 2 | import org.apache.nifi.processor.FlowFileFilter 3 | 4 | //Filter for accept all files 5 | class AllFiles implements FlowFileFilter{ 6 | @Override 7 | FlowFileFilterResult filter(FlowFile flowFile) { 8 | return FlowFileFilterResult.ACCEPT_AND_CONTINUE 9 | } 10 | } 11 | 12 | 13 | List inFlowFiles = session.get(new AllFiles()) 14 | 15 | //If have no files return 16 | if (inFlowFiles.isEmpty()) return 17 | 18 | //Transfer all to successd 19 | session.transfer(inFlowFiles,REL_SUCCESS) 20 | -------------------------------------------------------------------------------- /Convert/date_time/dt.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.nifi.flowfile.FlowFile 2 | 3 | import java.time.* 4 | import java.time.format.* 5 | 6 | FlowFile flowFile = session.get() 7 | if (!flowFile) return 8 | 9 | String ts_raw = flowFile.ts_raw 10 | 11 | if (ts_raw == null) { 12 | REL_FAILURE << flowFile 13 | return 14 | } 15 | 16 | String ts = LocalDateTime.parse(ts_raw, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'")) 17 | .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")) 18 | 19 | flowFile = session.putAttribute(flowFile, "ts", ts) 20 | REL_SUCCESS << flowFile 21 | -------------------------------------------------------------------------------- /Databases/PostgreSQL/readme.md: -------------------------------------------------------------------------------- 1 | # Назначение 2 | Производит bulk вставку flowfile'а с csv контентом в PostgreSQL с помощью CopyAPI 3 | 4 | # Применение 5 | Перед применением во flowfile нужно задать следующие атрибуты: 6 | - delimiter - разделить для записей 7 | - schema.table - таблица для вставки с указанием схемы (например public.zzz_test) 8 | В самом процессоре должен быть задан динамические параметры 9 | - CTL.* с указанием на используемый DBCPService 10 | - RecordReader.* с указанием на используемый Reader 11 | 12 | На выходе пропишется атрибут record.count с указанием количества вставленных записей. -------------------------------------------------------------------------------- /Convert/dbf-to-csv/readme.md: -------------------------------------------------------------------------------- 1 | # Преобразуем DBF файл в CSV 2 | 3 | Демо файл предваритеьно преобразован в base64, чтобы его можно было разместить в GenerateFlowFile процессор в виде текста. 4 | Base64EncodeContent процессор преобразует его обратно в бинарный файл. 5 | Третьим шагом, groovy скрипт преобразует DBF файл в CSV. 6 | 7 | ![](https://github.com/vomikan/nifi-scripts/blob/main/Convert/dbf-to-csv/nifi_sample.png?raw=true) 8 | 9 | Используем библиотеку из проекта https://github.com/albfernandez/javadbf 10 | 11 | В свойствах ExecuteGroovyScript указываем путь к файлу 12 | 13 | | Property | Value | 14 | |----------|-------| 15 | | Additional classpath | ./lib/dbf/javadbf-1.13.2.jar | 16 | -------------------------------------------------------------------------------- /JSON/Compare/readme.md: -------------------------------------------------------------------------------- 1 | ## Сравнение двух JSON файлов 2 | 3 | Первый JSON файл задаётся в GenerateFlowFile процессоре в разделе Properties Custom text. 4 | Значение атрибута "test1" будет случайным образом принимать значения от 1 до 2. 5 | Новые JSON файлы будут генерироваться каждые 5 секунд. 6 | ``` 7 | { 8 | "test2": "2", 9 | "test1": "${random():mod(2):plus(1)}" 10 | } 11 | ``` 12 | Второй "эталонный" JSON файл задаётся в атрибуте script.etalon_json 13 | ``` 14 | {"test2": "2","test1": "1"} 15 | ``` 16 | 17 | Процессор RouteOnAttribute распределить файлы на два потока. В один поток "одинаковый" пойдут файлы, которые совпадают с эталоном. 18 | В другой поток остальные (не совпадающие) файлы. 19 | ![](https://github.com/vomikan/nifi-scripts/blob/main/JSON/Compare/nifi_sample.png?raw=true) 20 | -------------------------------------------------------------------------------- /Files/flowfile_to_file_uppend/flowfile_to_file_uppend.groovy: -------------------------------------------------------------------------------- 1 | def flowFile = session.get() 2 | if(!flowFile) return 3 | 4 | try { 5 | session.read(flowFile, { inputStream -> 6 | 7 | def file_path = flowFile.getAttribute("file_path"); 8 | def file_name = flowFile.getAttribute("file_name"); 9 | 10 | def filePath = new File(file_path); 11 | if( !filePath.exists() ) { 12 | filePath.mkdir() 13 | } 14 | 15 | new File( file_path, file_name ).withWriterAppend { w -> 16 | w << inputStream << "\n" 17 | } 18 | 19 | 20 | } as InputStreamCallback) 21 | 22 | //transfer control to success 23 | session.transfer(flowFile, REL_SUCCESS) 24 | 25 | } catch (ex) { 26 | flowFile = session.putAttribute(flowFile, "script.error_message", ex.getMessage()) 27 | flowFile = session.putAttribute(flowFile, "script.error", ex.toString()) 28 | //transfer control to failure 29 | session.transfer(flowFile, REL_FAILURE) 30 | } 31 | -------------------------------------------------------------------------------- /JSON/ConvertJsonFieldToString/example/out/flowfile.json: -------------------------------------------------------------------------------- 1 | [ { 2 | "metadata" : { 3 | "integrationTimestamp" : 1681505099863 4 | }, 5 | "messageObject" : { 6 | "id" : "key", 7 | "createdOn" : "2022-01-05T00:02:26.4100000Z", 8 | "modifiedOn" : "2022-01-05T00:02:26.4100000Z", 9 | "currentAmount" : 7149.0, 10 | "contact" : "key", 11 | "type" : "main", 12 | "dueDate" : "2024-03-17T21:00:00.0000000Z", 13 | "regDate" : "2022-11-26T00:00:00.0000000Z", 14 | "totalAmount" : 7149.0, 15 | "bonusBalanceBPMID" : "key", 16 | "bonusBalanceStateName" : "Updated", 17 | "bonuses" : "[{\"typeSource\":\"Sale\",\"currentAmount\":1153.00,\"totalAmount\":1153.00,\"dueAmount\":1153.00,\"dueDate\":\"2024-03-17T21:00:00.0000000Z\"},{\"typeSource\":\"Action\",\"currentAmount\":5996.00,\"totalAmount\":5996.00,\"dueAmount\":3000.00,\"dueDate\":\"2023-05-01T21:01:33.0478528Z\"}]", 18 | "contactBPMID" : "key" 19 | } 20 | } ] -------------------------------------------------------------------------------- /JSON/Compare/compare2json.groovy: -------------------------------------------------------------------------------- 1 | import groovy.json.JsonSlurper 2 | 3 | def flowFile = session.get() 4 | if(!flowFile) return 5 | 6 | try { 7 | def map1 = flowFile.read().withReader("UTF-8"){ new JsonSlurper().parse(it) } 8 | 9 | def jsonSlurper = new JsonSlurper() 10 | def second_json = flowFile.getAttribute("script.etalon_json") 11 | def map2 = jsonSlurper.parseText(second_json) 12 | Boolean result = (map1 == map2) 13 | 14 | flowFile = session.putAttribute(flowFile, "script.output", result.toString()) 15 | 16 | //Clearing an attribute that is not needed 17 | flowFile = session.putAttribute(flowFile, "script.etalon_json", "") 18 | 19 | //transfer control to success 20 | session.transfer(flowFile, REL_SUCCESS) 21 | } catch (ex) { 22 | flowFile = session.putAttribute(flowFile, "script.error_message", ex.getMessage()) 23 | flowFile = session.putAttribute(flowFile, "script.error", ex.toString()) 24 | //transfer control to failure 25 | session.transfer(flowFile, REL_FAILURE) 26 | } 27 | -------------------------------------------------------------------------------- /Convert/xls-to-csv/readme.md: -------------------------------------------------------------------------------- 1 | # Преобразуем XLS в CSV 2 | 3 | Для преобразования используем библиотеку [Apache POI - the Java API for Microsoft Documents](https://poi.apache.org/) версии 5.0.0 4 | [![latest packaged version(s)](https://poi.apache.org/images/project-header.png )](https://archive.apache.org/dist/poi/release/bin/poi-bin-5.0.0-20210120.zip) 5 | 6 | Все jar файлы сохранены в одну папку /opt/nifi/lib/poi 7 | 8 | Простейший Excel файл создан для демонстранции 9 | 10 | ![image](https://user-images.githubusercontent.com/6836805/177600089-01809627-4ac6-408a-a545-1e2e2eb41da2.png) 11 | 12 | В итоге работы Groovy скрипта получается CSV файл. 13 | ``` 14 | "Col1","Col2","Col3","" 15 | "123.0","bbbbb","0.17","" 16 | ``` 17 | 18 | Скрипт работает с файлами office 97+ в формате .xls. 19 | 20 | Настройки процессора ExecuteGroovyScript 1.13.2 21 | ``` 22 | /opt/nifi/lib/poi/poi-5.0.0.jar; /opt/nifi/lib/poi/commons-math3-3.6.1.jar 23 | ``` 24 | 25 | ![image](https://user-images.githubusercontent.com/6836805/177602470-8231e833-6a24-4e1d-a4e2-7f7772ebffe6.png) 26 | -------------------------------------------------------------------------------- /JSON/ConvertJsonFieldToString/example/in/flowfile.json: -------------------------------------------------------------------------------- 1 | [ { 2 | "metadata" : { 3 | "integrationTimestamp" : 1681505098676 4 | }, 5 | "messageObject" : { 6 | "id" : "key", 7 | "createdOn" : "2023-03-29T16:32:44.8800000Z", 8 | "modifiedOn" : "2023-03-29T16:32:44.8800000Z", 9 | "currentAmount" : 1149.00, 10 | "contact" : "key", 11 | "type" : "main", 12 | "dueDate" : "2024-04-13T21:00:00.0000000Z", 13 | "regDate" : "2023-03-31T00:00:00.0000000Z", 14 | "totalAmount" : 1149.00, 15 | "bonusBalanceBPMID" : "key", 16 | "bonusBalanceStateName" : "Updated", 17 | "bonusBalanceState" : { }, 18 | "bonuses" : [ { 19 | "typeSource" : "Sale", 20 | "currentAmount" : 149.00, 21 | "totalAmount" : 149.00, 22 | "dueAmount" : 149.00, 23 | "dueDate" : "2024-04-13T21:00:00.0000000Z" 24 | }, { 25 | "typeSource" : "Action", 26 | "currentAmount" : 1000.00, 27 | "totalAmount" : 1000.00, 28 | "dueAmount" : 1000.00, 29 | "dueDate" : "2023-05-05T16:19:54.1393545Z" 30 | } ], 31 | "contactBPMID" : "key" 32 | } 33 | } ] -------------------------------------------------------------------------------- /Databases/PostgreSQL/PGCopyScript.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.nifi.processor.ProcessSession 2 | 3 | session = (ProcessSession) session 4 | def in_ff = session.get() 5 | if (!in_ff) return 6 | 7 | def recordCount 8 | def table = in_ff.'schema.table' 9 | def delimiter = in_ff.'delimiter' 10 | def conn = CTL.db.getConnection() 11 | def readerFactory = RecordReader.csv 12 | try { 13 | session.read(in_ff, { inputStream -> 14 | def variables = new HashMap(in_ff.attributes) 15 | def reader = readerFactory.createRecordReader(variables, inputStream, -1L, log) 16 | def fields = "(" + reader.getSchema().getFieldNames().join(",") + ")" 17 | long rowsInserted = conn.getWrapped().getInnermostDelegateInternal().getCopyAPI() 18 | .copyIn( 19 | "COPY gidrometcenter.${table}${fields} FROM STDIN (FORMAT csv, DELIMITER '${delimiter}')", 20 | inputStream, 21 | 8192 22 | ) 23 | recordCount = rowsInserted.toString() 24 | }) 25 | in_ff.'record.count' = recordCount 26 | session.transfer(in_ff, REL_SUCCESS) 27 | } catch (Exception e) { 28 | log.error('Error has occured', e) 29 | session.transfer(in_ff, REL_FAILURE) 30 | } finally { 31 | conn.close() 32 | } 33 | -------------------------------------------------------------------------------- /JSON/UnescapeJson/readme.md: -------------------------------------------------------------------------------- 1 | (EN) Unescape all inner JSON strings in FlowFile 2 | ============================================== 3 | Unescape JSON from all inner strings. 4 | The script is implemented for early versions of NiFi, where the unescapeJson function is missing. 5 | 6 | In FlowFile Example: 7 | 8 | ` 9 | [ 10 | { 11 | "name1": "KIM Ltd.", 12 | "forma": "[{\"key0\":\"val0\",\"key1\":\"val1\",\"key2\":\"val2\"}]", 13 | "name2": "" 14 | } 15 | ] 16 | ` 17 | 18 | Results of Script: 19 | 20 | ` 21 | [ 22 | { 23 | "name1": "Kim Ltd", 24 | "forma": [ 25 | { 26 | "key0": "val0", 27 | "key1": "val1", 28 | "key2": "val2" 29 | } 30 | ], 31 | "name2": "" 32 | } 33 | ] 34 | ` 35 | 36 | (RU) Достает все вложенные JSON из экранированных строк. 37 | =================================================================== 38 | Скрипт реализован для ранних версий NiFi, где функция unescapeJson отсутствует. 39 | 40 | *Пример входящего файла* 41 | 42 | ` 43 | [ 44 | { 45 | "name1": "KIM Ltd.", 46 | "forma": "[{\"key0\":\"val0\",\"key1\":\"val1\",\"key2\":\"val2\"}]", 47 | "name2": "" 48 | } 49 | ] 50 | ` 51 | 52 | 53 | *Результаты для скрипта по данному файлу* 54 | 55 | ` 56 | [ 57 | { 58 | "name1": "Kim Ltd", 59 | "forma": [ 60 | { 61 | "key0": "val0", 62 | "key1": "val1", 63 | "key2": "val2" 64 | } 65 | ], 66 | "name2": "" 67 | } 68 | ] 69 | ` 70 | -------------------------------------------------------------------------------- /SYSTEM/work_with_durations/filter_files_on_duration.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.nifi.flowfile.FlowFile 2 | import org.apache.nifi.processor.FlowFileFilter 3 | import org.apache.nifi.processor.ProcessSession 4 | 5 | ProcessSession session = session 6 | 7 | long currentTime = new Date().getTime() 8 | List files = session.get(new FlowFileFilter() { 9 | @Override 10 | FlowFileFilter.FlowFileFilterResult filter(FlowFile flowFile) { 11 | //Accept Files that queued for more than 1 minute, but only those which process start not later than hour ago 12 | if (flowFile.lastQueueDate < currentTime - 60000 && flowFile.getEntryDate() > currentTime - 3600000) 13 | return FlowFileFilter.FlowFileFilterResult.ACCEPT_AND_CONTINUE 14 | else return FlowFileFilter.FlowFileFilterResult.REJECT_AND_CONTINUE 15 | } 16 | }) 17 | if (files.size() == 0) return 18 | //transfer files to Success 19 | session.transfer(files, REL_SUCCESS) 20 | 21 | files = session.get(new FlowFileFilter() { 22 | @Override 23 | FlowFileFilter.FlowFileFilterResult filter(FlowFile flowFile) { 24 | //Accept Files that start processed more than hour ago 25 | if (flowFile.getEntryDate() <= currentTime - 3600000) return FlowFileFilter.FlowFileFilterResult.ACCEPT_AND_CONTINUE 26 | else return FlowFileFilter.FlowFileFilterResult.REJECT_AND_CONTINUE 27 | } 28 | }) 29 | if (files.size()==0) return 30 | // Send such old files to Failure 31 | session.transfer(files.REL_FAILURE) 32 | -------------------------------------------------------------------------------- /JSON/UnescapeJson/script.groovy: -------------------------------------------------------------------------------- 1 | import groovy.json.JsonGenerator 2 | import groovy.json.JsonOutput 3 | import groovy.json.JsonParserType 4 | import groovy.json.JsonSlurper 5 | 6 | import org.apache.commons.io.IOUtils 7 | import org.apache.nifi.processor.io.StreamCallback 8 | 9 | import java.nio.charset.StandardCharsets 10 | 11 | 12 | class DeepJson { 13 | 14 | static def jsonSlurper = new JsonSlurper().setType(JsonParserType.CHARACTER_SOURCE) 15 | 16 | static Object findDeep(Map map, Object key) { 17 | map.get(key) ?: map.findResult { k, v -> if (v in Map) findDeep(v, key) } 18 | } 19 | 20 | static Object convertString(String s) { 21 | try { 22 | def js = jsonSlurper.parseText(s) 23 | if (js in Map) { 24 | convertMap(js) 25 | } else if (js in ArrayList) { 26 | convertArray(js) 27 | } else s 28 | } catch (ignored) { 29 | s 30 | } 31 | } 32 | 33 | static Map convertMap(Map m) { 34 | m.each { it.value = convert(it.value) } 35 | } 36 | 37 | static ArrayList convertArray(ArrayList a) { 38 | a.collect({convert(it)}) 39 | //a.collect({if (it in Map) convert(it) else it} ) // - replace line above if you want to skip array of string converting 40 | } 41 | 42 | static Object convert(Object o) { 43 | if (o in Map) { 44 | convertMap(o) 45 | } else if (o in ArrayList) { 46 | convertArray(o) 47 | } else if (o in String) { 48 | convertString(o) 49 | } else 50 | o 51 | } 52 | 53 | static String expandJsonStrings(String s) { 54 | def object = jsonSlurper.parseText(s) 55 | new JsonGenerator.Options().disableUnicodeEscaping().build().toJson(convert(object)) 56 | } 57 | } 58 | 59 | 60 | def flowFile = session.get(); 61 | if (flowFile == null) { 62 | return; 63 | } 64 | 65 | flowFile = session.write( 66 | flowFile, 67 | { inputStream, outputStream -> 68 | def content = IOUtils.toString(inputStream, StandardCharsets.UTF_8) 69 | outputStream.write(DeepJson.expandJsonStrings(content).getBytes(StandardCharsets.UTF_8)) 70 | } as StreamCallback 71 | ) 72 | session.transfer(flowFile, REL_SUCCESS) -------------------------------------------------------------------------------- /JSON/ConvertJsonFieldToString/readme.md: -------------------------------------------------------------------------------- 1 | # Cкрипт преобразует вложенное поле в строку 2 | 3 | В текущем примере требуется преобразовать вложенную запись к JSON строке. Для больших вложенностей, массивов метод EscapeJson процессора UpdateRecord не отрабатывает. 4 | 5 | На входе: 6 | 7 | ```json 8 | [ { 9 | "metadata" : { 10 | "integrationTimestamp" : 1681505098676 11 | }, 12 | "messageObject" : { 13 | "id" : "key", 14 | "createdOn" : "2023-03-29T16:32:44.8800000Z", 15 | "modifiedOn" : "2023-03-29T16:32:44.8800000Z", 16 | "currentAmount" : 1149.00, 17 | "contact" : "key", 18 | "type" : "main", 19 | "dueDate" : "2024-04-13T21:00:00.0000000Z", 20 | "regDate" : "2023-03-31T00:00:00.0000000Z", 21 | "totalAmount" : 1149.00, 22 | "bonusBalanceBPMID" : "key", 23 | "bonusBalanceStateName" : "Updated", 24 | "bonusBalanceState" : { }, 25 | "bonuses" : [ { 26 | "typeSource" : "Sale", 27 | "currentAmount" : 149.00, 28 | "totalAmount" : 149.00, 29 | "dueAmount" : 149.00, 30 | "dueDate" : "2024-04-13T21:00:00.0000000Z" 31 | }, { 32 | "typeSource" : "Action", 33 | "currentAmount" : 1000.00, 34 | "totalAmount" : 1000.00, 35 | "dueAmount" : 1000.00, 36 | "dueDate" : "2023-05-05T16:19:54.1393545Z" 37 | } ], 38 | "contactBPMID" : "key" 39 | } 40 | } ] 41 | ``` 42 | 43 | На выходе: 44 | 45 | ```json 46 | [ { 47 | "metadata" : { 48 | "integrationTimestamp" : 1681505099863 49 | }, 50 | "messageObject" : { 51 | "id" : "key", 52 | "createdOn" : "2022-01-05T00:02:26.4100000Z", 53 | "modifiedOn" : "2022-01-05T00:02:26.4100000Z", 54 | "currentAmount" : 7149.0, 55 | "contact" : "key", 56 | "type" : "main", 57 | "dueDate" : "2024-03-17T21:00:00.0000000Z", 58 | "regDate" : "2022-11-26T00:00:00.0000000Z", 59 | "totalAmount" : 7149.0, 60 | "bonusBalanceBPMID" : "key", 61 | "bonusBalanceStateName" : "Updated", 62 | "bonuses" : "[{\"typeSource\":\"Sale\",\"currentAmount\":1153.00,\"totalAmount\":1153.00,\"dueAmount\":1153.00,\"dueDate\":\"2024-03-17T21:00:00.0000000Z\"},{\"typeSource\":\"Action\",\"currentAmount\":5996.00,\"totalAmount\":5996.00,\"dueAmount\":3000.00,\"dueDate\":\"2023-05-01T21:01:33.0478528Z\"}]", 63 | "contactBPMID" : "key" 64 | } 65 | } ] 66 | ``` 67 | -------------------------------------------------------------------------------- /Convert/xls-to-csv/xls-to-csv.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.poi.ss.usermodel.* 2 | import org.apache.poi.hssf.usermodel.* 3 | import org.apache.poi.xssf.usermodel.* 4 | import org.apache.poi.ss.util.* 5 | import java.io.* 6 | import java.text.SimpleDateFormat 7 | import org.apache.commons.io.IOUtils 8 | import java.nio.charset.StandardCharsets 9 | 10 | flowFile = session.get() 11 | if(!flowFile)return 12 | 13 | newFlowFile = session.create() 14 | def filename = flowFile.getAttribute('filename') 15 | newFlowFile = session.putAttribute(newFlowFile, "filename",filename) 16 | 17 | flowFile.getAttributes().each { key,value -> 18 | session.putAttribute(newFlowFile, key,value) 19 | } 20 | 21 | try{ 22 | Workbook wb = WorkbookFactory.create(session.read(flowFile)) 23 | 24 | def sheet = ProcessSheet.evaluateAttributeExpressions(flowFile).value 25 | 26 | def ws = wb.getSheet(sheet) 27 | int r = ws.getLastRowNum() 28 | def csv_data_rows = [] 29 | 30 | for(def i = SkipRows.value.toInteger() ; i <= r ; i++ ){ 31 | def row = ws.getRow(i) 32 | def noOfCell = MaxCellNumber.value.toInteger() 33 | def tmp_data_list = [] 34 | 35 | for (def j=0;j < noOfCell;j++){ 36 | Cell cell = row.getCell(j) 37 | if (cell == null || cell.getCellType() == CellType.BLANK) { 38 | value = "" 39 | } 40 | else if(cell.getCellType() == CellType.NUMERIC){ 41 | if (DateUtil.isCellDateFormatted(cell)) { 42 | Date date = cell.getDateCellValue(); 43 | SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy") 44 | String formatted = format1.format(date) 45 | value = formatted 46 | } else { 47 | value = (cell.getNumericCellValue()) 48 | } 49 | } 50 | else{value = (cell.getStringCellValue()) 51 | value = value.replace("\n","") 52 | } 53 | 54 | def temp = '"' + value +'"' 55 | tmp_data_list.add(temp) 56 | 57 | } 58 | data_row = tmp_data_list.join(",") 59 | csv_data_rows.add(data_row) 60 | } 61 | 62 | session.remove(flowFile) 63 | newFlowFile = session.write(newFlowFile, {outputStream -> 64 | outputStream.write(csv_data_rows.join("\n").getBytes(StandardCharsets.UTF_8)) 65 | } as OutputStreamCallback) 66 | session.transfer(newFlowFile, REL_SUCCESS) 67 | } 68 | catch(ex) 69 | { 70 | session.remove(newFlowFile) 71 | log.error("my message" + ex.getMessage()) 72 | session.transfer(flowFile, REL_FAILURE) 73 | } 74 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/readme.md: -------------------------------------------------------------------------------- 1 | (EN) Split JSON FlowFile to flat JSON FlowFile 2 | ============================================== 3 | Get JSON with inner record in it and split it to different flowfiles each of that flowfile contains flate JSON. 4 | 5 | In FlowFile Example: 6 | 7 | ` 8 | {"id": "1", "type": "cost", "value": 1000, "lines": [{"id":1,"description": "field1","value": 100,"types": [{"name":"item"},{"name": "valuable"}]},{"id":2,"description": "field2","value": 900,"types": [{"name":"item"},{"name": "valuable"}]}], "persons": [{"name": "Johnson","type": "seller"},{"name": "Simpson","type": "buyer"}]} 9 | ` 10 | 11 | Results of Script: 12 | 13 | ` 14 | {"id":"1","type":"cost","value":1000} 15 | ` 16 | 17 | ` 18 | {"parent_id":"1","main_id":"1","name":"Johnson","type":"seller"} 19 | {"parent_id":"1","main_id":"1","name":"Simpson","type":"buyer"} 20 | ` 21 | 22 | ` 23 | {"parent_id":"1","main_id":"1","id":1,"description":"field1","value":100} 24 | {"parent_id":"1","main_id":"1","id":2,"description":"field2","value":900} 25 | ` 26 | 27 | ` 28 | {"parent_id":"1","main_id":"1","name":"item"} 29 | {"parent_id":"1","main_id":"1","name":"valuable"} 30 | {"parent_id":"1","main_id":"1","name":"item"} 31 | {"parent_id":"1","main_id":"1","name":"valuable"} 32 | ` 33 | 34 | 35 | works only with LineByLine JSON File 36 | 37 | (RU) Разделяет JSON файл с иерархической структурой на плоские JSON 38 | =================================================================== 39 | Разбивает входящий JSON на отдельные файлы в каждом из которых набор строк JSON с плоской структурой. ID достает из поля \_id или id и прокидывает в дочерние файлы. 40 | 41 | *Пример входящего файла* 42 | 43 | ` 44 | {"id": "1", "type": "cost", "value": 1000, "lines": [{"id":1,"description": "field1","value": 100,"types": [{"name":"item"},{"name": "valuable"}]},{"id":2,"description": "field2","value": 900,"types": [{"name":"item"},{"name": "valuable"}]}], "persons": [{"name": "Johnson","type": "seller"},{"name": "Simpson","type": "buyer"}]} 45 | ` 46 | 47 | 48 | *Результаты для скрипта по данному файлу* 49 | 50 | ` 51 | {"id":"1","type":"cost","value":1000} 52 | ` 53 | 54 | ` 55 | {"parent_id":"1","main_id":"1","name":"Johnson","type":"seller"} 56 | {"parent_id":"1","main_id":"1","name":"Simpson","type":"buyer"} 57 | ` 58 | 59 | ` 60 | {"parent_id":"1","main_id":"1","id":1,"description":"field1","value":100} 61 | {"parent_id":"1","main_id":"1","id":2,"description":"field2","value":900} 62 | ` 63 | 64 | ` 65 | {"parent_id":"1","main_id":"1","name":"item"} 66 | {"parent_id":"1","main_id":"1","name":"valuable"} 67 | {"parent_id":"1","main_id":"1","name":"item"} 68 | {"parent_id":"1","main_id":"1","name":"valuable"} 69 | ` 70 | 71 | Работает только для формат JSON Line by Line 72 | -------------------------------------------------------------------------------- /Convert/dbf-to-csv/db-to-csv.groovy: -------------------------------------------------------------------------------- 1 | /* Thanks to Nikolay Akimov https://github.com/vomikan 2 | based on https://github.com/albfernandez/javadbf#reading-a-dbf-file 3 | Added MAX_LINES - Max lines in one OutFile 4 | */ 5 | import org.apache.nifi.flowfile.FlowFile 6 | import org.apache.nifi.processor.ProcessSession 7 | import org.apache.nifi.processor.io.InputStreamCallback 8 | 9 | import com.linuxense.javadbf.* 10 | 11 | SEP = "," 12 | MAX_LINES = 10000 13 | 14 | def escapeCSV(String s) { 15 | str1 = new String(s.getBytes("ISO-8859-1"), "UTF-8") 16 | str2 = new String(s.getBytes("ISO-8859-1"), "windows-1251") 17 | if (str1.length() < str2.length()) { s = str1 } else { s = str2 } 18 | if (s.contains(SEP)) { 19 | s = /"/ + s.replaceAll(/"/, /""/) + /"/ 20 | } 21 | return s 22 | } 23 | 24 | ProcessSession session=session 25 | def flowFile = session.get() 26 | if(!flowFile) return 27 | List files=[] 28 | FlowFile currentFile 29 | OutputStream outputStream 30 | try { 31 | int current = 0 32 | session.read(flowFile, { inputStream -> 33 | reader = new DBFReader(inputStream) 34 | 35 | int numberOfFields = reader.getFieldCount() 36 | fields = new String[numberOfFields] 37 | String header = '' 38 | for (int i = 0; i < numberOfFields; i++) { 39 | fields[i] = reader.getField(i).getName() 40 | header += escapeCSV(fields[i]) 41 | if (i < numberOfFields - 1) { header += SEP } 42 | } 43 | 44 | DBFRow row 45 | while ((row = reader.nextRow()) != null) { 46 | if (current == 0) { 47 | files.add(session.create(flowFile)) 48 | currentFile = files.get(files.size() - 1) 49 | outputStream = session.write(currentFile) 50 | outputStream.write("${header.toString()}".getBytes('UTF-8')) 51 | } 52 | String csv = '\n' 53 | for (int i = 0; i < numberOfFields; i++) { 54 | csv += escapeCSV(row.getString(fields[i])) 55 | if (i < numberOfFields - 1) { csv += SEP } 56 | } 57 | outputStream.write("${csv.toString()}".getBytes('UTF-8')) 58 | current++ 59 | if (current >= MAX_LINES) { 60 | current = 0 61 | outputStream.close() 62 | } 63 | } 64 | } as InputStreamCallback) 65 | 66 | //transfer control to success 67 | if (outputStream != null){ outputStream.close() } 68 | 69 | session.transfer(files, REL_SUCCESS) 70 | session.remove(flowFile) 71 | } catch (ex) { 72 | flowFile = session.putAttribute(flowFile, "script.error_message", ex.getMessage()) 73 | flowFile = session.putAttribute(flowFile, "script.error", ex.toString()) 74 | //transfer control to failure 75 | session.transfer(flowFile, REL_FAILURE) 76 | if (outputStream != null){outputStream.close()} 77 | session.remove(files) 78 | } 79 | -------------------------------------------------------------------------------- /JSON/ConvertJsonFieldToString/escape_json_tree.groovy: -------------------------------------------------------------------------------- 1 | import groovy.json.JsonSlurper 2 | import groovy.json.JsonGenerator 3 | import java.nio.charset.StandardCharsets 4 | 5 | def flowFile = session.get() 6 | if (flowFile == null) { 7 | return 8 | } 9 | 10 | JsonSlurper jsonSlurper = new JsonSlurper() 11 | 12 | if (flowFile.'kafka.topic' == 'CRM_BonusBalances') { 13 | flowFile = session.write(flowFile, 14 | { inputStream, outputStream -> 15 | content = org.apache.commons.io.IOUtils.toString(inputStream, java.nio.charset.StandardCharsets.UTF_8) 16 | //log.debug(content) 17 | json = jsonSlurper.parseText(content) 18 | //log.debug("size ="+json.size().toString()) 19 | for (int i = 0; i < json.size(); i++) { 20 | //log.debug(json[i]['messageObject'].toString()) 21 | if (json[i]['messageObject']['bonuses']) { 22 | bonuses = json[i]['messageObject']['bonuses'] 23 | //log.debug(communications.toString()) 24 | 25 | if (bonuses.size() != 0) { 26 | def strbonuses = new JsonGenerator.Options() 27 | .disableUnicodeEscaping() 28 | .build() 29 | .toJson(bonuses) 30 | 31 | //println(strbonuses) 32 | //log.debug('Here') 33 | json[i]['messageObject']['bonuses'] = strbonuses 34 | } 35 | else json[i]['messageObject']['bonuses'] = '' 36 | } 37 | json[i]['messageObject'].remove('bonusBalanceState') 38 | if (json[i]['messageObject']['dueDate'] == '') { json[i]['messageObject']['dueDate'] = null } 39 | if (json[i]['messageObject']['regDate'] == '') { json[i]['messageObject']['regDate'] = null } 40 | } 41 | //println "Result \r\n" 42 | def resultJson = new JsonGenerator.Options() 43 | .disableUnicodeEscaping() 44 | .build() 45 | .toJson(json) 46 | 47 | outputStream.write(resultJson.getBytes(StandardCharsets.UTF_8)) 48 | } as StreamCallback) 49 | 50 | session.transfer(flowFile, REL_SUCCESS) 51 | return 52 | } 53 | 54 | log.debug('CRM_Batch_BonusBalances') 55 | 56 | flowFile = session.write(flowFile, 57 | { inputStream, outputStream -> 58 | def content = org.apache.commons.io.IOUtils.toString(inputStream, java.nio.charset.StandardCharsets.UTF_8) 59 | 60 | def resultJson = [] 61 | //log.debug(content) 62 | json = jsonSlurper.parseText(content) 63 | //log.debug("size ="+json.size().toString()) 64 | 65 | for (int i = 0; i < json.size(); i++) { 66 | //log.debug(json[i]['messageObject'].toString()) 67 | 68 | log.debug('MessageObject size: ' + json[i]['MessageObject'].size()) 69 | 70 | for (j = 0; j < json[i]['MessageObject'].size(); j++) { 71 | log.debug(' j =' + j) 72 | log.debug(json[i]['MessageObject'][j].toString()) 73 | 74 | bonuses = json[i]['MessageObject'][j]['bonuses'] 75 | //log.debug(communications.toString()) 76 | if (bonuses.size() > 0) { 77 | strbonuses = new JsonGenerator.Options() 78 | .disableUnicodeEscaping() 79 | .build() 80 | .toJson(bonuses) 81 | 82 | log.debug('Convert bonuses to str : ' + strbonuses) 83 | json[i]['MessageObject'][j]['bonuses'] = strbonuses 84 | } 85 | else { 86 | json[i]['MessageObject'][j]['bonuses'] = '' 87 | } 88 | 89 | json[i]['MessageObject'][j].remove('bonusBalanceState') 90 | if (json[i]['MessageObject'][j]['dueDate'] == '') { json[i]['MessageObject'][j]['dueDate'] = null } 91 | if (json[i]['MessageObject'][j]['regDate'] == '') { json[i]['MessageObject'][j]['regDate'] = null } 92 | 93 | def tmpJson = [ 94 | metadata: json[i]['Metadata'], 95 | messageObject : json[i]['MessageObject'][j] 96 | ] 97 | resultJson.add(tmpJson) 98 | } 99 | } 100 | 101 | //println "Result \r\n" 102 | resultJson_str = new JsonGenerator.Options() 103 | .disableUnicodeEscaping() 104 | .build() 105 | .toJson(resultJson) 106 | 107 | outputStream.write(resultJson_str.getBytes(StandardCharsets.UTF_8)) 108 | } as StreamCallback) 109 | 110 | session.transfer(flowFile, REL_SUCCESS) 111 | -------------------------------------------------------------------------------- /JSON/SplitByFlatRecord/split.groovy: -------------------------------------------------------------------------------- 1 | import org.apache.nifi.flowfile.FlowFile 2 | import org.apache.nifi.processor.ProcessSession 3 | import org.apache.nifi.processor.io.InputStreamCallback 4 | import groovy.json.* 5 | 6 | 7 | def srcflowFile = session.get(); 8 | if (srcflowFile == null) { 9 | //Exit on zero files 10 | return; 11 | } 12 | 13 | Map resultFiles = new HashMap<>(); 14 | Map resultOut = new HashMap<>() 15 | 16 | /* writeTable Create One Flat Structure 17 | / prefix = prefix of created fields 18 | / name = name of table to write 19 | / m = record to write 20 | / result = Streams we already created 21 | / resultF = FlowFiles we already created 22 | / flowFile = base flow file 23 | / session = session to operate flowfile 24 | */ 25 | def writeTable(String prefix, String name, Map m, Map result, Map resultF, FlowFile flowFile, ProcessSession session) { 26 | def table_name = String.format("%s_%s", prefix, name) 27 | if (!(table_name in result)) { 28 | def ff = session.create(flowFile) 29 | def outer = session.write(ff) 30 | resultF.put(table_name, ff) 31 | result.put(table_name, outer) 32 | } 33 | OutputStream out = result.get(table_name) 34 | // Writing JsonLineByLine 35 | out.write(new JsonGenerator.Options().disableUnicodeEscaping().build().toJson(m).getBytes("UTF-8")) 36 | out.write('\n'.getBytes("UTF-8")) 37 | } 38 | 39 | //ConvertName 40 | def translateName(String name) { 41 | if (name.toLowerCase() in ["token", "default"]) { 42 | return name + "_fld" 43 | } else if (name in ["_id"]) { 44 | return "record" + name 45 | } else return name 46 | } 47 | /* 48 | / parseJSON - Parse map object 49 | / main_id = Id of whole record 50 | / parent_id = Id of parent level record 51 | / prefix = prefix to fields 52 | / name = name of created record 53 | / flowFile = file to clone 54 | / session = session to operate flowFiles 55 | */ 56 | def parseJSON(String main_id, String parent_id, String prefix, String name, Map js, Map resultF, Map result, FlowFile flowFile, ProcessSession session) { 57 | def m = [:] 58 | if (!parent_id.isBlank()) { 59 | m.put("parent_id", parent_id) 60 | } 61 | String id = parent_id 62 | if (js.containsKey("_id")) { 63 | def val = js.get("_id") 64 | if (val instanceof Map && val.size() == 1) { 65 | id = val.get(val.keySet()[0]) 66 | } else if (val instanceof String) { 67 | id = val.toString() 68 | } 69 | } else if (js.get("id")){ 70 | def val = js.get("id") 71 | if (val instanceof Map && val.size() == 1) { 72 | id = val.get(val.keySet()[0]) 73 | } else if (val instanceof String) { 74 | id = val.toString() 75 | } 76 | } 77 | if (main_id.isBlank()) { 78 | main_id = id 79 | } else { 80 | m.put("main_id", main_id) 81 | } 82 | for (String key : js.keySet()) { 83 | def val = js.get(key) 84 | if (val instanceof Map) { 85 | //Parse inner object 86 | if (val.size() == 1) { 87 | //If inner object have only one field just flatten it to upper level 88 | m.put(translateName(key), val.get(val.keySet()[0])) 89 | } else 90 | //Recurse call 91 | parseJSON(main_id, id, prefix, key, val, resultF, result, flowFile, session) 92 | } else if (val instanceof List) { 93 | // Parse list object recursively 94 | parseJSONA(main_id, id, prefix, key, val, resultF, result, flowFile, session) 95 | } else { 96 | //Add to record plain fields 97 | m.put(translateName(key), val) 98 | } 99 | } 100 | //Write plain record to file 101 | writeTable(prefix, name, m, result, resultF, flowFile, session) 102 | } 103 | 104 | /* 105 | / parseJSONA - parse list object 106 | / main_id = Id of whole record 107 | / parent_id = Id of parent level record 108 | / prefix = prefix to fields 109 | / name = name of created record 110 | / flowFile = file to clone 111 | / session = session to operate flowFiles 112 | */ 113 | def parseJSONA(String main_id, String id, String prefix, String name, List js, Map resultF, Map result, FlowFile flowFile, ProcessSession session) { 114 | if (js instanceof List) { 115 | //Additional check for call in main level 116 | for (def item in js) { 117 | //Iterate objects in list 118 | if (item instanceof Map) 119 | //Parse map recursively 120 | parseJSON(main_id, id, prefix, name, item, resultF, result, flowFile, session) 121 | else if (item instanceof List) { 122 | //Parse list recursively 123 | parseJSONA(main_id, id, prefix, name, item, resultF, result, flowFile, session) 124 | } else { 125 | //Create record from plain fields 126 | def m = [:] 127 | if (!id.isBlank()) { 128 | m.put("parent_id", id) 129 | } 130 | if (!main_id.isBlank()) { 131 | m.put("main_id", main_id) 132 | } 133 | m.put(translateName("value"), item) 134 | writeTable(prefix, name, m, result, resultF, flowFile, session) 135 | } 136 | } 137 | } 138 | } 139 | 140 | //Main Cycle 141 | def prefix='TRN' 142 | def table='transaction' 143 | session.read(srcflowFile, 144 | { it -> 145 | try { 146 | def ir = new InputStreamReader(it, 'UTF-8') 147 | def json = new JsonSlurper().parseText(ir.getText()) 148 | if (json instanceof Map) { 149 | parseJSON("", "", prefix, table, json, resultFiles, resultOut, srcflowFile, session) 150 | } else if (json instanceof List) { 151 | parseJSONA("", "", prefix, table, json, resultFiles, resultOut, srcflowFile, session) 152 | } 153 | } catch (Exception e) { 154 | throw e 155 | } 156 | } as InputStreamCallback 157 | ) 158 | 159 | //Sending completed files to Success 160 | for (String key : resultFiles.keySet()) { 161 | resultOut.get(key).close() 162 | def ff = session.putAttribute(resultFiles.get(key), "table.name", key) 163 | session.transfer(ff, REL_SUCCESS) 164 | } 165 | session.remove(srcflowFile) 166 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Convert/Encoding/UTF-16LE_with_BOM.xml: -------------------------------------------------------------------------------- 1 | 2 |