Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve formatting #117

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions distributor/src/distributor/filters.bal
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ map<string> awaitResultsCallbackMap = {};

# Filter to challenge authentication.
public type AuthChallengeFilter object {

*http:RequestFilter;

public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context)
Expand All @@ -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);
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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)) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note - This is swapped here because otherwise no point of wrapping the expression with parentheses.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we just remove the extra parentheses instead.

Suggested change
if (!headerValue.startsWith(auth:AUTH_SCHEME_BASIC)) {
if !headerValue.startsWith(auth:AUTH_SCHEME_BASIC) {

return false;
}

Expand Down
10 changes: 5 additions & 5 deletions distributor/src/distributor/genhtml.bal
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ballerina/time;
import ballerina/math;
import ballerina/lang.'string;
import ballerina/math;
import ballerina/time;

map<string> electionCode2Name = {
"2019PRE": "PRESIDENTIAL ELECTION - NOVEMBER 16, 2019",
Expand All @@ -22,7 +22,7 @@ map<string> electionCode2Name = {
"2015-PRE-REPLAY-015": "PRESIDENTIAL ELECTION - 08/01/2015 RESULT REPLAY"
};

function generateHtml (string electionCode, map<json> result, boolean sorted) returns string|error {
function generateHtml(string electionCode, map<json> 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)";
Expand Down Expand Up @@ -88,15 +88,15 @@ function generateHtml (string electionCode, map<json> result, boolean sorted) re
return "<html>" + head + body + "</html>";
}

function sortPartyResults (json[] unsorted) returns json[] {
function sortPartyResults(json[] unsorted) returns json[] {
return unsorted.sort(function (json r1, json r2) returns int {
int n1 = <int>r1.votes;
int n2 = <int>r2.votes;
return (n1 < n2) ? 1 : (n1 == n2 ? 0 : -1);
});
}

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();
Expand Down
6 changes: 3 additions & 3 deletions distributor/src/distributor/listeners.bal
Original file line number Diff line number Diff line change
Expand Up @@ -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), {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The standard we follow is to leave a space to be consistent with

listener http:Listener resultsListener = new http:Listener(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,
Expand Down
3 changes: 2 additions & 1 deletion distributor/src/distributor/main.bal
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ballerina/config;
import ballerina/websub;

import ballerinax/java.jdbc;

import maryamzi/websub.hub.mysqlstore;
Expand All @@ -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 =
Expand Down
1 change: 1 addition & 0 deletions distributor/src/distributor/messenger.bal
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ballerina/config;
import ballerina/log;
import ballerina/stringutils;

import wso2/twilio;

twilio:TwilioConfiguration twilioConfig = {
Expand Down
6 changes: 3 additions & 3 deletions distributor/src/distributor/results.bal
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 7 additions & 6 deletions distributor/src/distributor/save.bal
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -114,7 +115,7 @@ function __init() {

// read json string and convert to json
io:StringReader sr = new(dr.jsonResult, encoding = "UTF-8");
map<json> jm = <map<json>> sr.readJson();
map<json> jm = <map<json>> sr.readJson();

// put results in the cache
resultsCache.push(<Result> {
Expand Down Expand Up @@ -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):" +
<string> account.detail()?.message);
"Please provide valid 'eclk.sms.twilio.accountSid'/'authToken'/'source'(twilio mobile no):" +
<string> account.detail()?.message);
} else {
validTwilioAccount = true;
log:printInfo("SMS notification is enabled : twilio.account.status=" + account.status.toString());
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -265,7 +266,7 @@ function resetResults() returns error? {
}

# Add a polling division level result to the cumulative total.
function addToCumulative (map<json> jm) {
function addToCumulative(map<json> jm) {
boolean firstRound = jm.'type == PRESIDENTIAL_RESULT;
json[] pr = <json[]> checkpanic jm.by_party;

Expand Down
16 changes: 8 additions & 8 deletions distributor/src/distributor/website.bal
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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>";
head += "<title>Sri Lanka Elections Commission</title>";
head += "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\">";
Expand All @@ -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
Expand All @@ -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" {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 6 additions & 6 deletions subscriber/src/subscriber/genhtml.bal
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ballerina/time;
import ballerina/math;
import ballerina/lang.'string;
import ballerina/math;
import ballerina/time;

map<string> electionCode2Name = {
"2019PRE": "PRESIDENTIAL ELECTION - 16/11/2019",
Expand All @@ -22,7 +22,7 @@ map<string> electionCode2Name = {
"2015-PRE-REPLAY-015": "PRESIDENTIAL ELECTION - 08/01/2015 RESULT REPLAY"
};

function generateHtml (string electionCode, map<json> result, boolean sorted) returns string|error {
function generateHtml(string electionCode, map<json> 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 = "<head>";
Expand Down Expand Up @@ -71,15 +71,15 @@ function generateHtml (string electionCode, map<json> result, boolean sorted) re
return "<html>" + head + body + "</html>";
}

function sortPartyResults (json[] unsorted) returns json[] {
function sortPartyResults(json[] unsorted) returns json[] {
return unsorted.sort(function (json r1, json r2) returns int {
int n1 = <int>r1.votes;
int n2 = <int>r2.votes;
return (n1 < n2) ? 1 : (n1 == n2 ? 0 : -1);
});
}

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();
Expand All @@ -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;
}
2 changes: 1 addition & 1 deletion subscriber/src/subscriber/save.bal
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
39 changes: 19 additions & 20 deletions subscriber/src/subscriber/subscriber.bal
Original file line number Diff line number Diff line change
Expand Up @@ -45,38 +45,38 @@ 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);
subscriberPort = <@untainted> port;
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
});
Expand Down Expand Up @@ -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());
Expand All @@ -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 {
Expand Down