├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── nifi-simulator-bundle-nar
└── pom.xml
├── nifi-simulator-bundle-processors
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── hashmap
│ │ │ └── tempus
│ │ │ └── processors
│ │ │ ├── DataValue.java
│ │ │ ├── GatewayValue.java
│ │ │ ├── GatewayValueSerializer.java
│ │ │ └── GenerateTimeSeriesFlowFile.java
│ ├── resources
│ │ └── META-INF
│ │ │ └── services
│ │ │ └── org.apache.nifi.processor.Processor
│ └── scala
│ │ └── com
│ │ └── hashmap
│ │ └── tempus
│ │ └── processors
│ │ └── SimController.scala
│ └── test
│ ├── java
│ └── com
│ │ └── hashmap
│ │ └── tempus
│ │ └── processors
│ │ └── GenerateTimeSeriesFlowfileTest.java
│ └── resources
│ └── configs
│ ├── basicConfig.json
│ └── unitTestConfig.json
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | *.zip
18 | *.tar.gz
19 | *.rar
20 |
21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
22 | hs_err_pid*
23 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | language: java
17 |
18 | env:
19 | - USER_LANGUAGE=en USER_REGION=US'
20 |
21 | os:
22 | - linux
23 |
24 | jdk:
25 | - oraclejdk8
26 |
27 | # Caches mvn repository in order to speed upbuilds
28 | cache:
29 | directories:
30 | - $HOME/.m2
31 |
32 | install:
33 | - mvn clean install
34 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](https://travis-ci.org/hashmapinc/nifi-simulator-bundle)
4 | [](http://www.apache.org/licenses/LICENSE-2.0.txt)
5 |
6 | # nifi-simulator-bundle
7 |
8 | ## Overview
9 | The Apache NiFi Simulator Bundle is a processor that wraps the great work done by the [TSimulus](https://github.com/cetic/TSimulus) project and provides a utility that allows for generating random, realistic time series data. This NiFi processor came out of a need not to just generate random data that looked like a sensor, but random data that acts like a real sensor. This allows a developer to test out far more of a system than just the throughput.
10 |
11 | The system is driven by a configuration file that defines the shape (patterns, noise, cycles, etc.) and then converts this data into a time series value.
12 |
13 | Additionally, this processor contains logic that allows the simulation to be run in real time, further making the simulation more realistic.
14 |
15 | ## Processor Usage
16 | As mentioned in the Overview section, this processor wraps TSimulus, however, It does include the facility to generate the data in real time. Additionally, the processor outputs the data to a NiFi flow file in a CSV format. Each exported value will be a new line.
17 |
18 | The flowfile will be output in the following format:
19 |
20 | | name | ts | value |
21 | |-------|-----------------------|------------------|
22 | |torque |2017-07-06T21:58:08.957|0.6081689813614467|
23 |
24 | There are 4 properties to the processor.
25 | 1. *Simulator Configuration File* - This is the location on disk where the TSimulus configuration file is located
26 | 2. *Print Header* - This is a boolean value which will indicate whether or not the **name,ts,value** header is printed in the flowfile
27 | 3. *Use Long Timestamp* - This is a boolean value which will indicate whether or not the time stamp will be represented as millisecond from the epoch (if true), or
28 | an ISO8601 compliant time zone.
29 | 4. *Timezone* - This is used to make a faithful conversion of the timestamp to milliseconds from the epoch. When the long timestamp option is used, this will direct the simulator how to configure
30 | the conversion.
31 | The intention of this processor is to be used along with the new Record-Based processors in Apache NiFi. A suggestion would be to use the following Avro schema in the Schema Registry controller service and then use the record processors to further operate on the data.
32 |
33 | {
34 | "name": "simulatorFormat",
35 | "namespace": "com.hashmap",
36 | "type": "record",
37 | "fields": [
38 | { "name": "name", "type": "String" },
39 | { "name": "timestamp", "type": "Timestamp" },
40 | { "name": "value", "type": "string" }
41 | ]
42 | }
43 |
44 | ## Configuration Documentation
45 | The configuration file documentation is located [here](http://tsimulus.readthedocs.io/en/latest/generators.html#configuration-document). This will explain how to build the JSON configuration document. NOTE: One caveat that needs to be mentioned, the configuration JSON document contains from and to elements which define the bounds of the set. While the simulator will still run when the simulation is run outside of those bounds, it is wise to set the to element to some point in the future, as the simulation tends to generate more realistic time data when the timestamp that data is being generated for lies within the bounds of the time window.
46 |
47 | ## Getting Started
48 | NOTE: The processor was built against the Apache NiFi 1.3 Maven Archtype.
49 |
50 | To build the library and get started first off clone the GitHub repository
51 |
52 | git clone https://github.com/hashmapinc/nifi-simulator-bundle.git
53 |
54 | Change directory into the WitsmlObjectsLibrary
55 |
56 | cd nifi-simulator-bundle
57 |
58 | Execute a maven clean install
59 |
60 | mvn clean install
61 |
62 | A Build success message should appear
63 |
64 | [INFO] ------------------------------------------------------------------------
65 | [INFO] BUILD SUCCESS
66 | [INFO] ------------------------------------------------------------------------
67 | [INFO] Total time: 13.271 s
68 | [INFO] Finished at: 2017-06-30T15:14:58-05:00
69 | [INFO] Final Memory: 20M/377M
70 | [INFO] ------------------------------------------------------------------------
71 |
72 | Navigate to the *nifi-simulator-bundle-nar/target* directory and copy the nifi-simulator-bundle-nar-1.0-SNAPSHOT.nar file to the Apache NiFi */lib* folder.
73 |
74 | Restart NiFi.
75 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-nar/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 | 4.0.0
18 |
19 |
20 | com.hashmap
21 | simulator-bundle
22 | 1.4.0
23 |
24 |
25 | nifi-simulator-bundle-nar
26 | 1.0-SNAPSHOT
27 | nar
28 |
29 | true
30 | true
31 |
32 |
33 |
34 |
35 | com.hashmap
36 | nifi-simulator-bundle-processors
37 | 1.4.0
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 | 4.0.0
18 |
19 |
20 | com.hashmap
21 | simulator-bundle
22 | 1.4.0
23 |
24 |
25 | nifi-simulator-bundle-processors
26 | jar
27 |
28 |
29 |
30 | org.apache.nifi
31 | nifi-api
32 |
33 |
34 | org.apache.nifi
35 | nifi-utils
36 |
37 |
38 | org.apache.nifi
39 | nifi-mock
40 | test
41 |
42 |
43 | org.slf4j
44 | slf4j-simple
45 | test
46 |
47 |
48 | junit
49 | junit
50 | test
51 |
52 |
53 | com.fasterxml.jackson.core
54 | jackson-databind
55 | 2.7.8
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/java/com/hashmap/tempus/processors/DataValue.java:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import com.fasterxml.jackson.annotation.JsonProperty;
6 |
7 | public class DataValue {
8 |
9 | @JsonProperty(value = "ts", index = 1)
10 | private String timeStamp;
11 |
12 | @JsonProperty(index = 2)
13 | private Map values;
14 |
15 |
16 | public String getTimeStamp(){
17 | return timeStamp;
18 | }
19 |
20 | public Map getValues(){
21 | return values;
22 | }
23 |
24 | public DataValue(){
25 | values = new HashMap<>();
26 | }
27 |
28 | public void setTimeStamp(String timeStamp){
29 | this.timeStamp = timeStamp;
30 | }
31 |
32 | public void addValue(String key, Object value){
33 | values.put(key, value);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/java/com/hashmap/tempus/processors/GatewayValue.java:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class GatewayValue {
7 |
8 | private String deviceName;
9 | private List dataValues;
10 |
11 |
12 | public String getDeviceName() {
13 | return deviceName;
14 | }
15 |
16 | public void setDeviceName(String deviceName) {
17 | this.deviceName = deviceName;
18 | }
19 |
20 | public List getDataValues(){
21 | return dataValues;
22 | }
23 |
24 | public GatewayValue(){
25 | dataValues = new ArrayList<>();
26 | }
27 |
28 | public void addDataValue(DataValue value){
29 | dataValues.add(value);
30 | }
31 | }
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/java/com/hashmap/tempus/processors/GatewayValueSerializer.java:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors;
2 |
3 | import com.fasterxml.jackson.core.JsonGenerator;
4 | import com.fasterxml.jackson.databind.SerializerProvider;
5 | import com.fasterxml.jackson.databind.ser.std.StdSerializer;
6 |
7 | import java.io.IOException;
8 |
9 | public class GatewayValueSerializer extends StdSerializer {
10 |
11 | public GatewayValueSerializer() {
12 | this(null);
13 | }
14 |
15 | public GatewayValueSerializer(Class t){
16 | super(t);
17 | }
18 |
19 | @Override
20 | public void serialize(GatewayValue gatewayValue, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
21 | jsonGenerator.writeStartObject();
22 |
23 | jsonGenerator.writeObjectField(gatewayValue.getDeviceName(), gatewayValue.getDataValues());
24 |
25 | jsonGenerator.writeEndObject();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/java/com/hashmap/tempus/processors/GenerateTimeSeriesFlowFile.java:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors;
2 |
3 | /*
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with
6 | * this work for additional information regarding copyright ownership.
7 | * The ASF licenses this file to You under the Apache License, Version 2.0
8 | * (the "License"); you may not use this file except in compliance with
9 | * the License. You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import be.cetic.tsimulus.config.Configuration;
21 | import com.fasterxml.jackson.annotation.JsonInclude;
22 | import com.fasterxml.jackson.core.JsonProcessingException;
23 | import com.fasterxml.jackson.databind.ObjectMapper;
24 | import com.fasterxml.jackson.databind.module.SimpleModule;
25 | import org.apache.nifi.annotation.behavior.InputRequirement;
26 | import org.apache.nifi.annotation.documentation.CapabilityDescription;
27 | import org.apache.nifi.annotation.documentation.Tags;
28 | import org.apache.nifi.annotation.lifecycle.OnScheduled;
29 | import org.apache.nifi.components.PropertyDescriptor;
30 | import org.apache.nifi.flowfile.FlowFile;
31 | import org.apache.nifi.logging.ComponentLog;
32 | import org.apache.nifi.processor.*;
33 | import org.apache.nifi.processor.exception.ProcessException;
34 | import org.apache.nifi.processor.util.StandardValidators;
35 | import org.joda.time.DateTime;
36 | import org.joda.time.DateTimeZone;
37 | import org.joda.time.LocalDateTime;
38 | import scala.Some;
39 | import scala.Tuple3;
40 | import scala.collection.JavaConverters;
41 |
42 | import javax.xml.crypto.Data;
43 | import java.util.*;
44 |
45 |
46 | @Tags({"Simulator, Timeseries, IOT, Testing"})
47 | @InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
48 | @CapabilityDescription("Generates realistic time series data using the TSimulus time series generator, and places the values into the flowfile in a CSV format.")
49 | public class GenerateTimeSeriesFlowFile extends AbstractProcessor {
50 |
51 | private Configuration simConfig = null;
52 | private boolean isTest = false;
53 | private ObjectMapper mapper = new ObjectMapper();
54 |
55 | public static final PropertyDescriptor SIMULATOR_CONFIG = new PropertyDescriptor
56 | .Builder().name("SIMULATOR_CONFIG")
57 | .displayName("Simulator Configuration File")
58 | .description("The JSON configuration file to use to configure TSimulus")
59 | .required(true)
60 | .addValidator(StandardValidators.FILE_EXISTS_VALIDATOR)
61 | .build();
62 |
63 | public static final PropertyDescriptor JSON_DEVICE_TYPE = new PropertyDescriptor
64 | .Builder().name("JSON_DEVICE_TYPE")
65 | .displayName("Tempus JSON Device Type")
66 | .description("When JSON is selected, whether the processor should output the data in the Gateway message format or the device message format. If Gateway, Device Name is required.")
67 | .required(false)
68 | .allowableValues("Gateway", "Device")
69 | .defaultValue("Device")
70 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
71 | .build();
72 |
73 | public static final PropertyDescriptor PRINT_HEADER = new PropertyDescriptor
74 | .Builder().name("PRINT_HEADER")
75 | .displayName("Print Header")
76 | .description("Directs the processor whether to print a header line or not.")
77 | .required(false)
78 | .allowableValues("true","false")
79 | .defaultValue("false")
80 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
81 | .build();
82 |
83 | public static final PropertyDescriptor DATA_FORMAT = new PropertyDescriptor
84 | .Builder().name("DATA_FORMAT")
85 | .displayName("Data Format")
86 | .description("The format the data should be in, either CSV or JSON")
87 | .required(true)
88 | .allowableValues("JSON","CSV")
89 | .defaultValue("JSON")
90 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
91 | .build();
92 |
93 | public static final PropertyDescriptor LONG_TIMESTAMP = new PropertyDescriptor
94 | .Builder().name("LONG_TIMESTAMP")
95 | .displayName("Use Long Timestamp")
96 | .description("If True it will use number of milliseconds from the epoch, if not it will use an ISO8601 compatable timestamp.")
97 | .required(true)
98 | .allowableValues("true","false")
99 | .defaultValue("false")
100 | .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
101 | .build();
102 |
103 | public static final PropertyDescriptor TIMEZONE = new PropertyDescriptor
104 | .Builder().name("TIMEZONE")
105 | .displayName("Timezone")
106 | .description("The timezone that the data will be generated in")
107 | .required(true)
108 | .defaultValue("America/Chicago")
109 | .allowableValues(DateTimeZone.getAvailableIDs())
110 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
111 | .build();
112 |
113 | public static final PropertyDescriptor DEVICE_NAME = new PropertyDescriptor
114 | .Builder().name("DEVICE_NAME")
115 | .displayName("Device Name")
116 | .description("In Gateway mode, the name of the device that will be used as the identity.")
117 | .required(false)
118 | .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
119 | .build();
120 |
121 | public static final Relationship SUCCESS = new Relationship.Builder()
122 | .name("Success")
123 | .description("When the flowfile is successfully generated")
124 | .build();
125 |
126 | private List descriptors;
127 |
128 | private Set relationships;
129 |
130 | @Override
131 | protected void init(final ProcessorInitializationContext context) {
132 | mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
133 | final List descriptors = new ArrayList<>();
134 | descriptors.add(SIMULATOR_CONFIG);
135 | descriptors.add(PRINT_HEADER);
136 | descriptors.add(LONG_TIMESTAMP);
137 | descriptors.add(TIMEZONE);
138 | descriptors.add(DATA_FORMAT);
139 | descriptors.add(DEVICE_NAME);
140 | descriptors.add(JSON_DEVICE_TYPE);
141 | this.descriptors = Collections.unmodifiableList(descriptors);
142 |
143 | final Set relationships = new HashSet<>();
144 | relationships.add(SUCCESS);
145 | this.relationships = Collections.unmodifiableSet(relationships);
146 | }
147 |
148 | @Override
149 | public Set getRelationships() {
150 | return this.relationships;
151 | }
152 |
153 | @Override
154 | public final List getSupportedPropertyDescriptors() {
155 | return descriptors;
156 | }
157 |
158 | @Override
159 | public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
160 | if (SIMULATOR_CONFIG.equals(descriptor))
161 | simConfig = null;
162 | }
163 |
164 | @OnScheduled
165 | public void onScheduled(final ProcessContext context) {
166 | loadConfiguration(context.getProperty(SIMULATOR_CONFIG).getValue());
167 | }
168 |
169 | @Override
170 | public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
171 | ComponentLog logger = getLogger();
172 | FlowFile flowFile = session.get();
173 |
174 | // Create the flowfile, as it probably does not exist
175 | if (flowFile == null)
176 | flowFile = session.create();
177 |
178 | // Get the data
179 | String data = generateData(context.getProperty(PRINT_HEADER).asBoolean(), context.getProperty(LONG_TIMESTAMP).asBoolean(), context.getProperty(TIMEZONE).toString(), context.getProperty(DATA_FORMAT).getValue(),
180 | context.getProperty(JSON_DEVICE_TYPE).getValue(),context.getProperty(DEVICE_NAME).getValue());
181 |
182 | // Write the results back out to flow file
183 | try{
184 | flowFile = session.write(flowFile, out -> out.write(data.getBytes()));
185 | session.getProvenanceReporter().create(flowFile);
186 | session.transfer(flowFile, SUCCESS);
187 | } catch (ProcessException ex) {
188 | logger.error("Unable to write generated data out to flowfile. Error: ", ex);
189 | }
190 | }
191 |
192 | // Loads the configuration from the file
193 | private void loadConfiguration(String fileName)
194 | {
195 | if (simConfig == null){
196 | // Load the simulator configuration
197 | if (fileName.contains("/configs/unitTestConfig.json"))
198 | isTest = true;
199 | try{
200 | simConfig = SimController.getConfiguration(fileName);
201 | }catch (Exception ex){
202 | getLogger().error("Error loading configuration: " + ex.getMessage());
203 | throw ex;
204 | }
205 |
206 | }
207 | }
208 |
209 | // Actually do the data generation via TSimulus
210 | private String generateData(boolean printHeader, boolean longTimestamp, String Timezone, String dataFormat, String jsonDeviceType, String deviceName)
211 | {
212 | LocalDateTime queryTime = LocalDateTime.now();
213 |
214 | if(isTest)
215 | queryTime = LocalDateTime.parse("2016-01-01T00:00:00.000");
216 |
217 | // Get the time Values for the current time
218 | scala.collection.Iterable> data = SimController.getTimeValue(simConfig.timeSeries(), queryTime);
219 |
220 | // Convert the Scala Iterable to a Java one
221 | Iterable> generatedValues = JavaConverters.asJavaIterableConverter(data).asJava();
222 |
223 | String resultString = "";
224 |
225 | if (dataFormat.equals("CSV")){
226 | resultString = createCsv(printHeader, longTimestamp, Timezone, generatedValues);
227 | }
228 | else if (dataFormat.equals("JSON")){
229 | boolean isGateway = false;
230 |
231 | if (jsonDeviceType.equals("Gateway")) {
232 | isGateway = true;
233 | }
234 |
235 | resultString = generateJson(longTimestamp, Timezone, generatedValues, isGateway, deviceName);
236 | }
237 |
238 | return resultString;
239 | }
240 |
241 | private String generateJson(boolean longTimestamp, String Timezone, Iterable> generatedValues, boolean isGateway, String deviceName){
242 | DataValue value = new DataValue();
243 |
244 | generatedValues.forEach(tv -> {
245 | Object dataValue = ((Some)tv._3()).get();
246 | String ts = tv._2().toString();
247 |
248 | if (longTimestamp){
249 | DateTime localTime = tv._2().toDateTime(DateTimeZone.forID(Timezone));
250 | ts = String.valueOf(localTime.getMillis());
251 | }
252 |
253 | value.setTimeStamp(ts);
254 | value.addValue(tv._1(),dataValue);
255 |
256 | });
257 | String output = "";
258 |
259 | try {
260 |
261 | if (isGateway){
262 | GatewayValue gwValue = new GatewayValue();
263 | gwValue.setDeviceName(deviceName);
264 | gwValue.addDataValue(value);
265 | ObjectMapper gwMapper = new ObjectMapper();
266 | SimpleModule module = new SimpleModule();
267 | module.addSerializer(GatewayValue.class, new GatewayValueSerializer());
268 | gwMapper.registerModule(module);
269 |
270 | return gwMapper.writeValueAsString(gwValue);
271 | }
272 | return mapper.writeValueAsString(value);
273 |
274 | } catch (JsonProcessingException e) {
275 | getLogger().error("Error generating JSON: " + e.getMessage());
276 | }
277 | return output;
278 | }
279 |
280 | private String createCsv(boolean printHeader, boolean longTimestamp, String Timezone, Iterable> generatedValues){
281 | StringBuilder dataValueString = new StringBuilder();
282 |
283 | if (printHeader)
284 | dataValueString.append("name, ts, value").append(System.lineSeparator());
285 |
286 | generatedValues.forEach(tv -> {
287 | String dataValue = ((Some)tv._3()).get().toString();
288 | String ts = tv._2().toString();
289 | if (longTimestamp){
290 | DateTime localTime = tv._2().toDateTime(DateTimeZone.forID(Timezone));
291 | ts = String.valueOf(localTime.getMillis());
292 | }
293 | dataValueString.append(tv._1()).append(",").append(ts).append(",").append(dataValue);
294 | dataValueString.append(System.lineSeparator());
295 | });
296 |
297 | return dataValueString.toString().trim();
298 | }
299 | }
300 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor:
--------------------------------------------------------------------------------
1 | # Licensed to the Apache Software Foundation (ASF) under one or more
2 | # contributor license agreements. See the NOTICE file distributed with
3 | # this work for additional information regarding copyright ownership.
4 | # The ASF licenses this file to You under the Apache License, Version 2.0
5 | # (the "License"); you may not use this file except in compliance with
6 | # the License. You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | com.hashmap.tempus.processors.GenerateTimeSeriesFlowFile
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/main/scala/com/hashmap/tempus/processors/SimController.scala:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors
2 |
3 | import java.io.File
4 | import be.cetic.tsimulus.config.Configuration
5 | import be.cetic.tsimulus.timeseries._
6 | import com.github.nscala_time.time.Imports._
7 | import spray.json._
8 | import scala.io.Source
9 |
10 | object SimController
11 | {
12 | /**
13 | * Returns a point in time value for all exported values in the configuration file
14 | * @param ts The value in time to generate data for
15 | * @return a scala Iterable of Tuples in the form of URI, Timestamp, value
16 | */
17 | def getTimeValue(ts: Map[String, (TimeSeries[Any], _root_.com.github.nscala_time.time.Imports.Duration)], genTime: LocalDateTime) : Iterable[(String,LocalDateTime,AnyRef)] =
18 | {
19 | ts.map(series =>
20 | {
21 | val values = series._2._1
22 | val time = genTime
23 | val data = values.compute(time)
24 | new Tuple3[String,LocalDateTime,AnyRef](series._1, time, data)
25 | })
26 |
27 | }
28 |
29 | /**
30 | * Wrapped scala method to be able to be accessed from Java
31 | * @param filePath The path to the configuration file
32 | * @return The configuration object parsed from the file
33 | */
34 | def getConfiguration(filePath: String): Configuration = {
35 | val content = Source .fromFile(new File(filePath))
36 | .getLines()
37 | .mkString("\n")
38 |
39 | Configuration(content.parseJson);
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/test/java/com/hashmap/tempus/processors/GenerateTimeSeriesFlowfileTest.java:
--------------------------------------------------------------------------------
1 | package com.hashmap.tempus.processors;
2 |
3 | /*
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with
6 | * this work for additional information regarding copyright ownership.
7 | * The ASF licenses this file to You under the Apache License, Version 2.0
8 | * (the "License"); you may not use this file except in compliance with
9 | * the License. You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.apache.nifi.util.MockFlowFile;
21 | import org.apache.nifi.util.TestRunner;
22 | import org.apache.nifi.util.TestRunners;
23 | import org.junit.Before;
24 | import org.junit.Test;
25 |
26 |
27 | public class GenerateTimeSeriesFlowfileTest {
28 |
29 | @Test
30 | public void testGenerateTimeSeries() {
31 | TestRunner runner = TestRunners.newTestRunner(new GenerateTimeSeriesFlowFile());
32 | runner.setProperty(GenerateTimeSeriesFlowFile.SIMULATOR_CONFIG, getClass().getResource("/configs/basicConfig.json").getPath());
33 | runner.assertValid();
34 |
35 | runner.run();
36 |
37 | runner.assertTransferCount(GenerateTimeSeriesFlowFile.SUCCESS, 1);
38 | }
39 |
40 | @Test
41 | public void testInvalidConfig() {
42 | TestRunner runner = TestRunners.newTestRunner(new GenerateTimeSeriesFlowFile());
43 | runner.setProperty(GenerateTimeSeriesFlowFile.SIMULATOR_CONFIG, "/my/invalid/path");
44 | runner.assertNotValid();
45 | }
46 |
47 | @Test
48 | public void testFalseHeaderCreation() {
49 | TestRunner runner = TestRunners.newTestRunner(new GenerateTimeSeriesFlowFile());
50 | runner.setProperty(GenerateTimeSeriesFlowFile.PRINT_HEADER, "false");
51 | runner.setProperty(GenerateTimeSeriesFlowFile.SIMULATOR_CONFIG, getClass().getResource("/configs/unitTestConfig.json").getPath());
52 | runner.setProperty(GenerateTimeSeriesFlowFile.DATA_FORMAT, "CSV");
53 | runner.run();
54 | runner.assertTransferCount(GenerateTimeSeriesFlowFile.SUCCESS, 1);
55 | runner.getFlowFilesForRelationship(GenerateTimeSeriesFlowFile.SUCCESS).get(0).assertContentEquals("test,2016-01-01T00:00:00.000,17.5");
56 | }
57 |
58 | @Test
59 | public void testGatewayMessageType() {
60 | TestRunner runner = TestRunners.newTestRunner(new GenerateTimeSeriesFlowFile());
61 | runner.setProperty(GenerateTimeSeriesFlowFile.PRINT_HEADER, "false");
62 | runner.setProperty(GenerateTimeSeriesFlowFile.LONG_TIMESTAMP, "true");
63 | runner.setProperty(GenerateTimeSeriesFlowFile.SIMULATOR_CONFIG, getClass().getResource("/configs/unitTestConfig.json").getPath());
64 | runner.setProperty(GenerateTimeSeriesFlowFile.DATA_FORMAT, "JSON");
65 | runner.setProperty(GenerateTimeSeriesFlowFile.DEVICE_NAME, "test");
66 | runner.setProperty(GenerateTimeSeriesFlowFile.JSON_DEVICE_TYPE, "Gateway");
67 | runner.run();
68 | runner.assertTransferCount(GenerateTimeSeriesFlowFile.SUCCESS, 1);
69 | runner.getFlowFilesForRelationship(GenerateTimeSeriesFlowFile.SUCCESS).get(0).assertContentEquals("{\"test\":[{\"values\":{\"test\":17.5},\"ts\":\"1451628000000\"}]}");
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/test/resources/configs/basicConfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "generators":[
3 | {
4 | "name": "monthly-basis",
5 | "type": "monthly",
6 | "points": {"january": 3.3, "february": 3.7, "march": 6.8, "april": 9.8, "may": 13.6, "june": 16.2,
7 | "july": 18.4, "august": 18, "september": 14.9, "october": 11.1, "november": 6.8, "december": 3.9}
8 | },
9 | {
10 | "name": "daily-basis",
11 | "type": "monthly",
12 | "points": {"january": 3.3, "february": 3.7, "march": 6.8, "april": 9.8, "may": 13.6, "june": 16.2,
13 | "july": 18.4, "august": 18, "september": 14.9, "october": 11.1, "november": 6.8, "december": 3.9}
14 | },
15 | {
16 | "name": "generator1",
17 | "type": "gaussian",
18 | "seed": 42,
19 | "std": 0.5
20 | },
21 | {
22 | "name": "generator2",
23 | "type": "gaussian",
24 | "seed": 11,
25 | "std": 0.9
26 | }
27 | ],
28 | "exported":[
29 | {"name": "temperature", "generator": "generator1", "frequency": 6000},
30 | {"name": "pressure", "generator": "monthly-basis", "frequency": 3000},
31 | {"name": "torque", "generator": "generator2", "frequency": 6000},
32 | {"name": "rpm", "generator": "daily-basis", "frequency": 3000},
33 | {"name": "density", "generator": "generator1", "frequency": 6000},
34 | {"name": "porosity", "generator": "daily-basis", "frequency": 3000},
35 | {"name": "resistivity", "generator": "generator2", "frequency": 6000},
36 | {"name": "crpm", "generator": "monthly-basis", "frequency": 3000},
37 | {"name": "aprs", "generator": "daily-basis", "frequency": 6000},
38 | {"name": "stor", "generator": "monthly-basis", "frequency": 3000},
39 | {"name": "rpm", "generator": "generator1", "frequency": 6000},
40 | {"name": "gamma", "generator": "generator2", "frequency": 1000},
41 | {"name": "Attn", "generator": "generator1", "frequency": 2000}
42 | ],
43 | "from": "2016-01-01 00:00:00.000",
44 | "to": "2017-12-31 23:59:59.999"
45 | }
--------------------------------------------------------------------------------
/nifi-simulator-bundle-processors/src/test/resources/configs/unitTestConfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "generators":[
3 | {
4 | "name": "cst",
5 | "type": "constant",
6 | "value": 17.5
7 | }
8 | ],
9 | "exported":[
10 | {"name": "test", "generator": "cst", "frequency": 6000}
11 | ],
12 | "from": "2016-01-01 00:00:00.000",
13 | "to": "2017-12-31 23:59:59.999"
14 | }
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 | 4.0.0
18 |
19 |
20 | org.apache.nifi
21 | nifi-nar-bundles
22 | 1.4.0
23 |
24 |
25 | com.hashmap
26 | simulator-bundle
27 | 1.4.0
28 | pom
29 |
30 |
31 | 2.11.8
32 | 2.11
33 |
34 |
35 |
36 |
37 | Apache License, Version 2.0
38 | https://www.apache.org/licenses/LICENSE-2.0.txt
39 |
40 |
41 |
42 |
43 | nifi-simulator-bundle-processors
44 | nifi-simulator-bundle-nar
45 |
46 |
47 |
48 |
49 | org.scala-tools
50 | maven-scala-plugin
51 | 2.15.2
52 |
53 |
54 |
55 | compile
56 |
57 | compile
58 |
59 | compile
60 |
61 |
62 | test-compile
63 |
64 | testCompile
65 |
66 | test-compile
67 |
68 |
69 | process-resources
70 |
71 | compile
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | be.cetic
81 | tsimulus_2.11
82 | 0.1.14
83 |
84 |
85 | org.scala-lang
86 | scala-library
87 | ${scala.version}
88 |
89 |
90 | io.spray
91 | spray-json_2.11
92 | 1.3.2
93 |
94 |
95 | com.github.nscala-time
96 | nscala-time_2.11
97 | 2.14.0
98 |
99 |
100 |
101 |
--------------------------------------------------------------------------------