Antlr4 Javascript Visitor - javascript

I'm currently trying to develope a JavaScript Compiler with the help of an Antlr4 Visitor. I've got this already implemented with Java but cannot figure out how to do this in JavaScript. Probably somebody can answer me a few questions?
1: In Java there is a Visitor.visit function. If im right this isn't possibile with Javascript. Is there a work around for this?
2: My Javascript Visitor got all the generated visiting functions but when I use console.log(ctx) the context is undefined. Any idea why?
Extract from the SimpleVisitor.js:
// Visit a parse tree produced by SimpleParser#parse.
SimpleVisitor.prototype.visitParse = function(ctx) {
console.log(ctx);
};
Main js file:
var antlr4 = require('lib/antlr4/index');
var SimpleLexer = require('antlr4/SimpleLexer');
var SimpleParser = require('antlr4/SimpleParser');
var SimpleVisitor = require('antlr4/SimpleVisitor');
var input = "double hallo = 1;";
var chars = new antlr4.InputStream(input);
var lexer = new SimpleLexer.SimpleLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new SimpleParser.SimpleParser(tokens);
var visitor = new SimpleVisitor.SimpleVisitor();
parser.buildParseTrees = true;
var tree = parser.parse();
visitor.visitParse();
This is probably enough to start with ...
Bruno
Edit:
Probably the context is undefined because I call the function without arguments but where do I get the "starting"-context?
Edit2:
So I think I get the idea how this should work out. One Question remaining how do I determine which rule to call next inside each visitor function?

The basic idea behind the visitor is that you have to handle all the logic by yourself. To do this I generated the visitor using antlr. My own visitor overrides all functions that I need to implement my logic.
create lexer, tokens, ...
var antlr4 = require('antlr4/index');
var SimpleJavaLexer = require('generated/GrammarLexer');
var SimpleJavaParser = require('generated/GrammarParser');
var SimpleJavaVisitor = require('generated/GrammarVisitor');
var Visitor = require('./Visitor');
var input = "TestInput";
var chars = new antlr4.InputStream(input);
var lexer = new GrammarLexer.GrammarLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new GrammarParser.GrammarParser(tokens);
var visitor = new Visitor.Visitor();
parser.buildParseTrees = true;
var tree = parser.parse();
and call your entry function
visitor.visitTest(tree);
inside your new visitor you need to implement your new logic to determine which function to call next (the right context as argument is important)
var GrammarVisitor = require('generated/GrammarVisitor').GrammarVisitor;
function Visitor () {
SimpleJavaVisitor.call(this);
return this;
};
Visitor.prototype = Object.create(GrammarVisitor.prototype);
Visitor.prototype.constructor = Visitor;
Visitor.prototype.visitTest = function(ctx) {
// implement logic to determine which function to visit
// then call next function and with the right context
this.visitBlock(ctx.block());
};
I hope you can understand my basic idea. If anybody got any questions just comment.

Related

How to update URL address using ASP when based on JSON object

I'm making an application of a list of races in a table, this information is gotten from a JSON api. Upon selecting a race in a table I need a window to pop up with the name of the race in the url address bar, so something like asp?=race_name at the end.
How would I go about completing this?
I've looked this up but can't seem to find an answer, my guess is I'm googling the wrong thing as I'm not good at explaining
for (let i = 0; i < jsonObj.length; i++) {
document.getElementById(jsonObj[i].id).onclick = function () {
var newWin = window.open("","","width=700,height=700");
newWin.onload = function () {
var doc = newWin.document; // Create new document in window
var raceName = document.createElement('h3');
var distance = document.createElement('p');
var location = document.createElement('p');
var curPos = document.createElement('p');
var difference = document.createElement('p');
raceName.textContent = jsonObj[i].race_name;
distance.textContent = jsonObj[i].distance;
location.textContent = jsonObj[i].venue_name;
doc.body.appendChild(raceName);
doc.body.appendChild(distance);
doc.body.appendChild(location);
}
}
Here the window pops up and includes the correct information, I now just need to include code that would update the url address to include race name.

JScript to Javascript Conversion

The code below is a web service call to ICEPortal which is in JScript.NET format. Currently Iceportal doesn't have a webservice call using javascript. Has anybody done this using javascript? I need your help to convert the code below to javascript format.
// JScript.NET
var h:ICEPortal.ICEWebService = new ICEPortal.ICEWebService();
var myHeader:ICEPortal.ICEAuthHeader = new ICEPortal.ICEAuthHeader();
myHeader.Username = "distrib#distrib.com";
myHeader.Password = "password";
h.ICEAuthHeaderValue = myHeader;
var brochure:ICEPortal.Brochure;
var ErrorMsg;
var result = h.GetBrochure("MyMappedID", ErrorMsg, brochure);
I think you just need to remove the type definitions (in bold below):
var myHeader :ICEPortal.ICEAuthHeader = new ICEPortal.ICEAuthHeader();)
No idea what the ICEPortal classes are, but if they are available to your Javascript in the global namespace, the following should work. I've added these stubs in for the ICEPortal to test and it works fine for me in Chrome.
You'll obviously want to remove the stubs.
// stubbing out ICEPortal(s)
ICEPortal = {};
ICEPortal.ICEWebService = function() { return true; };
ICEPortal.ICEAuthHeader = function() { return true; };
ICEPortal.ICEWebService.prototype.GetBrochure = function() { return true; };
// end stubbing ICEPortal(s)
var h = new ICEPortal.ICEWebService();
var myHeader = new ICEPortal.ICEAuthHeader();
myHeader.Username = "distrib#distrib.com";
myHeader.Password = "password";
h.ICEAuthHeaderValue = myHeader;
var brochure;
var ErrorMsg;
var result = h.GetBrochure("MyMappedID", ErrorMsg, brochure);

How can I use an ajax request to fire Webservice calls in Javascript

I am currently working on some javascript that can be included in the header of surveys that use TrueSample, and will dynamically generate and fire Webservice calls for the survey. One of the requirements of Truesample is that after every page, it is sent the amount of time spend on that page, as well as some other arbitrary information generated in the beginning of the survey. I am trying to automate the every page web service call, so that I don't have to have hundreds of web services in every survey.
I am pretty far along, and have found some cool tricks to make this all work, but I am struggling with firing the webservice using javascript.
Here is what I have so far:
Qualtrics.SurveyEngine.addOnload(function()
{
var pageStart = new Date();
var beginning = pageStart.getTime();
// Necessary Variables
var account-id = parseInt("${e://Field/account-id}");
var passcode = parseInt("${e://Field/passcode}");
var survey-country = parseInt("${e://Field/survey-country}");
var end-client-id = parseInt("${e://Field/end-client-id}");
var page-exposure-duration;
var page-id = parseInt("${e://Field/pageID}");
var platform-id = parseInt("${e://Field/platform-id}");
var respondent-id = parseInt("${e://Field/respondent-id}");
var response-id = parseInt("${e://Field/response-id}");
var source-id = parseInt("${e://Field/source-id}");
var survey-id = parseInt("${e://Field/survey-id}");
var api-version = parseInt("${e://Field/api-version}");
//End Variables
var that = this;
that.hideNextButton();
var para = document.createElement("footnote");
var test = document.getElementById("Buttons");
var node = document.createElement('input');
var next = document.getElementById("NextButton");
node.id = "tsButton";
node.type = "button";
node.name = "tsButton";
node.value = " >> ";
node.onclick = function trueSample(){
var pageEnd = new Date();
var end = pageEnd.getTime();
var time = end - beginning;
window.alert(pageID + ", time spent on page = " + time);
Qualtrics.SurveyEngine.setEmbeddedData("pageID", pageID + 1);
new Ajax.Request('webserviceURL', {
parameters: {
account-id: account-id,
passcode: passcode,
survey-country: surveycountry,
end-client-id: end-client-id,
page-exposure-duration: time,
page-id: page-id,
platform-id: platform-id,
respondent-id: respondent-id,
response-id: response-id,
source-id: source-id,
survey-id: survey-id,
api-version: api-version}
});
that.clickNextButton();
};
para.appendChild(node);
test.insertBefore(para, next);
});
Does anyone have experience with firing webservice calls out of Javascript? And if so, do you have any ideas on how to finalize the ajax request and make it work? Or is there another(potentially better) method that I could use for these calls that would work? I understand that there is information on this on Stack Overflow, but I am having a hard time understanding how specific use cases apply to mine.
Also, please note that, while I would love to use JQuery, I am limited to vanilla Javascript, and Prototype.JS.
Using Traditional javascript XmlHttpRequest you can make an AJAX call. For a Webservice, we need couple of HTTP Headers. Like: SOAPAction, Content-Type, Accept. The values for these headers MUST be like below:
SOAPAction:""
Content-Type:text/xml
Accept:text/xml
So, additionally, your code should look something like this for making an AJAX call to the Webservice:
//Get XML Request Object
var request = new XMLHttpRequest();
// Define the URL
var url="http://your.end.point.url?wsdl";
//Define HTTP Method. Always POST for a Webservice
request.open("POST", url, true); // Remember that all the Webservice calls should be POST
//Setting Request Headers
request.setRequestHeader("SOAPAction", "\"\"");//Not sure of the escape sequence. The value should be "".
request.setRequestHeader("Accept","text/xml");
request.setRequestHeader("Content-Type","text/xml");
//Make your AJAX call
request.send(soap); // where soap is you SOAP Request Payload.
Parsing the response:
request.onreadystatechange=stateChanged;
function stateChanged()
{
if (request.status==200)
{
// Success. Parse the SOAP Response
}
if(request.status==500)
{
//Failure. Handle the SOAP Fault
}
}

Verify a signature using a certificate RSA Javascript

I am attempting to verify a signature with a certificate. We have to download the required certificate from the CA, verify the certificate, then verify the signature. I have no idea, and I'm hoping someone can shed some light. Here's what I have / know so far.
To sign a message, I used the following code:
function sign(sk, m, certname) {
var key = new RSAKey();
key.setPrivate(sk.n, sk.e, sk.d);
var h = CryptoJS.SHA256(JSON.stringify(m)).toString(CryptoJS.enc.Hex);
h = new BigInteger(h, 16);
var sig = key.doPrivate(h).toString(16);
var obj = { "type": "SIGNED", "msg": m, "certname": certname, "sig": sig };
return JSON.stringify(obj);
}
To verify a signature, I used the following code:
function verify(pk, signed) {
var key = new RSAKey();
var s = JSON.stringify(signed.sig).toString(CryptoJS.enc.Hex);
s = new BigInteger(s, 16);
key.setPublic(pk.n, pk.e);
var v = key.doPublic(s).toString(16);
var h = CryptoJS.SHA256(JSON.stringify(signed.msg)).toString(CryptoJS.enc.Hex);
return (v == h);
}
To verify a certificate, I used the following code: (EDIT: this is the new certificate verification function).
function verifyCertificate(signedCert, certname) {
var key = new RSAKey();
var s = JSON.stringify(signedCert.sig).toString(CryptoJS.enc.Hex);
s = new BigInteger(s, 16);
key.setPublic(CApk.n, CApk.e);
var v = key.doPublic(s).toString(16);
var h = CryptoJS.SHA256(JSON.stringify(signedCert.msg)).toString(CryptoJS.enc.Hex);
return (v == h);
}
And that's that. Can anyone please help. I don't know how to go about this.
EDIT: Okay, I think I have solved my own question (with assistance from the responses). This is the code that returns all positive results:
function verifyWithCert(sig) {
// 1. Download the required certificate from the CA
// 2. Verify the certificate
// 3. Verify the message
var certKey = new RSAKey();
var loadedCert = loadCert(sig.certname);
var certS = JSON.stringify(loadedCert.sig).toString(CryptoJS.enc.Hex);
certS = new BigInteger(certS, 16);
certKey.setPublic(CApk.n, CApk.e);
var certV = certKey.doPublic(certS).toString(16);
var certH = CryptoJS.SHA256(JSON.stringify(loadedCert.msg)).toString(CryptoJS.enc.Hex);
var verifyResult;
if (certV == certH) {
verifyResult = true;
}
var Sigkey = new RSAKey();
var s = JSON.stringify(sig.sig).toString(CryptoJS.enc.Hex);
s = new BigInteger(s, 16);
Sigkey.setPublic(loadedCert.msg.subject.pk.n, loadedCert.msg.subject.pk.e);
var v = Sigkey.doPublic(s).toString(16);
var h = CryptoJS.SHA256(JSON.stringify(sig.msg)).toString(CryptoJS.enc.Hex);
var verifySignature;
if (v == h) {
verifySignature = true;
}
var result = { "certificateFound": loadedCert ,"certificateVerified": verifyResult ,"signatureVerified": verifySignature };
return result;
}
(A note to other members of StackOverflow, I am also in this class so there's a bit of stuff that I mention that comes out of nowhere in regards to variables and other references.)
In the verifyCertificate function:
function verifyCertificate(signedCert, certname) {
var loadedCert = loadCert(certname);
// signedCert is the same as loadedCert above, the button runs the
// loadCert function and outputs the contents into the textarea,
// so the following will always be true.
var originalSig = JSON.stringify(signedCert.sig);
var loadedSig = JSON.stringify(loadedCert.sig);
log(loadedSig);
return (originalSig == loadedSig);
}
How am I supposed to verify the certificate then? What am I comparing the loaded CA certificate to? I thought maybe compare the public key in the certificate to the public key used to sign the message but... I don't know. I'm very confused.
You're on the right track with that though, think about the verify() function, and the details contained in the CApk variable at the top of the file. Can you hash the message from the loadCert() JSON response and match it against the output from:
function verify() {
//[...]
key.setPublic(pk.n, pk.e);
//[...]
}
Assuming you change a few variables?
It's similar to the method I used at least, so I'm hoping it's right. I figure if you can hash the message using the details in CApk, and compare it to a hash of the message contained in the JSON response, that verifies the certificate. Hopefully.
There is an error in 'verify certificate' approach.
you need to test the signature of certificate with public key of CA given in 355a3_main to verify, the code given here will only verify your certificate and will give s false positive for rest
i think this should work
var loadedCert = loadCert(certname);
var originalSig = JSON.stringify(signedCert.sig);
var loadedSig = JSON.stringify(loadedCert.sig);
log(loadedSig,originalSig);
var key = new RSAKey();
var s = JSON.stringify(signedCert.sig).toString(CryptoJS.enc.Hex);
s = new BigInteger(s, 16);
key.setPublic(CApk.n, CApk.e);
var v = key.doPublic(s).toString(16);
var h = CryptoJS.SHA256(JSON.stringify(signedCert.msg)).toString(CryptoJS.enc.Hex);
if (originalSig == loadedSig && v==h)
return true;
else
return false;
That being said what about the long message of arbitrary length?
Except... you know how he says his solutions for the core tasks are between 5 and 10 lines? well this is about 20 lines of code, so i don't know if I should be suspicious of my code
I used the function verify and verifycertificate again in the RSA signature verification with certificate function. That will make your code fairly short. and I really appreciate this post, you're all my life savers.

Jscript ReadLine() related

Can any one please tell me that we use ReadLine() to read a particular line from a file (.txt). Now I want to read the total content of the file (not only the first line). For that what method I need to use. I googled a lot but I cant get the solution.
My Code is given below:
var ForReading = 1;
var TristateUseDefault = -2;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newFile = fso.OpenTextFile(sFileName, ForReading, true, TristateUseDefault);
var importTXT = newFile.ReadLine();
This is returning the first line of the .txt file by importTXT variable. Now I want to get the total file content in importTXT.
Any suggestion will be very much helpful for me.
You use the ReadAll method:
var importTXT = newFile.ReadAll();
(Don't forget to close the stream when you are done with it.)
Here: ReadAll (msdn)
I found the example given very poor - for example it did not CLOSE the file, so I added this to the msdn page:
function ReadAllTextFile(filename)
{
var ForReading = 1;
var fso = new ActiveXObject("Scripting.FileSystemObject");
// Open the file for input.
var f = fso.OpenTextFile(filename, ForReading);
// Read from the file.
var text = (f.AtEndOfStream)?"":f.ReadAll(); // this is where it is read
f.Close();
return text;
}
var importTXT = ReadAllTextFile(sFileName);

Categories

Resources