DescriptorLangApiServiceImpl.java

/*
 * Copyright 2024 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.genesys.server.api.v2.facade.impl;

import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.genesys.server.api.v2.facade.DescriptorLangApiService;
import org.genesys.server.api.v2.model.impl.DescriptorLangDTO;
import org.genesys.server.exception.SearchException;
import org.genesys.server.model.traits.DescriptorLang;
import org.genesys.server.model.vocab.VocabularyTerm;
import org.genesys.server.service.DescriptorLangService;
import org.genesys.server.service.VocabularyTermLangService;
import org.genesys.server.service.filter.DescriptorLangFilter;
import org.genesys.server.service.filter.VocabularyTermLangFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class DescriptorLangApiServiceImpl extends APIFilteredServiceFacadeImpl<DescriptorLangService, DescriptorLangDTO, DescriptorLang, DescriptorLangFilter> implements DescriptorLangApiService {
	

	@Autowired
	@Lazy
	private VocabularyTermLangService vocabularyTermLangService;

	@Override
	protected DescriptorLang convert(DescriptorLangDTO source) {
		return mapper.map(source);
	}

	@Override
	protected DescriptorLangDTO convert(DescriptorLang source) {
		return mapper.map(source);
	}

	@Override
	public Page<DescriptorLangDTO> list(DescriptorLangFilter filter, Pageable page) throws SearchException {
		var result = service.list(filter, page);
		return result.map(dl -> {
			var dto = convert(dl);
			if (CollectionUtils.isNotEmpty(dl.getEntity().getTerms())) {
				VocabularyTermLangFilter f = new VocabularyTermLangFilter();
				f.entityId = dl.getEntity().getTerms().stream().map(VocabularyTerm::getId).collect(Collectors.toSet());
				f.languageTag = Set.of(LocaleContextHolder.getLocale().toLanguageTag());
				try {
					dto.setTerms(mapper.map(vocabularyTermLangService.list(f, Pageable.unpaged()).getContent(), mapper::map));
				} catch (SearchException e) {
					throw new RuntimeException(e);
				}
			}
			return dto;
		});
	}

}