Monday, March 14, 2016

ExecuteScript - JSON-to-JSON Revisited (with Jython)

I've received some good comments about a couple of previous blog posts on using the ExecuteScript processor in NiFi (0.5.0+) to perform JSON-to-JSON transformations. One post used Groovy and the other used Javascript.

Since then I've received some requests for a Jython example for ExecuteScript, so I figured I'd do the same use case again (JSON to JSON) so folks can see the differences in the languages when performing the same operations :)

The approach has been covered in detail in the other posts, so I will talk a bit about the Jython-specific stuff and then get right to the code.

One major caveat here is that I don't know Python :)  I learned enough to get the script working, but please let me know how to better do any of this. I stopped touching the script once it worked, so it's very possible there are unnecessary imports, classes, etc.

The first thing to do is to bring in the Jython libraries you will need, as well as importing the Java and NiFi classes to be used:
import json
import java.io
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback

I didn't need to import java.lang.String as Jython does type coercion. I probably couldn't call getBytes() on that string unless Jython knew to coerce the object to a Java String, but that's ok because we can call bytearray("myString".encode('utf-8')) to achieve the same results.

The next task was to create a StreamCallback object for use in session.write(). I created a Jython class for this and overrode the interface method:
class PyStreamCallback(StreamCallback):
  def __init__(self):
        pass
  def process(self, inputStream, outputStream):
        # ...

After that, I read in and parsed the JSON text with IOUtils then json.loads(), then performed all the operations on the various parts of the object/dictionary. Finally I generated a new JSON string with json.dumps(), encoded to UTF-8, got the byte array, and wrote it to the output stream.

The resulting script is as follows:
import json
import java.io
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback

class PyStreamCallback(StreamCallback):
  def __init__(self):
        pass
  def process(self, inputStream, outputStream):
    text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
    obj = json.loads(text)
    newObj = {
          "Range": 5,
          "Rating": obj['rating']['primary']['value'],
          "SecondaryRatings": {}
        }
    for key, value in obj['rating'].iteritems():
      if key != "primary":
        newObj['SecondaryRatings'][key] = {"Id": key, "Range": 5, "Value": value['value']}
              
    outputStream.write(bytearray(json.dumps(newObj, indent=4).encode('utf-8'))) 

flowFile = session.get()
if (flowFile != None):
  flowFile = session.write(flowFile,PyStreamCallback())
  flowFile = session.putAttribute(flowFile, "filename", flowFile.getAttribute('filename').split('.')[0]+'_translated.json')
  session.transfer(flowFile, REL_SUCCESS)

The template is available as a Gist (here). I welcome all suggestions on how to make this better, and please share any scripts you come up with!

Cheers!

9 comments:

  1. I modified your template to convert timestamps in JSON from a String to a Long:
    https://gist.github.com/ryanpersaud/734b68e3624d06433deaa114acc33865

    ReplyDelete
  2. When you make this call to the callback

    flowFile = session.write(flowFile,PyStreamCallback())

    can I treat inputStream as I would any file pointer - in other words, read in my records using csv.DictReader(inputStream, fieldnames) , for example? It would be helpful if I could do that rather than use a list iterator to iterate through the records.

    Thanks in advance for any comments.

    ReplyDelete
  3. Not sure, you might need FileUtil to wrap() the input stream: http://www.jython.org/javadoc/org/python/core/util/FileUtil.html

    ReplyDelete
  4. I'd like to append Attributes for a flowFile in my processing workflow to a disk file I use as a log. I need to create the output file on the first access attempt if it is not there, but if it exists I want to append to the contents that are already there.

    This script above is very helpful, and shows me how I can customize the Attributes of the flowFile out of this ExecuteScript processor. But the putFile processor that might follow only affords us the option to create a new output file each time. Is there an example that would demonstrate how to append the flowFile attribute information to a log file each time without losing the previous contents of the output file?

    Thanks again.

    ReplyDelete
    Replies
    1. This will add current date as a string:

      import json
      import java.io
      from datetime import datetime
      from org.apache.commons.io import IOUtils
      from java.nio.charset import StandardCharsets
      from org.apache.nifi.processor.io import StreamCallback

      class PyStreamCallback(StreamCallback):
      def __init__(self):
      pass

      def process(self, inputStream, outputStream):
      text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
      flowFileJson = json.loads(text)
      today_sting = datetime.today().strftime('%Y-%m-%d')
      flowFileJson['current_date'] = today_sting

      outputStream.write(bytearray(json.dumps(flowFileJson, indent=4).encode('utf-8')))

      flowFile = session.get()
      if (flowFile != None):
      flowFile = session.write(flowFile,PyStreamCallback())
      session.transfer(flowFile, REL_SUCCESS)


      If you want to add this string to every json object in json array replace
      flowFileJson['current_date'] = today_sting
      with
      for j in flowFileJson:
      j['current_date'] = today_sting

      Delete
  5. I am trying to do something similar here, but I want to encrypt parts of the JSON. I have created some code that does the encryption, but it requires me to import some python modules, mainly the Cipher module. As seen at this link(https://repl.it/EJU7/0). However, nifi cannot recognize the "from Crypto.Cipher import AES" call. Do you know any workarounds for this or any way to fix this?

    ReplyDelete
  6. I keep getting the error "No module named Crypto" even though I added the module path "/Library/Python/2.7/site-packages/Crypto/Cipher/AES.pyc" to the module directory section.

    ReplyDelete
  7. ExecuteScript uses Jython, not Python. This means that it can't import native or compiled Python modules, just pure Python modules. Check the Jython documentation on this, perhaps there is a pure Python library for crypto that you can use instead.

    ReplyDelete
  8. Hi,

    I am very new to NIFI.
    I am getting error like :
    "Failed to process session due to process exception, SyntaxError : no viable alternative character '' in script at line ::: column number 0."

    Could somebody guide me.

    Code :
    import json
    import java.io
    from org.apache.commons.io import IOUtils
    from java.nio.charset import StandardCharsets
    from org.apache.nifi.processor.io import StreamCallback
    class PyStreamCallback(StreamCallback):
    def __init__(self):
    pass
    def process(self, inputStream, outputStream):
    text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
    newObj = {
    "Range": 5,
    "SecondaryRatings": {}
    }
    outputStream.write(bytearray(json.dumps(newObj, indent=4).encode('utf-8')))
    flowFile = session.get()
    if (flowFile != None):
    flowFile = session.write(flowFile, PyStreamCallback())
    session.transfer(flowFile, REL_SUCCESS)


    Here I am just sending newObj on any input stream just for POC thing

    ReplyDelete