All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.zeebe.servicecontainer.ServiceGroupReference Maven / Gradle / Ivy

/*
 * Copyright © 2017 camunda services GmbH ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.zeebe.servicecontainer;

import java.util.Collection;
import java.util.Map;
import java.util.function.BiConsumer;

public final class ServiceGroupReference {
  @SuppressWarnings("rawtypes")
  private static final BiConsumer NOOP_CONSUMER =
      (n, v) -> {
        // ignore
      };

  protected BiConsumer, S> addHandler;
  protected BiConsumer, S> removeHandler;

  @SuppressWarnings("unchecked")
  private ServiceGroupReference() {
    this(NOOP_CONSUMER, NOOP_CONSUMER);
  }

  private ServiceGroupReference(
      BiConsumer, S> addHandler, BiConsumer, S> removeHandler) {
    this.addHandler = addHandler;
    this.removeHandler = removeHandler;
  }

  public BiConsumer, S> getAddHandler() {
    return addHandler;
  }

  public BiConsumer, S> getRemoveHandler() {
    return removeHandler;
  }

  public static  ServiceGroupReference collection(Collection collection) {
    final BiConsumer, S> addHandler = (name, v) -> collection.add(v);
    final BiConsumer, S> removeHandler = (name, v) -> collection.remove(v);

    return new ServiceGroupReference<>(addHandler, removeHandler);
  }

  public static  ServiceGroupReference map(Map, S> map) {
    final BiConsumer, S> addHandler = (name, v) -> map.put(name, v);
    final BiConsumer, S> removeHandler = (name, v) -> map.remove(name, v);

    return new ServiceGroupReference<>(addHandler, removeHandler);
  }

  public static  ReferenceBuilder create() {
    return new ReferenceBuilder<>();
  }

  public static class ReferenceBuilder {
    protected final ServiceGroupReference referenceCollection = new ServiceGroupReference<>();

    public ReferenceBuilder onRemove(BiConsumer, S> removeConsumer) {
      referenceCollection.removeHandler = removeConsumer;
      return this;
    }

    public ReferenceBuilder onAdd(BiConsumer, S> addConsumer) {
      referenceCollection.addHandler = addConsumer;
      return this;
    }

    public ServiceGroupReference build() {
      return referenceCollection;
    }
  }
}