{"info":{"_postman_id":"08c0bb83-20cc-41ec-81be-2a7e2304f0e8","name":"NGSI-LD Real-time Processing (Spark)","description":"<html><head></head><body><p>This tutorial is an introduction to the <a href=\"http://fiware-cosmos-spark.rtfd.io\">FIWARE Cosmos Orion Spark Connector</a>, which\nenables easier Big Data analysis over context, integrated with one of the most popular BigData platforms:\n<a href=\"https://spark.apache.org/\">Apache Spark</a>. Apache Spark is a framework and distributed processing engine for stateful\ncomputations over unbounded and bounded data streams. Spark has been designed to run in all common cluster environments,\nperform computations at in-memory speed and at any scale.</p>\n<p>The <code>docker-compose</code> file for this tutorial can be found on GitHub: </p>\n<p><img src=\"https://fiware.github.io/tutorials.Big-Data-Flink/icon/GitHub-Mark-32px.png\" alt=\"GitHub\"> <a href=\"https://github.com/FIWARE/tutorials.Big-Data-Flink\">FIWARE-LD 305: Big Data Analysis (Flink) </a></p>\n<h1 id=\"real-time-processing-and-big-data-analysis\">Real-time Processing and Big Data Analysis</h1>\n<blockquote>\n<p>\"You have to find what sparks a light in you so that you in your own way can illuminate the world.\"</p>\n<p>— Oprah Winfrey</p>\n</blockquote>\n<p>Smart solutions based on FIWARE are architecturally designed around microservices. They are therefore are designed to\nscale-up from simple applications (such as the Supermarket tutorial) through to city-wide installations base on a large\narray of IoT sensors and other context data providers.</p>\n<p>The massive amount of data involved eventually becomes too much for a single machine to analyse, process and store, and\ntherefore the work must be delegated to additional distributed services. These distributed systems form the basis of\nso-called <strong>Big Data Analysis</strong>. The distribution of tasks allows developers to be able to extract insights from huge\ndata sets which would be too complex to be dealt with using traditional methods. and uncover hidden patterns and\ncorrelations.</p>\n<p>As we have seen, context data is core to any Smart Solution, and the Context Broker is able to monitor changes of state\nand raise <a href=\"https://github.com/Fiware/tutorials.Subscriptions\">subscription events</a> as the context changes. For smaller\ninstallations, each subscription event can be processed one-by-one by a single receiving endpoint, however as the system\ngrows, another technique will be required to avoid overwhelming the listener, potentially blocking resources and missing\nupdates.</p>\n<p><strong>Apache Spark</strong> is an open-source distributed general-purpose cluster-computing framework. It provides an interface for\nprogramming entire clusters with implicit data parallelism and fault tolerance. The <strong>Cosmos Spark</strong> connector allows\ndevelopers write custom business logic to listen for context data subscription events and then process the flow of the\ncontext data. Spark is able to delegate these actions to other workers where they will be acted upon either in\nsequentially or in parallel as required. The data flow processing itself can be arbitrarily complex.</p>\n<p>Obviously, in reality, our existing Supermarket scenario is far too small to require the use of a Big Data solution, but\nwill serve as a basis for demonstrating the type of real-time processing which may be required in a larger solution\nwhich is processing a continuous stream of context-data events.</p>\n<h1 id=\"architecture\">Architecture</h1>\n<p>This application builds on the components and dummy IoT devices created in\n<a href=\"https://github.com/FIWARE/tutorials.IoT-Agent/\">previous tutorials</a>. It will make use of three FIWARE components - the\n<a href=\"https://fiware-orion.readthedocs.io/en/latest/\">Orion Context Broker</a>, the\n<a href=\"https://fiware-iotagent-ul.readthedocs.io/en/latest/\">IoT Agent for Ultralight 2.0</a>, and the\n<a href=\"https://fiware-cosmos-spark.readthedocs.io/en/latest/\">Cosmos Orion Spark Connector</a> for connecting Orion to an\n<a href=\"https://spark.apache.org/docs/latest/cluster-overview.html\">Apache Spark cluster</a>. The Spark cluster itself will\nconsist of a single <strong>Cluster Manager</strong> <em>master</em> to coordinate execution and some <strong>Worker Nodes</strong> <em>worker</em> to execute\nthe tasks.</p>\n<p>Both the Orion Context Broker and the IoT Agent rely on open source <a href=\"https://www.mongodb.com/\">MongoDB</a> technology to\nkeep persistence of the information they hold. We will also be using the dummy IoT devices created in the\n<a href=\"https://github.com/FIWARE/tutorials.IoT-Agent/\">previous tutorial</a>.</p>\n<p>Therefore the overall architecture will consist of the following elements:</p>\n<ul>\n<li>Two <strong>FIWARE Generic Enablers</strong> as independent microservices:<ul>\n<li>The <a href=\"https://fiware-orion.readthedocs.io/en/latest/\">Orion Context Broker</a> which will receive requests using\n<a href=\"https://forge.etsi.org/swagger/ui/?url=https://forge.etsi.org/gitlab/NGSI-LD/NGSI-LD/raw/master/spec/updated/full_api.json\">NGSI-LD</a></li>\n<li>The FIWARE <a href=\"https://fiware-iotagent-ul.readthedocs.io/en/latest/\">IoT Agent for UltraLight 2.0</a> which will\nreceive southbound requests using\n<a href=\"https://forge.etsi.org/swagger/ui/?url=https://forge.etsi.org/gitlab/NGSI-LD/NGSI-LD/raw/master/spec/updated/full_api.json\">NGSI-LD</a>\nand convert them to\n<a href=\"https://fiware-iotagent-ul.readthedocs.io/en/latest/usermanual/index.html#user-programmers-manual\">UltraLight 2.0</a>\ncommands for the devices</li>\n</ul>\n</li>\n<li>An <a href=\"https://spark.apache.org/docs/latest/cluster-overview.html\">Apache Spark cluster</a> consisting of a single\n<strong>ClusterManager</strong> and <strong>Worker Nodes</strong><ul>\n<li>The FIWARE <a href=\"https://fiware-cosmos-spark.readthedocs.io/en/latest/\">Cosmos Orion Spark Connector</a> will be\ndeployed as part of the dataflow which will subscribe to context changes and make operations on them in\nreal-time</li>\n</ul>\n</li>\n<li>One <a href=\"https://www.mongodb.com/\">MongoDB</a> <strong>database</strong> :<ul>\n<li>Used by the <strong>Orion Context Broker</strong> to hold context data information such as data entities, subscriptions and\nregistrations</li>\n<li>Used by the <strong>IoT Agent</strong> to hold device information such as device URLs and Keys</li>\n</ul>\n</li>\n<li>The <strong>Tutorial Application</strong> does the following:<ul>\n<li>Offers static <code>@context</code> files defining the context entities within the system.</li>\n<li>Acts as set of dummy <a href=\"https://github.com/FIWARE/tutorials.IoT-Sensors/tree/NGSI-LD\">agricultural IoT devices</a>\nusing the\n<a href=\"https://fiware-iotagent-ul.readthedocs.io/en/latest/usermanual/index.html#user-programmers-manual\">UltraLight 2.0</a></li>\n</ul>\n</li>\n</ul>\n<p>The overall architecture can be seen below:</p>\n<p><img src=\"https://fiware.github.io/tutorials.Big-Data-Spark/img/Tutorial%20FIWARE%20Spark.png\" alt=\"\"></p>\n<h2 id=\"spark-cluster-configuration\">Spark Cluster Configuration</h2>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-yaml\">spark-master:\n    image: bde2020/spark-master:2.4.5-hadoop2.7\n    container_name: spark-master\n    expose:\n        - \"8080\"\n        - \"9001\"\n    ports:\n        - \"8080:8080\"\n        - \"7077:7077\"\n        - \"9001:9001\"\n    environment:\n        - INIT_DAEMON_STEP=setup_spark\n        - \"constraint:node==spark-master\"\n</code></pre>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-yaml\">spark-worker-1:\n    image: bde2020/spark-worker:2.4.5-hadoop2.7\n    container_name: spark-worker-1\n    depends_on:\n        - spark-master\n    ports:\n        - \"8081:8081\"\n    environment:\n        - \"SPARK_MASTER=spark://spark-master:7077\"\n        - \"constraint:node==spark-master\"\n</code></pre>\n<p>The <code>spark-master</code> container is listening on three ports:</p>\n<ul>\n<li>Port <code>8080</code> is exposed so we can see the web frontend of the Apache Spark-Master Dashboard.</li>\n<li>Port <code>7070</code> is used for internal communications.</li>\n</ul>\n<p>The <code>spark-worker-1</code> container is listening on one port:</p>\n<ul>\n<li>Port <code>9001</code> is exposed so that the installation can receive context data subscriptions.</li>\n<li>Ports <code>8081</code> is exposed so we can see the web frontend of the Apache Spark-Worker-1 Dashboard.</li>\n</ul>\n<h1 id=\"start-up\">Start Up</h1>\n<p>Before you start, you should ensure that you have obtained or built the necessary Docker images locally. Please clone\nthe repository and create the necessary images by running the commands shown below. Note that you might need to run some\nof the commands as a privileged user:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">git clone https://github.com/FIWARE/tutorials.Big-Data-Flink.git\ncd tutorials.Big-Data-Flink\ngit checkout NGSI-LD\n./services create\n</code></pre>\n<p>This command will also import seed data from the previous tutorials and provision the dummy IoT sensors on startup.</p>\n<p>To start the system, run the following command:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">./services start\n</code></pre>\n<blockquote>\n<p>:information_source: <strong>Note:</strong> If you want to clean up and start over again you can do so with the following command:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">./services stop\n</code></pre>\n</blockquote>\n<h1 id=\"real-time-processing-operations\">Real-time Processing Operations</h1>\n<p>According to the <a href=\"https://spark.apache.org/documentation.html\">Apache Spark documentation</a>, Spark Streaming is an\nextension of the core Spark API that enables scalable, high-throughput, fault-tolerant stream processing of live data\nstreams. Data can be ingested from many sources like Kafka, Flume, Kinesis, or TCP sockets, and can be processed using\ncomplex algorithms expressed with high-level functions like map, reduce, join and window. Finally, processed data can be\npushed out to filesystems, databases, and live dashboards. In fact, you can apply Spark’s machine learning and graph\nprocessing algorithms on data streams.</p>\n<p><img src=\"https://spark.apache.org/docs/latest/img/streaming-arch.png\" alt=\"\"></p>\n<p>Internally, it works as follows. Spark Streaming receives live input data streams and divides the data into batches,\nwhich are then processed by the Spark engine to generate the final stream of results in batches.</p>\n<p><img src=\"https://spark.apache.org/docs/latest/img/streaming-flow.png\" alt=\"\"></p>\n<p>This means that to create a streaming data flow we must supply the following:</p>\n<ul>\n<li>A mechanism for reading Context data as a <strong>Source Operator</strong></li>\n<li>Business logic to define the transform operations</li>\n<li>A mechanism for pushing Context data back to the context broker as a <strong>Sink Operator</strong></li>\n</ul>\n<p>The <strong>Cosmos Spark</strong> connector - <code>orion.spark.connector-1.2.2.jar</code> offers both <strong>Source</strong> and <strong>Sink</strong> operators. It\ntherefore only remains to write the necessary Scala code to connect the streaming dataflow pipeline operations together.\nThe processing code can be complied into a JAR file which can be uploaded to the spark cluster. Two examples will be\ndetailed below, all the source code for this tutorial can be found within the\n<a href=\"https://github.com/ging/fiware-cosmos-orion-spark-connector-tutorial/tree/master/cosmos-examples\">cosmos-examples</a>\ndirectory.</p>\n<p>Further Spark processing examples can be found on\n<a href=\"https://fiware-cosmos-spark-examples.readthedocs.io/\">Spark Connector Examples</a>.</p>\n<h3 id=\"compiling-a-jar-file-for-spark\">Compiling a JAR file for Spark</h3>\n<p>An existing <code>pom.xml</code> file has been created which holds the necessary prerequisites to build the examples JAR file</p>\n<p>In order to use the Orion Spark Connector we first need to manually install the connector JAR as an artifact using\nMaven:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">cd cosmos-examples\ncurl -LO https://github.com/ging/fiware-cosmos-orion-spark-connector/releases/download/FIWARE_7.9.1/orion.spark.connector-1.2.2.jar\nmvn install:install-file \\\n  -Dfile=./orion.spark.connector-1.2.2.jar \\\n  -DgroupId=org.fiware.cosmos \\\n  -DartifactId=orion.spark.connector \\\n  -Dversion=1.2.2 \\\n  -Dpackaging=jar\n</code></pre>\n<p>Thereafter the source code can be compiled by running the <code>mvn package</code> command within the same directory\n(<code>cosmos-examples</code>):</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">mvn package\n</code></pre>\n<p>A new JAR file called <code>cosmos-examples-1.2.2.jar</code> will be created within the <code>cosmos-examples/target</code> directory.</p>\n<h3 id=\"generating-a-stream-of-context-data\">Generating a stream of Context Data</h3>\n<p>For the purpose of this tutorial, we must be monitoring a system in which the context is periodically being updated. The\ndummy IoT Sensors can be used to do this. Open the device monitor page at <code>http://localhost:3000/device/monitor</code> and\nstart a tractor moving. This can be done by selecting an appropriate the command from\nthe drop down list and pressing the <code>send</code> button. The stream of measurements coming from the devices can then be seen\non the same page:</p>\n<p><img src=\"https://fiware.github.io/tutorials.Big-Data-Spark/img/farm-devices.gif\" alt=\"\"></p>\n<h2 id=\"logger---reading-context-data-streams\">Logger - Reading Context Data Streams</h2>\n<p>The first example makes use of the <code>OrionReceiver</code> operator in order to receive notifications from the Orion Context\nBroker. Specifically, the example counts the number notifications that each type of device sends in one minute. You can\nfind the source code of the example in\n<a href=\"https://github.com/ging/fiware-cosmos-orion-spark-connector-tutorial/blob/master/cosmos-examples/src/main/scala/org/fiware/cosmos/tutorial/Logger.scala\">org/fiware/cosmos/tutorial/Logger.scala</a></p>\n<h3 id=\"logger---installing-the-jar\">Logger - Installing the JAR</h3>\n<p>Restart the containers if necessary, then access the worker container:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">docker exec -it spark-worker-1 bin/bash\n</code></pre>\n<p>And run the following command to run the generated JAR package in the Spark cluster:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">/spark/bin/spark-submit \\\n--class  org.fiware.cosmos.tutorial.LoggerLD \\\n--master  spark://spark-master:7077 \\\n--deploy-mode client /home/cosmos-examples/target/cosmos-examples-1.2.2.jar \\\n--conf \"spark.driver.extraJavaOptions=-Dlog4jspark.root.logger=WARN,console\"\n</code></pre>\n</body></html>","schema":"https://schema.getpostman.com/json/collection/v2.0.0/collection.json","toc":[{"content":"Real-time Processing and Big Data Analysis","slug":"real-time-processing-and-big-data-analysis"},{"content":"Architecture","slug":"architecture"},{"content":"Start Up","slug":"start-up"},{"content":"Real-time Processing Operations","slug":"real-time-processing-operations"}],"owner":"513743","collectionId":"08c0bb83-20cc-41ec-81be-2a7e2304f0e8","publishedId":"TWDUqJNb","public":true,"customColor":{"top-bar":"FFFFFF","right-sidebar":"303030","highlight":"233c68"},"publishDate":"2021-02-17T12:37:57.000Z"},"item":[{"name":"Receiving context data and performing operations","item":[{"name":"Orion - Subscribe to Context Changes","id":"8d251bfc-02d8-4338-8449-19c6d9f1c3a0","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"POST","header":[{"key":"Content-Type","value":"application/ld+json"},{"key":"NGSILD-Tenant","value":"openiot"}],"body":{"mode":"raw","raw":"{\n  \"description\": \"Notify Flink of all animal and farm vehicle movements\",\n  \"type\": \"Subscription\",\n  \"entities\": [{\"type\": \"Tractor\"}, {\"type\": \"Device\"}],\n  \"watchedAttributes\": [\"location\"],\n  \"notification\": {\n    \"attributes\": [\"location\"],\n    \"format\": \"normalized\",\n    \"endpoint\": {\n      \"uri\": \"http://taskmanager:9001\",\n      \"accept\": \"application/json\"\n    }\n  },\n   \"@context\": \"http://context-provider:3000/data-models/ngsi-context.jsonld\"\n}"},"url":"http://localhost:1026/ngsi-ld/v1/subscriptions/","description":"<p>Once a dynamic context system is up and running (we have deployed the <code>Logger</code> job in the Spark cluster), we need to\ninform <strong>Spark</strong> of changes in context.</p>\n<p>This is done by making a POST request to the <code>/ngsi-ld/v1/subscriptions</code> endpoint of the Orion Context Broker.</p>\n<ul>\n<li><p>The <code>NGSILD-Tenant</code> header is used to filter the subscription to only listen to\nmeasurements from the attached IoT Sensors, since they had been provisioned using these settings</p>\n</li>\n<li><p>The notification <code>uri</code> must match the one our Flink program is listening to.</p>\n</li>\n<li><p>The <code>throttling</code> value defines the rate that changes are sampled.</p>\n</li>\n</ul>\n<p>The response will be <strong><code>201 - Created</code></strong></p>\n","urlObject":{"protocol":"http","path":["ngsi-ld","v1","subscriptions",""],"host":["localhost:1026"],"query":[],"variable":[]}},"response":[],"_postman_id":"8d251bfc-02d8-4338-8449-19c6d9f1c3a0"},{"name":"Orion - Check Subscription is working","id":"7ef7d820-b70f-4ee7-8ead-7cc5860040fa","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"GET","header":[{"key":"NGSILD-Tenant","value":"openiot"}],"url":"http://localhost:1026/ngsi-ld/v1/subscriptions/","description":"<p>If a subscription has been created, we can check to see if it is firing by making a GET request to the\n<code>/ngsi-ld/v1/subscriptions/</code> endpoint.Within the <code>notification</code> section of the response, you can see several additional <code>attributes</code> which describe the health\nof the subscription</p>\n<p>If the criteria of the subscription have been met, <code>timesSent</code> should be greater than <code>0</code>. A zero value would indicate\nthat the <code>subject</code> of the subscription is incorrect or the subscription has created with the wrong <code>fiware-service-path</code>\nor <code>fiware-service</code> header</p>\n<p>The <code>lastNotification</code> should be a recent timestamp - if this is not the case, then the devices are not regularly\nsending data. Remember to activate the smart farm by moving a <strong>Tractor</strong></p>\n<p>The <code>lastSuccess</code> should match the <code>lastNotification</code> date - if this is not the case then <strong>Cosmos</strong> is not receiving\nthe subscription properly. Check that the hostname and port are correct.</p>\n<p>Finally, check that the <code>status</code> of the subscription is <code>active</code> - an expired subscription will not fire.</p>\n","urlObject":{"protocol":"http","path":["ngsi-ld","v1","subscriptions",""],"host":["localhost:1026"],"query":[],"variable":[]}},"response":[],"_postman_id":"7ef7d820-b70f-4ee7-8ead-7cc5860040fa"}],"id":"b5e5f21b-b0e6-4afa-9725-0aefc5aa0e22","description":"<p>The first example makes use of the <code>OrionReceiver</code> operator in order to receive notifications from the Orion Context\nBroker. Specifically, the example counts the number notifications that each type of device sends in one minute. You can\nfind the source code of the example in\n<a href=\"https://github.com/ging/fiware-cosmos-orion-spark-connector-tutorial/blob/master/cosmos-examples/src/main/scala/org/fiware/cosmos/tutorial/Logger.scala\">org/fiware/cosmos/tutorial/Logger.scala</a></p>\n<h3 id=\"logger---installing-the-jar\">Logger - Installing the JAR</h3>\n<p>Restart the containers if necessary, then access the worker container:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">docker exec -it spark-worker-1 bin/bash\n</code></pre>\n<p>And run the following command to run the generated JAR package in the Spark cluster:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">/spark/bin/spark-submit \\\n--class  org.fiware.cosmos.tutorial.LoggerLD \\\n--master  spark://spark-master:7077 \\\n--deploy-mode client /home/cosmos-examples/target/cosmos-examples-1.2.2.jar \\\n--conf \"spark.driver.extraJavaOptions=-Dlog4jspark.root.logger=WARN,console\"\n</code></pre>\n<h3 id=\"logger---checking-the-output\">Logger - Checking the Output</h3>\n<p>Leave the subscription running for <strong>one minute</strong>. Then, the output on the console on which you ran the Spark job will\nbe like the following:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-text\">Sensor(Tractor,19)\nSensor(Device,49)\n</code></pre>\n<h3 id=\"logger---analyzing-the-code\">Logger - Analyzing the Code</h3>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-scala\">package org.fiware.cosmos.tutorial\nimport org.apache.spark._\nimport org.apache.spark.streaming.{Seconds, StreamingContext}\nimport org.fiware.cosmos.orion.spark.connector._\n\n\nobject LoggerLD{\n\n  def main(args: Array[String]): Unit = {\n\n    val conf = new SparkConf().setAppName(\"Example 1\")\n    val ssc = new StreamingContext(conf, Seconds(60))\n    // Create Orion Receiver. Receive notifications on port 9001\n    val eventStream = ssc.receiverStream(new NGSILDReceiver(9001))\n\n    // Process event stream\n    eventStream\n      .flatMap(event =&gt; event.entities)\n      .map(ent =&gt; {\n        new Sensor(ent.`type`)\n      })\n      .countByValue()\n      .window(Seconds(60))\n      .print()\n\n\n    ssc.start()\n    ssc.awaitTermination()\n  }\n  case class Sensor(device: String)\n}\n</code></pre>\n<p>The first lines of the program are aimed at importing the necessary dependencies, including the connector. The next step\nis to create an instance of the <code>NGSILDReceiver</code> using the class provided by the connector and to add it to the\nenvironment provided by Spark.</p>\n<p>The <code>NGSILDReceiver</code> constructor accepts a port number (<code>9001</code>) as a parameter. This port is used to listen to the\nsubscription notifications coming from Orion and converted to a <code>DataStream</code> of <code>NgsiEvent</code> objects. The definition of\nthese objects can be found within the\n<a href=\"https://github.com/ging/fiware-cosmos-orion-spark-connector/blob/master/README.md#orionreceiver\">Orion-Spark Connector documentation</a>.</p>\n<p>The stream processing consists of five separate steps. The first step (<code>flatMap()</code>) is performed in order to put\ntogether the entity objects of all the NGSI Events received in a period of time. Thereafter the code iterates over them\n(with the <code>map()</code> operation) and extracts the desired attributes. In this case, we are interested in the sensor <code>type</code>\n(<code>Device</code> or <code>Tractor</code>).</p>\n<p>Within each iteration, we create a custom object with the property we need: the sensor <code>type</code>. For this purpose, we can\ndefine a case class as shown:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-scala\">case class Sensor(device: String)\n</code></pre>\n<p>Thereafter can count the created objects by the type of device (<code>countByValue()</code>) and perform operations such as\n<code>window()</code> on them.</p>\n<p>After the processing, the results are output to the console:</p>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-scala\">processedDataStream.print()\n</code></pre>\n","event":[{"listen":"prerequest","script":{"id":"645407fc-e970-4fac-bfb9-0c33c9d51305","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"5d338376-1293-4d1c-8e87-9944a0360e8b","type":"text/javascript","exec":[""]}}],"_postman_id":"b5e5f21b-b0e6-4afa-9725-0aefc5aa0e22"},{"name":"Receiving context data, performing operations and persisting context data","item":[{"name":"Orion - Subscribe to Context Changes","id":"f5ad07ba-5853-413b-a9f1-6bb722c766cb","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"POST","header":[{"key":"Content-Type","value":"application/ld+json"},{"key":"NGSILD-Tenant","value":"openiot"}],"body":{"mode":"raw","raw":"'{\n  \"description\": \"Notify Flink of changes of Soil Humidity\",\n  \"type\": \"Subscription\",\n  \"entities\": [{\"type\": \"SoilSensor\"}],\n  \"watchedAttributes\": [\"humidity\"],\n  \"notification\": {\n    \"attributes\": [\"humidity\"],\n    \"format\": \"normalized\",\n    \"endpoint\": {\n      \"uri\": \"http://flink-taskmanager:9001\",\n      \"accept\": \"application/json\"\n    }\n  },\n   \"@context\": \"http://context-provider:3000/data-models/ngsi-context.jsonld\"\n}'"},"url":"http://localhost:1026/ngsi-ld/v1/subscriptions/","description":"<p>A new subscription needs to be set up to run this example. The subscription is listening to changes of context on the soil humidity sensor.</p>\n","urlObject":{"protocol":"http","path":["ngsi-ld","v1","subscriptions",""],"host":["localhost:1026"],"query":[],"variable":[]}},"response":[],"_postman_id":"f5ad07ba-5853-413b-a9f1-6bb722c766cb"},{"name":"Orion - Check Subscription is working","id":"52eba681-0cd5-4fc7-8817-8fa310a7ff58","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"GET","header":[{"key":"fiware-service","value":"openiot"},{"key":"fiware-servicepath","value":"/"}],"url":"http://localhost:1026/ngsi-ld/v1/subscriptions/","description":"<p>If a subscription has been created, we can check to see if it is firing by making a GET request to the\n<code>/ngsi-ld/v1/subscriptions/</code> endpoint.</p>\n","urlObject":{"protocol":"http","path":["ngsi-ld","v1","subscriptions",""],"host":["localhost:1026"],"query":[],"variable":[]}},"response":[],"_postman_id":"52eba681-0cd5-4fc7-8817-8fa310a7ff58"},{"name":"Orion - Delete Subscription","id":"3b33880c-364f-411a-88e5-60c1e4ec76d9","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"DELETE","header":[{"key":"fiware-service","value":"openiot"},{"key":"fiware-servicepath","value":"/"}],"body":{"mode":"raw","raw":""},"url":"http://localhost:1026/ngsi-ld/v1/subscriptions/5e134a0c924f6d7d27b63844","description":"<p>If necessary an old subscription can be deleted by referencing its subscription id.</p>\n","urlObject":{"protocol":"http","path":["ngsi-ld","v1","subscriptions","5e134a0c924f6d7d27b63844"],"host":["localhost:1026"],"query":[],"variable":[]}},"response":[],"_postman_id":"3b33880c-364f-411a-88e5-60c1e4ec76d9"}],"id":"fe77c1fa-211e-4fb6-b73c-7a047ae07d4f","description":"<p>The second example turns on a water faucet when the soil humidity is too low and turns it back off it when the soil humidity it is back to normal levels. This way, the soil humidity is always kept at an adequate level.</p>\n<p>The dataflow stream uses the <code>NGSILDReceiver</code> operator in order to receive notifications and filters the input to only respond to motion senseors and then uses the <code>NGSILDSink</code> to push processed context back to the Context Broker. You can find the source code of the example in\n<a href=\"https://github.com/ging/fiware-cosmos-orion-spark-connector-tutorial/blob/master/cosmos-examples/src/main/scala/org/fiware/cosmos/tutorial/FeedbackLD.scala\">org/fiware/cosmos/tutorial/FeedbackLD.scala</a></p>\n<h3 id=\"feedback-loop---installing-the-jar\">Feedback Loop - Installing the JAR</h3>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-console\">/spark/bin/spark-submit  \\\n--class  org.fiware.cosmos.tutorial.FeedbackLD \\\n--master  spark://spark-master:7077 \\\n--deploy-mode client /home/cosmos-examples/target/cosmos-examples-1.2.2.jar \\\n--conf \"spark.driver.extraJavaOptions=-Dlog4jspark.root.logger=WARN,console\"\n</code></pre>\n<h3 id=\"feedback-loop---checking-the-output\">Feedback Loop - Checking the Output</h3>\n<p>Go to <code>http://localhost:3000/device/monitor</code></p>\n<p>Raise the temperature in Farm001 and wait until the humidity value is below 35, then the water faucet will be automatically turned on to increase the soil humidity. When the humidity rises above 50, the water faucet will be turned off automatically as well.</p>\n<h3 id=\"feedback-loop---analyzing-the-code\">Feedback Loop - Analyzing the Code</h3>\n<pre class=\"click-to-expand-wrapper is-snippet-wrapper\"><code class=\"language-scala\">package org.fiware.cosmos.tutorial\n\nimport org.apache.spark._\nimport org.apache.spark.streaming.{Seconds, StreamingContext}\nimport org.fiware.cosmos.orion.spark.connector._\n\nobject FeedbackLD {\n  final val CONTENT_TYPE = ContentType.JSON\n  final val METHOD = HTTPMethod.PATCH\n  final val CONTENT = \"{\\n  \\\"type\\\" : \\\"Property\\\",\\n  \\\"value\\\" : \\\" \\\" \\n}\"\n  final val HEADERS = Map(\n    \"NGSILD-Tenant\" -&gt; \"openiot\",\n    \"Link\" -&gt; \"&lt;http://context-provider:3000/data-models/ngsi-context.jsonld&gt;; rel=\\\"http://www.w3.org/ns/json-ld#context\\\"; type=\\\"application/ld+json\\\"\"\n  )\n  final val LOW_THRESHOLD = 35\n  final val HIGH_THRESHOLD = 50\n  def main(args: Array[String]): Unit = {\n\n    val conf = new SparkConf().setAppName(\"Feedback\")\n    val ssc = new StreamingContext(conf, Seconds(10))\n\n    // Create Orion Receiver. Receive notifications on port 9001\n    val eventStream = ssc.receiverStream(new NGSILDReceiver(9001))\n\n    // Process event stream\n    val processedDataStream = eventStream.flatMap(event =&gt; event.entities)\n      .filter(ent =&gt; ent.`type` == \"SoilSensor\")\n\n    /* High humidity */\n    val highHumidity = processedDataStream\n      .filter(ent =&gt;  (ent.attrs(\"humidity\") != null) &amp;&amp; (ent.attrs(\"humidity\")(\"value\").asInstanceOf[BigInt] &gt; HIGH_THRESHOLD))\n      .map(ent =&gt; (ent.id,ent.attrs(\"humidity\")(\"value\")))\n\n    val highSinkStream= highHumidity.map(sensor =&gt; {\n      OrionSinkObject(CONTENT,\"http://orion:1026/ngsi-ld/v1/entities/urn:ngsi-ld:Device:water\"+sensor._1.takeRight(3)+\"/attrs/off\",CONTENT_TYPE,METHOD,HEADERS)\n    })\n\n    highHumidity.map(sensor =&gt; \"Sensor\" + sensor._1 + \" has detected a humidity level above \" + HIGH_THRESHOLD + \". Turning off water faucet!\").print()\n    OrionSink.addSink( highSinkStream )\n\n\n    /* Low humidity */\n    val lowHumidity = processedDataStream\n      .filter(ent =&gt; (ent.attrs(\"humidity\") != null) &amp;&amp; (ent.attrs(\"humidity\")(\"value\").asInstanceOf[BigInt] &lt; LOW_THRESHOLD))\n      .map(ent =&gt; (ent.id,ent.attrs(\"humidity\")(\"value\")))\n\n    val lowSinkStream= lowHumidity.map(sensor =&gt; {\n      OrionSinkObject(CONTENT,\"http://orion:1026/ngsi-ld/v1/entities/urn:ngsi-ld:Device:water\"+sensor._1.takeRight(3)+\"/attrs/on\",CONTENT_TYPE,METHOD,HEADERS)\n    })\n\n    lowHumidity.map(sensor =&gt; \"Sensor\" + sensor._1 + \" has detected a humidity level below \" + LOW_THRESHOLD + \". Turning on water faucet!\").print()\n    OrionSink.addSink( lowSinkStream )\n\n    ssc.start()\n    ssc.awaitTermination()\n  }\n}\n</code></pre>\n<p>As you can see, it is similar to the previous example. The main difference is that it writes the processed data back in the Context Broker through the <strong><code>OrionSink</code></strong>.</p>\n<p>The arguments of the <strong><code>OrionSinkObject</code></strong> are:</p>\n<ul>\n<li><strong>Message</strong>: <code>\"{\\n  \\\"type\\\" : \\\"Property\\\",\\n  \\\"value\\\" : \\\" \\\" \\n}\"</code>.</li>\n<li><strong>URL</strong>: <code>\"http://orion:1026/ngsi-ld/v1/entities/urn:ngsi-ld:Device:water\"+sensor._1.takeRight(3)+\"/attrs/on\"</code> or <code>\"http://orion:1026/ngsi-ld/v1/entities/urn:ngsi-ld:Device:water\"+sensor._1.takeRight(3)+\"/attrs/off\"</code>, depending on whether we are turning on or off the water faucet. TakeRight(3) gets the number of\nthe sensor, for example '001'.</li>\n<li><strong>Content Type</strong>: <code>ContentType.JSON</code>.</li>\n<li><strong>HTTP Method</strong>: <code>HTTPMethod.PATCH</code>.</li>\n<li><strong>Headers</strong>: <code>Map(\"NGSILD-Tenant\" -&gt; \"openiot\", \"Link\" -&gt; \"&lt;http://context-provider:3000/data-models/ngsi-context.jsonld&gt;; rel=\\\"http://www.w3.org/ns/json-ld#context\\\"; type=\\\"application/ld+json\\\"\" )</code>.\nWe add the headers we need in the HTTP Request.</li>\n</ul>\n","event":[{"listen":"prerequest","script":{"id":"6bbf67fc-0308-443b-a61b-0ea8cb9cd3d6","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"05ff23e9-b8d3-4f1a-9ccd-a456fc4f4cf2","type":"text/javascript","exec":[""]}}],"_postman_id":"fe77c1fa-211e-4fb6-b73c-7a047ae07d4f"}],"event":[{"listen":"prerequest","script":{"id":"8ac322d1-1356-4ff5-b344-2ce3e2a77749","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"bfa2d737-57d9-4054-beb0-48bb2cf25769","type":"text/javascript","exec":[""]}}],"variable":[{"key":"orion","value":"localhost:1026"},{"key":"subscriptionId","value":"5e134a0c924f6d7d27b63844"}]}