r/javahelp • • Dec 20 '22

Unsolved Scripting language for Java

hello

i have to give my users ability to modify their data via simple code snippets. sometimes its simple math expressions ("price * 1.5" etc) sometimes they split strings, extract data from json etc. this gives my platform a lot of flexibility.

i want to use a fast scripting language in java. i tried graal.js with scriptenginemanager but it takes too long to boot up.

is there any faster alternatives or other approaches ? i am asking this because i just started using java and if there is a better solution in java ecosystem i dont want to miss it

thank everyone in advance for any help :)

16 Upvotes

23 comments sorted by

•

u/AutoModerator Dec 20 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

7

u/NYXIC0N Dec 20 '22

Lua is a well known scripting language, theres a java port available, but i dont know how up to date this is. It at least claims that "good perfomance is a major goal of luaJ".

https://github.com/luaj/luaj

May be worth a try.

1

u/prisonbird Dec 20 '22

thanks. i heard about lua before. i will check it out.

4

u/Battlepine Dec 20 '22

Groovy works well for my team.

1

u/prisonbird Dec 20 '22

how do you run groovy ?

1

u/Battlepine Dec 20 '22

Their documentation is really good.

https://groovy-lang.org/documentation.html

Groovy is extensible w/ Java enough that I've literally copied code from unit tests in Java, repurposed it a bit, and ran it within Groovy. It makes it super easy to test and get performance insights from pain points in code.

0

u/prisonbird Dec 20 '22

i know groovy but what i meant is : i have a web ui, i am getting some piece of code from the users. and i have to run this code on my backend for a lot of records in my database. what should be the correct approach to do this ?
i am not experienced in java ecosystem and i feel like first thing i saw in the documentation might not be the correct approach since my use case is weird

1

u/pragmos Extreme Brewer Dec 20 '22

1

u/Zyklonik kopi luwak civet Dec 21 '22

The script engine has been deprecated for OpenJDK, however. It's only available via GraalVM, I believe.

2

u/pragmos Extreme Brewer Dec 21 '22

The module is still there for Java 17 though. Maybe you meant the JavaScript engine implementation (Nashorn, was it?) was removed from the JDK.

1

u/Zyklonik kopi luwak civet Dec 21 '22

Ah yes, my bad. Yes, it was the Nashorn script engine which was deprecated via JEP 335.

1

u/prisonbird Dec 20 '22

how do you run groovy ?

2

u/Zyklonik kopi luwak civet Dec 20 '22

Unfortunately, OpenJDK removed its scripting engine support for good claiming that there weren't enough users to justify the maintenance effort.

What you want instead (depending on the seriousness/importance of your usecase) is a custom scripting language that compiles down to Java bytecode. https://javacc.github.io/javacc/ is what you want to be looking at. That way, you can embed your own language inside the same JVM (and indeed the same application) running your main application.

I personally would handcode a parser for a custom scripting language, but if you're not interested in that, or short on time, have a look at JavaCC linked above.

1

u/prisonbird Dec 20 '22

sounds cool, i will try to parse javascript with this.

1

u/Zyklonik kopi luwak civet Dec 20 '22

Another option is, if you don't mind Lisp, using something like ABCL (Armed Bear Common Lisp) (https://abcl.org/) as a scripting language. Then you get the full power of Common Lisp as a scripting language!

For instance, suppose we wished to define the factorial function in Common Lisp, and then wished to invoke that from our Java program:

~/dev/playground/abcl-demo:$ jshell --class-path ./abcl.jar
|  Welcome to JShell -- Version 20-ea
|  For an introduction type: /help intro

jshell> import org.armedbear.lisp.*

jshell> Interpreter interp = Interpreter.createInstance()
Failed to introspect virtual threading methods: java.lang.NoSuchMethodException: java.lang.Thread.builder()
interp ==> org.armedbear.lisp.Interpreter@4bff2185

jshell> String program = """
   ...> (defun factorial (n)
   ...>   (if (zerop n)
   ...>     1
   ...>     (* n (factorial (- n 1)))))
   ...> """
program ==> "(defun factorial (n)\n  (if (zerop n)\n    1\n   ...  (factorial (- n 1)))))\n"

jshell> interp.eval(program)
$4 ==> COMMON-LISP-USER:FACTORIAL

jshell> org.armedbear.lisp.Package pkg = Packages.findPackage("COMMON-LISP-USER")
pkg ==> org.armedbear.lisp.Package@6d2d99fc

jshell> Symbol factSym = pkg.findAccessibleSymbol("FACTORIAL")
factSym ==> COMMON-LISP-USER:FACTORIAL

jshell> org.armedbear.lisp.Function factorial = (org.armedbear.lisp.Function) factSym.getSymbolFunction()
factorial ==> org.armedbear.lisp.Closure@f9b5552

jshell> LispObject res = factorial.execute(Fixnum.getInstance(10))
res ==> org.armedbear.lisp.Fixnum@375f00

jshell> res.intValue()
$9 ==> 3628800

The program string could come from a user script, for example. Of course, that's a minor issue.

9

u/seanprefect Grumpy Guy Who Remembers Java 2 Dec 20 '22

Ive always had good luck with Groovy

2

u/mboekhoff Dec 20 '22

I've personally used JavaScript to achieve this before, using the Rhino engine. This was years ago, though, so take that with a pinch of salt.

1

u/[deleted] Dec 20 '22

1

u/Zyklonik kopi luwak civet Dec 20 '22

Note that this is native code though, so it necessarily runs in its own process space, not embedded within the same JVM instance as the host application.

1

u/sometimes_insightful Dec 21 '22 edited Dec 21 '22

Depending on how complex your expressions are, you might consider using something like antlr and writing your own parser for it. Setting up something to handle math and string operations wouldn’t be very hard and then you can control the syntax however you like. You can use a visitor and visit each node in the syntax tree and return the result of each sub-expression.

Another benefit is this makes security much easier. If you are running a scripting engine you need to keep in mind that people can try to write malicious expressions. Something simple as an infinite loop can hang your process, not to mention worse attacks that could escape the sandbox.

Here is an example grammar for arithmetic you could try out, but keep in mind you can make it do pretty much anything.

https://github.com/antlr/grammars-v4/blob/master/arithmetic/arithmetic.g4

-1

u/ozzymozzy2211 Dec 20 '22

jshell can run java https://en.m.wikipedia.org/wiki/JShell

never tried before but looks powerful

3

u/Zyklonik kopi luwak civet Dec 20 '22

JShell is simply the REPL for Java. It's Java, not a scripting language.