FileRepositoryClassLoader.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.custom.jasper;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.Path;

import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.model.RepositoryFolder;
import org.genesys.filerepository.service.RepositoryService;

public class FileRepositoryClassLoader extends ClassLoader {
	private final Path basicPath;
	private final RepositoryService repositoryService;

	public FileRepositoryClassLoader(Path basicPath, RepositoryService repositoryService) {
		this.basicPath = basicPath;
		this.repositoryService = repositoryService;
	}

	@Override
	public InputStream getResourceAsStream(String name) {
		try {
			var resourceBytes = searchForResource(basicPath, name);
			return resourceBytes != null ? new ByteArrayInputStream(resourceBytes) : null;
		} catch (InvalidRepositoryPathException e) {
			return null;
		}
	}

	private byte[] searchForResource(Path path, String name) throws InvalidRepositoryPathException {
		byte[] resourceBytes = getResourceBytes(path, name);
		if (resourceBytes != null) {
			return resourceBytes;
		}
		var folders = repositoryService.listPathsRecursively(path);
		for (RepositoryFolder folder : folders) {
			resourceBytes = getResourceBytes(folder.getFolderPath(), name);
			if (resourceBytes != null) {
				break;
			}
		}
		return resourceBytes;
	}

	private byte[] getResourceBytes(Path path, String fileName) {
		try {
			var file = repositoryService.getFile(path, fileName);
			return repositoryService.getFileBytes(file);
		} catch (Exception e) {
			return null;
		}
	}
}