BaseAttachmentFilteredSupport.java

/*
 * Copyright 2025 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.service.impl;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.ParameterizedType;

import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.api.Pagination;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.CooperatorAttachment;
import org.gringlobal.model.CooperatorOwnedModel;
import org.gringlobal.service.AttachmentFilteredService;
import org.gringlobal.service.AttachmentService;
import org.gringlobal.service.ElasticsearchService;
import org.gringlobal.service.filter.IFullTextFilter;
import org.gringlobal.spring.persistence.ExtendedJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * Base implementation of filtered attachment service
 */
@Validated
@Slf4j
public abstract class BaseAttachmentFilteredSupport<T extends CooperatorOwnedModel, A extends CooperatorAttachment, R extends AttachmentService.AttachmentRequest<A>, F extends EmptyModelFilter<F, A, ?>> extends BaseAttachmentSupport<T, A, R> implements AttachmentFilteredService<T, A, R, F> {

	@Autowired(required = false)
	protected ElasticsearchService elasticsearchService;

	@SuppressWarnings("unchecked")
	private Class<A> targetType = ((Class<A>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]);

	protected BaseAttachmentFilteredSupport(NumberPath<Long> owningEntityId, NumberPath<Long> qAttachId) {
		super(owningEntityId, qAttachId);
	}

	@Override
	public Page<A> list(F filter, Pageable page) throws SearchException {
		return list(targetType, adjustFilter(filter), page);
	}

	protected Page<A> list(Class<A> clazz, F filter, Pageable page, String... boostFields) throws SearchException {
		page = Pagination.addSortByParams(page, idSortParams);

		if (filter instanceof IFullTextFilter) {
			IFullTextFilter ftf = (IFullTextFilter) filter;
			// if (ftf.isFulltextQuery() && elasticsearchService != null) { // This could be quietly ignoring full-test search
			if (ftf.isFulltextQuery()) {
				return elasticsearchService.findAll(clazz, filter, null, page, (entityIds) -> list(entityIds), boostFields);
			}
		}

		BooleanBuilder predicate = new BooleanBuilder();
		if (filter != null) {
			predicate.and(filter.buildPredicate());
		}

		if (attachRepository instanceof ExtendedJpaRepository && entityListQuery() != null) {
			JPAQuery<A> query = entityListQuery().where(predicate);
			return ((ExtendedJpaRepository<A, Long>)attachRepository).findAll(query, page);
		} else {
			// default implementation without custom loading
			return attachFinder.findAll(predicate, page);
		}
	}

	/**
	 * Adjust filter lets us add additional constraints
	 * @param filter the original filter
	 * @return adjusted filter
	 */
	protected F adjustFilter(F filter) {
		return filter;
	}

	protected void updateRepositoryFileMetadata(A updated, A target) {
		if (updated.getRepositoryFile() != null && target.getRepositoryFile() != null) {
			try {
				repositoryService.updateMetadata(updated.getRepositoryFile());
			} catch (Throwable e) {
				log.error(e.getMessage(), e);
			}
		}
	}
}