0
  • It should be doable with few lines of (Java) code.
  • The text is received from a webserver but I must not trust HTTP headers. It has to verified merely by the content.
7
  • Java != JavaScript. And I suppose it is possible, but it is most likely more in depth than just a "few lines of code" Commented Sep 23, 2016 at 13:37
  • 5
    @Adjit — The question is asking how to write a program in Java that can detect is some text is JavaScript or not. There doesn't appear to be any mistaken impression that the two languages are the same thing. Commented Sep 23, 2016 at 13:38
  • @Quentin oooh, well maybe the OP should clarify a little Commented Sep 23, 2016 at 13:39
  • 1
    If you can't trust the server to give you back what you are expecting, then that is the first sign to not even attempt to do this! However, it is doable, but you will never be able to fully trust it! Commented Sep 23, 2016 at 13:39
  • 2
    you'd need to parse the text, generate an AST, and then maybe run it through an AST spec. i don't know of any javascript ast specs for java but if you are using javascript take a look at esprima.org Commented Sep 23, 2016 at 13:39

1 Answer 1

2

Of course! Just use a JS parser, such as Esprima (a reference in the industry), and do:

function isIsReallyJSCodeOrWhat(code) {
  try {
    esprima.parse(code);
  } catch (err) {
    return false;
  }

  return true;
}

It's that simple. JS parsers (esprima, acorn, etc.) are all based on the Estree specification. Try having a look at the AST produced by esprima.parse. It's simple to read, and to modify. This way, you can check that the code does nothing you don't want, that it does not refer to some specific variables, etc.

If you want to quickly test some code and see what AST it produces, go to http://esprima.org/demo/parse.html.

Sign up to request clarification or add additional context in comments.

3 Comments

The question is asking how to parse the JavaScript in Java, not in JavaScript.
Since there are not a lot of tools for this in Java, the easiest way would be to call this little JS function from Java. Since JDK 1.6, you get Rhino for that; or if in Android, you can spawn (and cache) a transient webview to call the same thing. For such task, tt's often more easy to use a scripting language (think Lua, Python and JS) from an application than writing the algorithm natively.
Unfortunately this is not an answer to my question. On of the requirements is using Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.