-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSNStoSPARQLLogger.js
327 lines (270 loc) · 9.44 KB
/
SNStoSPARQLLogger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
var Buffer = require('buffer').Buffer;
var https = require('https');
var util = require('util');
var moment = require('moment');
var path = require('path');
var http = require('http');
var N3 = require('n3');
var needle = require('needle');
var JSONConfigurationController = require("./JSONConfigurationController.js");
var configuration;
var server;
var dateformat = "YYYY/MM/DD HH:mm:ss";
var configFileIncPath = path.join(__dirname + '/configuration.json');
var refreshNATIntervalID = undefined;
var amQuitting = false;
function main() {
configuration = new JSONConfigurationController();
configuration.setConfiguration(configFileIncPath);
configuration.on("configComplete", postConfiguration);
configuration.on("reset", resetConfiguration);
}
function resetConfiguration(callback) {
unSubscribeAllSNSTopics(function () {
if (typeof(server) !== 'undefined') {
console.log("** (" + getCurrentTime() + ") HTTP Server on port " + configuration.data.PrivatePort + " was shut down");
server.close();
}
console.log("** (" + getCurrentTime() + ") Resetting all configuration variables...");
if (typeof(refreshNATIntervalID) !== 'undefined') {
clearInterval(refreshNATIntervalID);
console.log("** (" + getCurrentTime() + ") Resetting NAT/uPNP Settings...");
}
refreshNATIntervalID = undefined;
if (callback != null) {
console.log("** (" + getCurrentTime() + ") Completed resetting...");
callback();
}
});
}
process.on( 'SIGINT', function() {
if (amQuitting)
{
console.log("** (" + getCurrentTime() + ") Already in the process of shutting down, please wait...");
}
else
{
amQuitting = true;
console.log("** (" + getCurrentTime() + ") Shutting down... please wait");
resetConfiguration(function() {
// some other closing procedures go here
console.log("** (" + getCurrentTime() + ") All set! Quitting.");
process.exit();
});
}
})
function postConfiguration() {
if (configuration.data.UseNATPNP) {
startPortForwarding();
refreshNATIntervalID = setInterval(function() {
startPortForwarding();
}, configuration.data.NatTTL * 60 * 1000);
}
if (configuration.data.snsEndpointURL.length > 0) setEndpointURL();
createHTTPServer(configuration.data.PrivatePort);
subscribeAllSNSTopics();
}
function setEndpointURL() {
}
function unSubscribeAllSNSTopics(callback) {
var completed = 0;
for (var i in configuration.data.SNSTopics)
{
console.log("** (" + getCurrentTime() + ") Unsubscribing to SNS Topic: " + configuration.data.SNSTopics[i].TopicARN);
configuration.amazonSNSPublisher.unSubscribeSNSTopic(
configuration.data.SNSTopics[i].SubscriptionArn,
function (subscriptionArn) {
completed++;
console.log("** (" + getCurrentTime() + ") Waiting for final unsubscription (completed " + completed + " of " + configuration.data.SNSTopics.length + ")");
if (completed == configuration.data.SNSTopics.length)
{
console.log("** (" + getCurrentTime() + ") Completed the final unsubscription...");
callback();
}
});
}
}
function subscribeAllSNSTopics() {
for (var i in configuration.data.SNSTopics)
{
console.log("** (" + getCurrentTime() + ") Subscribing to SNS Topic: " + configuration.data.SNSTopics[i].TopicARN);
configuration.amazonSNSPublisher.subscribeSNSTopic(
configuration.data.SNSTopics[i].TopicARN,
configuration.data.snsEndpointURL
);
}
}
function createHTTPServer(port) {
server = http.createServer(parsePOST).listen(port);
console.log("** (" + getCurrentTime() + ") HTTP Server has started on Port " + port);
}
function parsePOST(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var postData = JSON.parse(body);
if (postData.Type == "SubscriptionConfirmation")
{
var topicArn = postData.TopicArn;
console.log("** (" + getCurrentTime() + ") Obtained a SNS Subscription Confirmation Token for topic " + topicArn);
configuration.amazonSNSPublisher.confirmSubscription(
topicArn,
postData.Token,
function (subscriptionArn) {
getSNSTopicByArn(topicArn).SubscriptionArn = subscriptionArn;
});
}
else if (postData.Type == "Notification")
{
var triples;
var n3 = N3.Writer();
var topicArn = postData.TopicArn;
var snsTopicOptions = getSNSTopicByArn(topicArn);
var message = JSON.parse(postData.Message);
var subjectURIPrefix = snsTopicOptions.SubjectURIPrefix;
var subjectType = snsTopicOptions.SubjectType;
var filterField = snsTopicOptions.FilterField;
var filterValue = snsTopicOptions.FilterValue;
var objectTypes = snsTopicOptions.ObjectTypes;
var passFilterTest = false;
var filter = false;
var convertTypes = false;
if (typeof(filterField) !== 'undefined') {
if (typeof(message[filterField]) !== 'undefined') {
filter = true;
}
}
if (typeof(objectTypes) !== 'undefined') {
if (objectTypes.length > 0) {
convertTypes = true;
}
}
// check to see if contains a trailing slash, add one if not.
if (subjectURIPrefix[subjectURIPrefix.length-1] != "/") {
subjectURIPrefix += "/";
}
var subject = subjectURIPrefix + postData.MessageId;
var object;
var predicate;
console.log("** (" + getCurrentTime() + ") Got a SNS Notification POST, Message Recieved: ");
console.log(message);
n3.addTriple(subject, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', subjectType);
for(var messageAttr in message)
{
predicate = subjectURIPrefix + "#" + messageAttr;
if (filter) {
// console.log("** (" + getCurrentTime() + ") Checking for the filter field.");
if (messageAttr.toString().toUpperCase() == filterField.toString().toUpperCase()) {
if (filterValue.toString().toUpperCase() == message[messageAttr].toString().toUpperCase()) {
passFilterTest = true;
}
}
}
if (convertTypes) {
for (var counter = 0; counter < objectTypes.length; counter++) {
if (messageAttr.toString().toUpperCase() == objectTypes[counter].property.toString().toUpperCase()) {
if (objectTypes[counter].convert == "JSONtoRDFDateTime") {
var d = moment(message[messageAttr]);
object = "\"" + d.format("YYYY-MM-DDTHH:mm:ss") + "^^" + objectTypes[counter].type + "\"";
}
else {
object = "\"" + message[messageAttr] + "^^" + objectTypes[counter].type + "\"";
}
}
}
}
if (typeof(object) === 'undefined') {
object = "\"" + message[messageAttr] + "\"";
}
if (configuration.data.debug) {
console.log("**********************************")
console.log("About to add the triple: ");
console.log("Subject: " + subject);
console.log("Predicate: " + predicate);
console.log("Object: " + object);
console.log("**********************************")
}
n3.addTriple(subject, predicate, object);
object = undefined;
}
if (configuration.data.debug) {
console.log("** (" + getCurrentTime() + ") filter: " + filter.toString() + " passFilterTest: " + passFilterTest.toString());
}
if (!filter || passFilterTest)
{
n3.end(function (error, result) {
var sparql = "INSERT DATA {" + result + "}";
if (!configuration.data.FakePublish) {
console.log("** (" + getCurrentTime() + ") SPARQL Statement about to be executed: " + sparql);
logToRDF(sparql);
}
else {
console.log("** (" + getCurrentTime() + ") Not going to execute sparql statement because fakePublish flag is set: " + sparql);
}
});
}
else if (configuration.data.debug) {
console.log("** (" + getCurrentTime() + ") Will not record becase a filter criteria has not been met.");
}
}
else
{
console.log("** (" + getCurrentTime() + ") Got a POST, but do not know what to do with it! body:");
console.log(body);
console.log("** (" + getCurrentTime() + ") ... and Headers for the POST " + request.headers);
}
});
}
else if (configuration.data.debug)
{
console.log("** (" + getCurrentTime() + ") Got a GET, but do not know why...");
console.log(request.param);
}
response.writeHead(200);
response.end();
}
function logToRDF(sparql) {
needle.post(configuration.data.SPARQL_Update_Endpoint, { update: sparql },
function(err, resp, body){
if (body.indexOf("Update succeeded") > 0)
{
console.log("** (" + getCurrentTime() + ") The SPARQL Update was sucessful");
}
else
{
console.log("** (" + getCurrentTime() + ") ERROR: The SPARQL Update was NOT sucessful:");
console.log(body);
}
});
}
function startPortForwarding() {
var natUpnp = require('nat-upnp');
console.log("** (" + getCurrentTime() + ") Using uPNP to port forward on : " + configuration.data.PublicPort + "/" + configuration.data.PrivatePort);
var client = natUpnp.createClient();
client.portMapping({
public: configuration.data.PublicPort,
private: configuration.data.PrivatePort,
ttl: configuration.data.NatTTL
}, function(err) {
if (err != null)
{
console.log("** (" + getCurrentTime() + ") ERROR: uPNP was NOT sucessful");
}
});
}
function getCurrentTime() {
return (moment().format(dateformat));
}
function getSNSTopicByArn(topicArn) {
for (var i in configuration.data.SNSTopics)
{
if (configuration.data.SNSTopics[i].TopicARN == topicArn)
{
return configuration.data.SNSTopics[i];
}
}
}
main();