I've been looking for a Javascript parser on Java that can capture and list all Javascript functions, for example
function beforeSave('Test', request, response) {
response.body = entity.foo;
if (request.query.isExist('Test', 'foo', entity.foo)) {
response.error();
} else {
response.success();
}
}
function afterSave('Test', request, response) {
response.body = 'done';
response.success();
}
Is there a Javascript parser library for Java that would be able to list all Functions from a given source text as well as get the function bodies as needed.
I believe java.util.regex is the right tool for the job.
With that you can search for keywords in strings. Example for getting the body of the function:
import java.util.regex.*;
Pattern p1 = Pattern.compile("function', \"([^\"]*)\"");
Matcher m1 = p1.matcher(String);
System.out.println(String.format("function=%s",m1.group(1)));
To see more about this go to the question here.
I´m not a Java-expert by any means so check out the other question and the documentation of the library for more information.
Related
I am sending an HTTP request and its sending responses like 'abc' , 'cde' etc dynamically. How can I group and get the count of 'abc', 'cde' responses? I need to analyze the results based on the responses I am getting.
Please advice.
You can do it with the help of beanshell processor
example could be,
import org.springframework.util.StringUtils;
String Pattern1= "abc";
int countPattern1 = StringUtils.countOccurrencesOf(new String(data),Pattern1);
vars.put("Count_Pattern1", String.valueOf(countPattern1));
Here This is simple java code which is finding occurrences of string "abc" in Response of sampler (Which is present in data variable)
vars.put is finally returning the count of occurrences in Count_Pattern1 variable. You can write your logic in same beanshell or elsewhere like,
import org.springframework.util.StringUtils;
String Pattern1= "abc";
int countPattern1 = StringUtils.countOccurrencesOf(new String(data),Pattern1);
vars.put("Count_Pattern1", String.valueOf(countPattern1));
//Your logic
Add a Beanshell PostProcessor as a child of the request which returns these abc or cde bits.
Put the following code into the PostProcessor's "Script" area
String response = new String(data);
if (response.contains("abc")) {
prev.setSampleLabel("abc");
}
if (response.contains("cde")) {
prev.setSampleLabel("cde");
}
Explanation:
data is a shorthand to byte-array containing parent sampler response data.
prev stands for the parent sampler SampleResult instance
basing on whether response contains abc or cde parent sampler name will be changed accordingly (see image below for demo, "Dummy Sampler" becomes "abc" or "cde")
analyze results with the listener of your choice basing on sampler name
See How to use BeanShell: JMeter's favorite built-in component guide for comprehensive information on Beanshell scripting, pre-defined variables reference and kind of Beanshell cookbook.
I am planning to implement a JavaScript parser in java. I know that there are several ways to do it. There are view frameworks/engines/parsers which could help to do it right, like:
ANTLR 3/4:
it seems like there is only a js grammer for v3
Mozilla Rhino: atm i can parse variable names on initital (top-) namespace. but i am not able to parse nested scopes e.g. object members.. hm..
Nashorn: maybe i should give it a try..?
Maybe:
closure-compiler: IMHO this is very nice. but not for "non-google" js-code :) e.g. you have to apply several coding conventions to your javascript sources to get it working properly..
maybe it is possible to adapt Packer to do it? Is there a Java implementation of Packer???
There is EcmaScript 5.1 related to this article. it seems to be very comfortable. But this is not exactly what I´am looking for.. And still no java :)
My question is:
What could/would be the best way to parse JavaScript for:
(object-)function names
(object-)member names e.g. variables
Is it even possible to do it?
What would be your approach? For me it is not essential to parse ALL special markups of JavaScript.. The important factor would be to parse function/variables in a consistent context for the typical markups like this:
// Avoid `console` errors in browsers that lack a console.
function Object() {
var method;
var noop = function() {
};
var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
};
var obj = new Object();
var test = "Hello World";
The parse should be able to deliver this information:
Node: Object
Node: Object.method
Node: Object.noop
Node: Object.length
Node: Object.console
Node: Object
Node: obj
Node: test
There is no direct need of any determination if the node is a function/variable.
By using java i want to convert javascript template (i try to make ) to pure javascript
Here is example :
Input
<? function test()
{
return "Just a message";
}
if("a"=="b")
{
?>
<h1><?=test()?></h1>
<?
}
?>
<?=test()?>
</head></html>
output pure js example
out.print("<html><head>");
function test()
{
return "Just a message";
}
out.print("<h1>");
if("a"=="b")
{
out.print(test());
}
out.print("</h1>");
out.print("</head></html>");
I need a function to convert javascript template to pure javascript an eval it later .
p/s
a example using javascript function here http://ejohn.org/blog/javascript-micro-templating/
but i'm not sure it work perfectly when given conplex template
You can match every pair. And each pair is javascript and the rest is outputted using out.print(...). A simple regex can do the job.
Or you can look at template engines which are fully tested and supported, such as: http://mustache.github.io/
This is very similar to this other SO question about arrays.
If I evaluate:
y = {a: 1, b: 2, "momomomo": function() { return "hi"; }, zz: "wham"}
in a Javascript script instantiated via JSR223 (ScriptingEngine), I get a NativeObject of some sort (I see this in Eclipse's debugger) and have no idea how to access its properties. Furthermore I don't even know which .jar file, if any, I need to add to my build path to be able to work with the class in question, and if I find an approach that works in Rhino Javascript, it is useless for Jython.
Seems like JSR223 should have included language-agnostic access methods to ScriptingEngine to provide the ability to wrap a returned object as a List<Object> for arrays or a Map<String, Object> for associative arrays.
Any suggestions?
I too am trying to embed different scripting languages with more features than jsr223 or bsf. For that i have had to define my own interfaces and implement thse around each different scripting engine.
One feature i wanted was the ability to pass a Function (java interface with a single method) to my scripting engine and have it just work when passed parameters. Each of my embedded scripting engines has a layer where i wrap/unwrap from/to java values from the scripting environment.
I would suggest the best way to solve the problem is for your wrapper around the scripting engine to provide a getValue( String name ) and have it fix up javascript arrays convertoing them to java Lists. Naturally the setValue(String, Object) would check if the value is a List and convert it back to a js array and so on. Its tedious :()
Convert it to a java object and return it. You can then work with the java object as you would normally.
The following is an example conversion function
function convertToJava(o) {
var rval;
if (Array.isArray(o)) {
rval = new java.util.ArrayList();
for (var key in o) {
rval.add(convertToJava(o[key]));
}
}
else if (typeof o === 'object') {
rval = new java.util.HashMap();
for (var key in o) {
rval.put(key, convertToJava(o[key]));
}
}
else if (typeof o === 'function') {
// skip
}
else if (typeof o === 'undefined') {
// skip
}
else {
rval = o;
}
return rval;
}
I've used the java compiler tree api to generate the ast for java source files. However, i'm unable to access th comments in the source files.
So far, i've been unable to find a way to extract comments from source file .. is there a way using the compiler api or some other tool ?
Our SD Java Front End is a Java parser that builds ASTs (and optionally symbol tables). It captures comments directly on tree nodes.
The Java Front End is a member of a family of compiler langauge front ends (C, C++, C#, COBOL, JavaScript, ...) all of which are supported by DMS Software Reengineering Toolkit. DMS is designed to process languages for the purposes of transformation, and thus can capture comments, layout and formats to enable regeneration of code preserving the original layout as much as possible.
EDIT 3/29/2012: (in contrast to answer posted for doing this with ANTLR)
To get a comment on an AST node in DMS, one calls the DMS (lisp-like) function
(AST:GetComments <node>)
which provide access to the array of comments associated with the AST node. One can inquire about the length of this array (may be null), or for each array element, ask for any of these properties: (AST:Get... FileIndex, Line, Column, EndLine, EndColumn, String (exact Unicode comment content).
The comments obtained through getCommentList method of CompilationUnit will not have the comment body. Also the comments will not be visited, during and AST Visit. Inorder to visit the comments we have call accept method for each comment in the Comment List.
for (Comment comment : (List<Comment>) compilationUnit.getCommentList()) {
comment.accept(new CommentVisitor(compilationUnit, classSource.split("\n")));
}
The body of the comments can be obtained using some simple logic. In the below AST Visitor for comments, we need to specify the Complied class unit and the source code of the class during initialization.
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.BlockComment;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.LineComment;
public class CommentVisitor extends ASTVisitor {
CompilationUnit compilationUnit;
private String[] source;
public CommentVisitor(CompilationUnit compilationUnit, String[] source) {
super();
this.compilationUnit = compilationUnit;
this.source = source;
}
public boolean visit(LineComment node) {
int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
String lineComment = source[startLineNumber].trim();
System.out.println(lineComment);
return true;
}
public boolean visit(BlockComment node) {
int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
int endLineNumber = compilationUnit.getLineNumber(node.getStartPosition() + node.getLength()) - 1;
StringBuffer blockComment = new StringBuffer();
for (int lineCount = startLineNumber ; lineCount<= endLineNumber; lineCount++) {
String blockCommentLine = source[lineCount].trim();
blockComment.append(blockCommentLine);
if (lineCount != endLineNumber) {
blockComment.append("\n");
}
}
System.out.println(blockComment.toString());
return true;
}
public void preVisit(ASTNode node) {
}
}
Edit: Moved splitting of source out of the visitor.
Just for the record. Now with Java 8 you have a whole interface to play with comments and documentation details here.
You might to use a different tool, like ANTLR's Java grammar. javac has no use for comments, and is likely to discard them completely. The parsers upon which tools like IDEs are built are more likely to retain comments in their AST.
Managed to solve the problem by using the getsourceposition() and some string manipulation (no regex was needed)