/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.boot;

import foam.core.X;
import foam.core.XFactory;
import foam.mlang.predicate.Predicate;

import java.util.ArrayList;
import java.util.List;

public class AltFactory implements XFactory {
  private final String key_;
  private final List<AltDelegate> altDelegates_ = new ArrayList<>();

  public AltFactory(String serviceKey) {
    key_ = serviceKey;
  }

  public void addDelegate(Predicate predicate, String serviceKey) {
    altDelegates_.add(new AltDelegate(predicate, serviceKey));
  }

  @Override
  public Object create(X x) {
    for ( var delegate : altDelegates_ ) {
      if ( delegate.f(x) ) {
        return delegate.get(x);
      }
    }
    return x.get(key_);
  }

  protected class AltDelegate {
    private final Predicate predicate_;
    private final String key_;

    public AltDelegate(Predicate predicate, String serviceKey) {
      predicate_ = predicate;
      key_ = serviceKey;
    }

    public boolean f(X x) {
      return predicate_.f(x);
    }

    public Object get(X x) {
      return x.get(key_);
    }
  }
}

@@ -282,16 +282,734 @@
 .List;%0A%0A
+/**%0A * AltFactory allows configuring multiple alternative services for an nspec%0A * depending on the associated predicates.%0A *%0A * Upon invoking the service wrapped with AltFactory, it checks the predicate%0A * of each alternative service then returns the service, otherwise, the original%0A * service is returned.%0A *%0A * Example usage: To configure a nspec serviceScript so that it returns%0A * %22serviceA%22 when the current user is user(id:1) and %22serviceB%22 for user(id:2)%0A * otherwise returns the %22defaultService%22.%0A *%0A * %3Cpre%3E%0A *   service = new foam.nanos.boot.AltFactory(%22defaultService%22);%0A *   service.addDelegate(new IsCurrentUser(1), %22serviceA%22);%0A *   service.addDelegate(new isCurrentUser(2), %22serviceB%22);%0A * %3C/pre%3E%0A */%0A
 public c

Add documentation