FileRepositoryClassLoader.java

/*
 * Copyright 2022 Global Crop Diversity Trust
 *
 * 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 org.gringlobal.custom.jasper;

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

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

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;
		}
	}
}