简体   繁体   中英

How to parse a function received as a query parameter in REST request?

I've got a use case where I would like to parse a function received as a parameter in my REST request, which can be GET or POST. Something like what Solr does:

https://localhost:8000/abc/solr?sort=div(popularity,price),bf="recip(rord(price),1,1000,1000)^0.3"

As you can see, params sort and bf are functions rather than values. Elastic search does something similar as well.

I know I can write a custom parser with a custom protocol, but I was wondering if there's any standard library, which could make my work easier. I really want to avoid writing something from scratch where I'll have to do all the syntax checking myself.

I'm tagging ES and Solr devs as they might be able to help me. Although, these are just examples and my application has nothing to do with Solr or Elastic Search .

var url = " http://www.abx.com ?" + $.param({foo: "bar", baz: "kuuq"})

I ended up using Nashorn, where I'll send javascript functions via HTTP requests and my java backend server will execute those functions using Nashorn javascript engine that comes with Java 8. For eg

import java.util.function.Function;
import javax.script.*;

public class TestFunction {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        @SuppressWarnings("unchecked")
        Function<Object,Object> f = (Function<Object,Object>)engine.eval(
            String.format("new java.util.function.Function(%s)", args[0]));
        for (int i = 1; i < args.length; i++) {
            System.out.println(f.apply(args[i]));
        }
    }
}

For example, running the command:

java TestFunction 'function(x) 3 * x + 1' 17 23 47

produces:

52.0
70.0
142.0

See this answer for more details: How to convert a string to a lambda expression?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM