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

io.datakernel.loader.StaticLoaderCache Maven / Gradle / Ivy

package io.datakernel.loader;

import io.datakernel.async.Promise;
import io.datakernel.bytebuf.ByteBuf;

import java.util.function.BiConsumer;
import java.util.function.Function;

import static io.datakernel.bytebuf.ByteBuf.wrapForReading;

class StaticLoaderCache implements StaticLoader {
	public static final byte[] NOT_FOUND = {};

	private final StaticLoader resourceLoader;
	private final Function get;
	private final BiConsumer put;

	public StaticLoaderCache(StaticLoader resourceLoader, Function get, BiConsumer put) {
		this.resourceLoader = resourceLoader;
		this.get = get;
		this.put = put;
	}

	@Override
	public Promise load(String path) {
		byte[] bytes = get.apply(path);
		if (bytes != null) {
			return Promise.of(wrapForReading(bytes));
		} else if (bytes == NOT_FOUND) {
			return Promise.ofException(NOT_FOUND_EXCEPTION);
		} else {
			return doLoad(path);
		}
	}

	private Promise doLoad(String path) {
		return resourceLoader.load(path)
				.whenComplete((buf, e2) -> {
					if (e2 == null) {
						put.accept(path, buf.getArray());
					} else if (e2 == NOT_FOUND_EXCEPTION) {
						put.accept(path, NOT_FOUND);
					}
				});
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy