Skip to content

Instantly share code, notes, and snippets.

@monilpat
Created August 3, 2016 21:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monilpat/b475d06efd411753ba3b9552f54550df to your computer and use it in GitHub Desktop.
Save monilpat/b475d06efd411753ba3b9552f54550df to your computer and use it in GitHub Desktop.
import java.nio.charset.StandardCharsets
import org.apache.commons.io.IOUtils
import org.apache.nifi.processor.io.StreamCallback
import groovy.transform.ToString
import com.vader.SentimentAnalyzer
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def flowFile = session.get()
if(!flowFile) return
flowFile=session.write(flowFile,{inputStream, outputStream ->
// ---------------PART ONE------------------
def jsonString = IOUtils.toString(inputStream, StandardCharsets.UTF_8) // Json String
def original=new JsonSlurper().parseText(jsonString) // JSON object
def tweetText= original.text // Gets text of tweet
// Puts text into Sentiment Analyzer
// ---------------PART TWO------------------
SentimentAnalyzer sentimentAnalyzer=new SentimentAnalyzer(tweetText)
sentimentAnalyzer.analyse()
def map=sentimentAnalyzer.getPolarity()
// Gets each of the scores
def posValue=map['positive']
def negValue=map['negative']
def neuValue=map['neutral']
def compValue=map['compound']
// Converts them to string
def pos=posValue.toString()
def neg=negValue.toString()
def neu=neuValue.toString()
def comp=compValue.toString()
// ---------------PART THREE------------------
// Creates second Json
def sentimentScore =new JsonBuilder()
def root=sentimentScore pos: pos, neg:neg, neu:neu,comp:comp, tweetText: tweetText
// concatentates both jsons
def finalPart=JsonOutput.toJson([original: original, sentimentScore: sentimentScore])
outputStream.write(finalPart.toString().getBytes(StandardCharsets.UTF_8))
} as StreamCallback)
// Successful transfer and exit
session.transfer(flowFile, REL_SUCCESS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment