From faabf5cfc00c4478ad546de5357b76382d48ae63 Mon Sep 17 00:00:00 2001 From: Shan Mahanama Date: Sat, 16 Nov 2019 15:16:14 +0800 Subject: [PATCH 1/3] Reorder imports --- distributor/src/distributor/website.bal | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/distributor/src/distributor/website.bal b/distributor/src/distributor/website.bal index cbb667c..4c2bec6 100644 --- a/distributor/src/distributor/website.bal +++ b/distributor/src/distributor/website.bal @@ -1,11 +1,11 @@ import ballerina/auth; +import ballerina/file; import ballerina/http; import ballerina/log; import ballerina/mime; import ballerina/time; -import ballerina/xmlutils; -import ballerina/file; import ballerina/websub; +import ballerina/xmlutils; const LEVEL_PD = "POLLING-DIVISION"; const LEVEL_ED = "ELECTORAL-DISTRICT"; From 2dce7ab3be5398e9644300a624446b1c2e105cff Mon Sep 17 00:00:00 2001 From: shan1024 Date: Sat, 16 Nov 2019 16:26:49 +0800 Subject: [PATCH 2/3] Fix formatting issues --- distributor/src/distributor/filters.bal | 6 ++++-- distributor/src/distributor/genhtml.bal | 10 +++++----- distributor/src/distributor/listeners.bal | 6 +++--- distributor/src/distributor/main.bal | 3 ++- distributor/src/distributor/messenger.bal | 1 + distributor/src/distributor/results.bal | 6 +++--- distributor/src/distributor/save.bal | 13 +++++++------ distributor/src/distributor/website.bal | 12 ++++++------ 8 files changed, 31 insertions(+), 26 deletions(-) diff --git a/distributor/src/distributor/filters.bal b/distributor/src/distributor/filters.bal index 49b1c25..fc7e469 100644 --- a/distributor/src/distributor/filters.bal +++ b/distributor/src/distributor/filters.bal @@ -14,6 +14,7 @@ map awaitResultsCallbackMap = {}; # Filter to challenge authentication. public type AuthChallengeFilter object { + *http:RequestFilter; public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context) @@ -25,7 +26,7 @@ public type AuthChallengeFilter object { http:Response res = new; res.statusCode = 401; res.addHeader(WWW_AUTHENTICATE_HEADER, "Basic realm=\"EC Media Results Delivery\""); - error? err = caller->respond(res); + error? err = caller->respond(res); if (err is error) { log:printError("error responding with auth challenge", err); } @@ -35,6 +36,7 @@ public type AuthChallengeFilter object { # Filter to remove an existing subscription for a user, when a new subscription request is sent. public type SubscriptionFilter object { + *http:RequestFilter; public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns boolean { @@ -95,7 +97,7 @@ public type SubscriptionFilter object { string headerValue = request.getHeader(http:AUTH_HEADER); - if !(headerValue.startsWith(auth:AUTH_SCHEME_BASIC)) { + if (!headerValue.startsWith(auth:AUTH_SCHEME_BASIC)) { return false; } diff --git a/distributor/src/distributor/genhtml.bal b/distributor/src/distributor/genhtml.bal index 3dbc512..a57a3d0 100644 --- a/distributor/src/distributor/genhtml.bal +++ b/distributor/src/distributor/genhtml.bal @@ -1,6 +1,6 @@ -import ballerina/time; -import ballerina/math; import ballerina/lang.'string; +import ballerina/math; +import ballerina/time; map electionCode2Name = { "2019PRE": "PRESIDENTIAL ELECTION - NOVEMBER 16, 2019", @@ -22,7 +22,7 @@ map electionCode2Name = { "2015-PRE-REPLAY-015": "PRESIDENTIAL ELECTION - 08/01/2015 RESULT REPLAY" }; -function generateHtml (string electionCode, map result, boolean sorted) returns string|error { +function generateHtml(string electionCode, map result, boolean sorted) returns string|error { boolean firstRound = (result.'type == PRESIDENTIAL_RESULT); string electionName = electionCode2Name[electionCode] ?: ("Presidential Election - " + electionCode); electionName += firstRound ? " (FIRST PREFERENCES)" : " (REVISED WITH 2nd/3rd PREFERENCES)"; @@ -88,7 +88,7 @@ function generateHtml (string electionCode, map result, boolean sorted) re return "" + head + body + ""; } -function sortPartyResults (json[] unsorted) returns json[] { +function sortPartyResults(json[] unsorted) returns json[] { return unsorted.sort(function (json r1, json r2) returns int { int n1 = r1.votes; int n2 = r2.votes; @@ -96,7 +96,7 @@ function sortPartyResults (json[] unsorted) returns json[] { }); } -function commaFormatInt (int n) returns string { +function commaFormatInt(int n) returns string { string minus = n < 0 ? "-" : ""; int num = math:absInt(n); string numStr = num.toString(); diff --git a/distributor/src/distributor/listeners.bal b/distributor/src/distributor/listeners.bal index 509dc67..09a3cf2 100644 --- a/distributor/src/distributor/listeners.bal +++ b/distributor/src/distributor/listeners.bal @@ -3,16 +3,16 @@ import ballerina/config; import ballerina/http; # Listener for results tabulation to deliver results to us. -listener http:Listener resultsListener = new (config:getAsInt("eclk.pub.port", 8181), { +listener http:Listener resultsListener = new(config:getAsInt("eclk.pub.port", 8181), { http1Settings: { maxEntityBodySize: 4194304 } }); -http:BasicAuthHandler inboundBasicAuthHandler = new (new auth:InboundBasicAuthProvider()); +http:BasicAuthHandler inboundBasicAuthHandler = new(new auth:InboundBasicAuthProvider()); # Listener for media orgs to subscribe, for the website and for them to pull specific results. -listener http:Listener mediaListener = new (config:getAsInt("eclk.hub.port", 9090), config = { +listener http:Listener mediaListener = new(config:getAsInt("eclk.hub.port", 9090), config = { auth: { authHandlers: [inboundBasicAuthHandler], position: 1, diff --git a/distributor/src/distributor/main.bal b/distributor/src/distributor/main.bal index 4877b27..361bff6 100644 --- a/distributor/src/distributor/main.bal +++ b/distributor/src/distributor/main.bal @@ -1,5 +1,6 @@ import ballerina/config; import ballerina/websub; + import ballerinax/java.jdbc; import maryamzi/websub.hub.mysqlstore; @@ -24,7 +25,7 @@ public function main() returns error? { } // create the datastore for the websub hub - mysqlstore:MySqlHubPersistenceStore persistenceStore = check new (db, key); + mysqlstore:MySqlHubPersistenceStore persistenceStore = check new(db, key); // start the hub var hubStartUpResult = diff --git a/distributor/src/distributor/messenger.bal b/distributor/src/distributor/messenger.bal index b0e43e1..6303a67 100644 --- a/distributor/src/distributor/messenger.bal +++ b/distributor/src/distributor/messenger.bal @@ -1,6 +1,7 @@ import ballerina/config; import ballerina/log; import ballerina/stringutils; + import wso2/twilio; twilio:TwilioConfiguration twilioConfig = { diff --git a/distributor/src/distributor/results.bal b/distributor/src/distributor/results.bal index f93edf5..223d294 100644 --- a/distributor/src/distributor/results.bal +++ b/distributor/src/distributor/results.bal @@ -1,10 +1,10 @@ import ballerina/http; import ballerina/io; +import ballerina/lang.'int; import ballerina/log; import ballerina/mime; import ballerina/time; import ballerina/websub; -import ballerina/lang.'int; # Service for results tabulation to publish results to. We assume that results tabulation will deliver # a result in two separate messages - one with the json result data and another with an image of the @@ -177,8 +177,8 @@ function publishResultData(Result result, string? electionCode = (), string? res // push it out with the election code and the json result as the message json resultAll = { - election_code : result.election, - result : result.jsonResult + election_code: result.election, + result: result.jsonResult }; var r = wh.publishUpdate(JSON_TOPIC, resultAll, mime:APPLICATION_JSON); if r is error { diff --git a/distributor/src/distributor/save.bal b/distributor/src/distributor/save.bal index bb0c263..5d50af5 100644 --- a/distributor/src/distributor/save.bal +++ b/distributor/src/distributor/save.bal @@ -1,6 +1,7 @@ import ballerina/config; import ballerina/io; import ballerina/log; + import ballerinax/java.jdbc; # This variable will contain all the results received. If the server crashes it will @@ -114,7 +115,7 @@ function __init() { // read json string and convert to json io:StringReader sr = new(dr.jsonResult, encoding = "UTF-8"); - map jm = > sr.readJson(); + map jm = > sr.readJson(); // put results in the cache resultsCache.push( { @@ -172,8 +173,8 @@ function __init() { var account = twilioClient->getAccountDetails(); if account is error { log:printError("SMS notification is disabled due to invalid twilio account details. " + - "Please provide valid 'eclk.sms.twilio.accountSid'/'authToken'/'source'(twilio mobile no):" + - account.detail()?.message); + "Please provide valid 'eclk.sms.twilio.accountSid'/'authToken'/'source'(twilio mobile no):" + + account.detail()?.message); } else { validTwilioAccount = true; log:printInfo("SMS notification is enabled : twilio.account.status=" + account.status.toString()); @@ -201,11 +202,11 @@ function saveResult(Result result) returns error? { // add up cumulative result from all the PD results to get current cumulative total if result.jsonResult.level == "POLLING-DIVISION" { - addToCumulative (result.jsonResult); + addToCumulative(result.jsonResult); } // update in memory cache of all results - resultsCache.push (result); + resultsCache.push(result); } # Save an image associated with a result @@ -265,7 +266,7 @@ function resetResults() returns error? { } # Add a polling division level result to the cumulative total. -function addToCumulative (map jm) { +function addToCumulative(map jm) { boolean firstRound = jm.'type == PRESIDENTIAL_RESULT; json[] pr = checkpanic jm.by_party; diff --git a/distributor/src/distributor/website.bal b/distributor/src/distributor/website.bal index 4c2bec6..c910241 100644 --- a/distributor/src/distributor/website.bal +++ b/distributor/src/distributor/website.bal @@ -22,7 +22,7 @@ service mediaWebsite on mediaListener { path: "/", methods: ["GET"] } - resource function showAll (http:Caller caller, http:Request req) returns error? { + resource function showAll(http:Caller caller, http:Request req) returns error? { string head = ""; head += "Sri Lanka Elections Commission"; head += ""; @@ -49,7 +49,7 @@ service mediaWebsite on mediaListener { return caller->ok(hr); } - resource function allresults (http:Caller caller, http:Request req) returns error? { + resource function allresults(http:Caller caller, http:Request req) returns error? { json[] results = []; // return results in reverse order @@ -67,7 +67,7 @@ service mediaWebsite on mediaListener { path: "/result/{election}/{seqNo}", methods: ["GET"] } - resource function data (http:Caller caller, http:Request req, string election, int seqNo) returns error? { + resource function data(http:Caller caller, http:Request req, string election, int seqNo) returns error? { // what's the format they want? we'll default to json if they don't say or get messy string format = req.getQueryParamValue ("format") ?: "json"; if format != "xml" && format != "json" && format != "html" { @@ -106,7 +106,7 @@ service mediaWebsite on mediaListener { path: "/release/{election}/{seqNo}", methods: ["GET"] } - resource function releaseDoc (http:Caller caller, http:Request req, string election, int seqNo) returns error? { + resource function releaseDoc(http:Caller caller, http:Request req, string election, int seqNo) returns error? { http:Response hr = new; // find image of the release doc and return it (if its there - may not have appeared yet) @@ -168,7 +168,7 @@ service mediaWebsite on mediaListener { scopes: ["ECAdmin"] } } - resource function smsRegistration (http:Caller caller, http:Request req, Recipient smsRecipient) returns error? { + resource function smsRegistration(http:Caller caller, http:Request req, Recipient smsRecipient) returns error? { string|error validatedNo = validate(smsRecipient.mobile); if validatedNo is error { http:Response res = new; @@ -217,7 +217,7 @@ service mediaWebsite on mediaListener { } } -# Print the results +# Print the results. # # + return - HTML string for results of the given type from the results cache function generateResultsTable(string 'type) returns string { From 43328e02481c014a8f81009c707f5f5f5018b874 Mon Sep 17 00:00:00 2001 From: shan1024 Date: Sat, 16 Nov 2019 16:31:18 +0800 Subject: [PATCH 3/3] Fix formatting issues --- subscriber/src/subscriber/genhtml.bal | 12 ++++---- subscriber/src/subscriber/save.bal | 2 +- subscriber/src/subscriber/subscriber.bal | 39 ++++++++++++------------ 3 files changed, 26 insertions(+), 27 deletions(-) diff --git a/subscriber/src/subscriber/genhtml.bal b/subscriber/src/subscriber/genhtml.bal index 4b44b36..5f98583 100644 --- a/subscriber/src/subscriber/genhtml.bal +++ b/subscriber/src/subscriber/genhtml.bal @@ -1,6 +1,6 @@ -import ballerina/time; -import ballerina/math; import ballerina/lang.'string; +import ballerina/math; +import ballerina/time; map electionCode2Name = { "2019PRE": "PRESIDENTIAL ELECTION - 16/11/2019", @@ -22,7 +22,7 @@ map electionCode2Name = { "2015-PRE-REPLAY-015": "PRESIDENTIAL ELECTION - 08/01/2015 RESULT REPLAY" }; -function generateHtml (string electionCode, map result, boolean sorted) returns string|error { +function generateHtml(string electionCode, map result, boolean sorted) returns string|error { string electionName = electionCode2Name[electionCode] ?: "Presidential Election - TEST"; string timeNow = check time:format(time:currentTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ"); string head = ""; @@ -71,7 +71,7 @@ function generateHtml (string electionCode, map result, boolean sorted) re return "" + head + body + ""; } -function sortPartyResults (json[] unsorted) returns json[] { +function sortPartyResults(json[] unsorted) returns json[] { return unsorted.sort(function (json r1, json r2) returns int { int n1 = r1.votes; int n2 = r2.votes; @@ -79,7 +79,7 @@ function sortPartyResults (json[] unsorted) returns json[] { }); } -function commaFormatInt (int n) returns string { +function commaFormatInt(int n) returns string { string minus = n < 0 ? "-" : ""; int num = math:absInt(n); string numStr = num.toString(); @@ -92,6 +92,6 @@ function commaFormatInt (int n) returns string { if numStr.length() > 0 { parts.unshift(numStr); } - string res = 'string:'join(",", ... parts); + string res = 'string:'join(",", ...parts); return minus + res; } diff --git a/subscriber/src/subscriber/save.bal b/subscriber/src/subscriber/save.bal index 43ed571..e7b2ba2 100644 --- a/subscriber/src/subscriber/save.bal +++ b/subscriber/src/subscriber/save.bal @@ -1,8 +1,8 @@ import ballerina/http; import ballerina/io; import ballerina/log; -import ballerina/xmlutils; import ballerina/stringutils as su; +import ballerina/xmlutils; const PRESIDENTIAL_RESULT = "PRESIDENTIAL-FIRST"; const LEVEL_PD = "POLLING-DIVISION"; diff --git a/subscriber/src/subscriber/subscriber.bal b/subscriber/src/subscriber/subscriber.bal index 5ba83d2..b5abb18 100644 --- a/subscriber/src/subscriber/subscriber.bal +++ b/subscriber/src/subscriber/subscriber.bal @@ -45,19 +45,19 @@ http:OutboundAuthConfig? auth = (); http:Client? imageClient = (); // what formats does the user want results saved in? -public function main (string secret, // secret to send to the hub - string? username = (), // my username - string? password = (), // my password - boolean await = false, // do I want the await results notification? - boolean 'json = false, // do I want json? - boolean 'xml = false, // do I want xml? - boolean image = false, // do I want the image? - boolean html = false, // do I want HTML? - boolean sorted = true, // do I want HTML results sorted highest to lowest - boolean wantCode = false, // do I want electionCode in the filename - string homeURL = "https://resultstest.ecdev.opensource.lk", // where do I subscribe at - int port = 1111, // port I'm going to open - string myURL = "" // how to reach me over the internet +public function main(string secret, // secret to send to the hub + string? username = (), // my username + string? password = (), // my password + boolean await = false, // do I want the await results notification? + boolean 'json = false, // do I want json? + boolean 'xml = false, // do I want xml? + boolean image = false, // do I want the image? + boolean html = false, // do I want HTML? + boolean sorted = true, // do I want HTML results sorted highest to lowest + boolean wantCode = false, // do I want electionCode in the filename + string homeURL = "https://resultstest.ecdev.opensource.lk", // where do I subscribe at + int port = 1111, // port I'm going to open + string myURL = "" // how to reach me over the internet ) returns error? { subscriberSecret = <@untainted> secret; subscriberPublicUrl = <@untainted> (myURL == "" ? string `http://localhost:${port}` : myURL); @@ -65,18 +65,18 @@ public function main (string secret, // secret to send to the hub hub = <@untainted> homeURL + "/websub/hub"; // check what format the user wants results in - wantJson = <@untainted>'json; - wantXml = <@untainted>'xml; - wantHtml = <@untainted>html; + wantJson = <@untainted> 'json; + wantXml = <@untainted> 'xml; + wantHtml = <@untainted> html; if !(wantJson || wantXml || wantHtml) { // default to giving json wantJson = true; } - sortedHtml = <@untainted>sorted; + sortedHtml = <@untainted> sorted; // set up auth if (username is string && password is string) { - auth:OutboundBasicAuthProvider outboundBasicAuthProvider = new ({ + auth:OutboundBasicAuthProvider outboundBasicAuthProvider = new({ username: <@untainted> username, password: <@untainted> password }); @@ -154,7 +154,6 @@ public function main (string secret, // secret to send to the hub error? pingStatus = ping:ping(); if !(pingStatus is ()) { log:printError("Error pinging on await notification", pingStatus); - } } else { log:printError("Expected text payload, received:" + textPayload.toString()); @@ -165,7 +164,7 @@ public function main (string secret, // secret to send to the hub } if image { - imageClient = <@untainted> new (homeURL, {auth: auth}); + imageClient = <@untainted> new(homeURL, {auth: auth}); // attach the image subscriber service imageSubscriberService = @websub:SubscriberServiceConfig {