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

com.spotify.zoltar.ModelLoader Maven / Gradle / Ivy

There is a newer version: 0.6.0
Show newest version
/*-
 * -\-\-
 * zoltar-core
 * --
 * Copyright (C) 2016 - 2018 Spotify AB
 * --
 * 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 com.spotify.zoltar;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;

/**
 * Handles the model loading logic.
 *
 * @param  Underlying model instance.
 */
@FunctionalInterface
public interface ModelLoader> {

  /**
   * Supplier of {@link Model}. Can throw {@link Exception} when the supplier is invoked.
   */
  @FunctionalInterface
  interface ThrowableSupplier> {

    M get() throws Exception;

  }

  /**
   * Lifts a supplier into a {@link ModelLoader}.
   *
   * @param supplier model supplier.
   * @param  Underlying model instance.
   */
  static > ModelLoader lift(final ThrowableSupplier supplier) {
    return () -> CompletableFuture.supplyAsync(() -> {
      try {
        return supplier.get();
      } catch (final Exception e) {
        throw new CompletionException(e);
      }
    });
  }

  /**
   * Get's the underlying model instance.
   *
   * @return Model instance
   */
  CompletionStage get();

  /**
   * Get's the underlying model instance.
   *
   * @return Model instance
   */
  default M get(final Duration duration) throws InterruptedException,
                                                ExecutionException,
                                                TimeoutException {
    return get()
        .toCompletableFuture()
        .get(duration.toMillis(), TimeUnit.MILLISECONDS);
  }

  default > L with(final Function, L> fn) {
    return fn.apply(this);
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy