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

io.carml.engine.sourceresolver.ClassPathResolver Maven / Gradle / Ivy

There is a newer version: 0.4.11
Show newest version
package io.carml.engine.sourceresolver;

import java.util.Optional;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ClassPathResolver implements SourceResolver {

  private final String basePath;

  private final Class loadingClass;

  public static ClassPathResolver of(String basePath) {
    return of(basePath, null);
  }

  public static ClassPathResolver of(Class loadingClass) {
    return of("", loadingClass);
  }

  public static ClassPathResolver of(String basePath, Class loadingClass) {
    return new ClassPathResolver(basePath, loadingClass);
  }

  @Override
  public Optional apply(Object source) {
    return unpackFileSource(source).map(relativePath -> {
      String sourceName = basePath.equals("") ? relativePath : String.format("%s/%s", basePath, relativePath);

      return loadingClass == null ? ClassPathResolver.class.getClassLoader()
          .getResourceAsStream(sourceName) : loadingClass.getResourceAsStream(sourceName);
    });
  }
}