FilteredTranslatedCRUDServiceImpl.java

/*
 * Copyright 2021 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 java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.gringlobal.api.v1.Pagination;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.CooperatorOwnedLang;
import org.gringlobal.model.SysLang;
import org.gringlobal.model.TranslatedCooperatorOwnedModel;
import org.gringlobal.service.FilteredTranslatedCRUDService;
import org.gringlobal.service.LanguageService;
import org.gringlobal.service.TranslationService;
import org.gringlobal.service.filter.IFullTextFilter;
import org.gringlobal.service.filter.TranslatedEntityFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.transaction.annotation.Transactional;

/**
 * The Class FilteredTranslatedCRUDServiceImpl.
 *
 * @param <E> the Entity type
 * @param <L> the EntityLang type
 * @param <T> the TranslatedEntity type
 * @param <F> the EntityFilter type
 * @param <R> the Repository for Entity
 */
@Transactional(readOnly = true)
public abstract class FilteredTranslatedCRUDServiceImpl<E extends TranslatedCooperatorOwnedModel<L, E>, L extends CooperatorOwnedLang<L, E>, T extends TranslationService.Translation<E, L>, F extends TranslatedEntityFilter<F, E>, R extends JpaRepository<E, Long> & QuerydslPredicateExecutor<E>>
	extends FilteredCRUDService2Impl<E, F, R> implements FilteredTranslatedCRUDService<E, L, T, F> {

	@Autowired
	protected TranslationService<E, L, T, F> translationSupport;

	@Autowired
	protected LanguageService languageService;

	private final Class<E> targetType;

	@SuppressWarnings("unchecked")
	public FilteredTranslatedCRUDServiceImpl() {
		this.targetType = ((Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		idSortParams = getIdSortParams();
	}

	@Override
	@Transactional
	public T create(T source) {
		assert(source.entity != null);
		return upsert(source.entity, languageService.getLanguage(LocaleContextHolder.getLocale()), source);
	}

	@Override
	public T loadTranslated(long id) {
		return translationSupport.getTranslated(load(id));
	}

	@Override
	public T reload(T source) {
		return translate(reload(source.entity));
	}

	protected final T translate(E source) {
		return translationSupport.getTranslated(source);
	}

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

	protected Page<T> listFiltered(Class<E> 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()) {
				var entityPage = elasticsearchService.findAll(clazz, filter, null, page, this::list, boostFields);
				var content = entityPage.getContent();
				if (content.isEmpty()) {
					return Page.empty(page);
				} else {
					return new PageImpl<>(translationSupport.getTranslated(entityPage.getContent()), page, entityPage.getTotalElements());
				}
			}
		}

		return translationSupport.list(filter, page);
	}

	@Override
	public List<L> getLangs(long entityId) {
		return translationSupport.listTranslations(get(entityId));
	}

	@Override
	@Transactional
	public L remove(E entity, SysLang sysLang) {
		return translationSupport.deleteTranslation(entity, sysLang);
	}

	@Override
	@Transactional
	public L upsert(E entity, SysLang sysLang, L input) {
		assert(!entity.isNew());
		assert(input.getEntity() == null || input.getEntity().getId().equals(entity.getId()));
		assert(input.getSysLang() == null || input.getSysLang().getId().equals(sysLang.getId()));
		return translationSupport.upsertLang(entity, sysLang, input);
	}

	private T upsert(@NotNull E entity, SysLang sysLang, T source) {
		if (entity.isNew()) {
			E reloaded = create(entity);
			translationSupport.addLang(reloaded, sysLang, source.updateLang(translationSupport.newLang()));
			return translate(reloaded);
		} else {
			E reloaded = update(entity);
			translationSupport.upsertLang(reloaded, sysLang, source.updateLang(translationSupport.getLang(entity, sysLang)));
			return translate(reloaded);
		}
	}

}