0

I have an application server written in java that must use different machine learning models based on the request context. For example my request context looks like

 class RequestContext {
      String clientId;
      String experimentId;
      String sessionId;
      ...
 }

Currently I have a delegation logic:

 if(requestContext.experimentId == "experiment1"
    && requestContext.clientId == "client1"
 ){
   // use model #1
 } else if(requestContext.experimentId == "experiment2"
           && requestContext.clientId == "client1"){
   // use model #2
 } ...

I could use guava's predicates to express these rules and upon match, delegate to the appropriate model. As a second step, I would like to move these out of the server code to an external configuration store and have the server periodically read from it. This would enable me to not have to deploy server code each time I change the delegation rule. Moreover, I could write a UI that would let the business users define the conditions and the model to use.

My idea is to first specify a list of conditions that are available (in this case, clientId, experimentId, and sessionId) and allow the user to write a simple java-like script to create the conditions, for example one would write

 clientId == "client1" && (sessionId != "session1" || experimentId == "experiment1")

then specify a model to use for when this condition is met. What library/techniques will help me parse a user specified predicate logic into a guava predicate-like object?

fo_x86
  • 2,583
  • 1
  • 30
  • 41
  • Why are you looking for external libraries? As far as I can see, parsing a user-defined predicate into the corresponding Requestcontext object is simple enough using guava. – Chthonic Project Feb 03 '14 at 10:09
  • How would I go about parsing the predicate logic that the user has specified. I would have to parse a string that contains the predicate logic into actual guava predicate objects. – fo_x86 Feb 03 '14 at 10:11

1 Answers1

0
final Pattern client_pattern = Pattern.compile("clientId\\s+==\\s+\"(.*?)\"");
Function<String, RequestContext> = new Function<String, RequestContext>() {
    public RequestContext apply(String s) {
        Matcher client_matcher = client_pattern.matcher(s);
        String client_id = client_matcher.find() ? client_matcher.group(1) : null;
        // similarly for experiment id and session id
        return new RequestContext(client_id, exp_id, session_id);
    }
};

That does the parsing. Now that you have the request context, the guava predicates are simple:

Predicate<RequestContext> pred_1 = new Predicate<RequestContext>() {
    public boolean apply(RequestContext rc) {
        return rc.clientId.equals("client1") && rc.experimentId.equals("experiment1");
    }
};

You could also write simpler atomic predicates and then use Predicates#and to combine them.

Chthonic Project
  • 8,216
  • 1
  • 43
  • 92