TranslatedCRUDController.java

/*
 * Copyright 2023 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.api.v2;

import com.querydsl.core.types.OrderSpecifier;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.api.model.CooperatorOwnedDTO;
import org.gringlobal.api.model.CooperatorOwnedLangDTO;
import org.gringlobal.api.model.Translated;
import org.gringlobal.api.v1.ApiBaseController;
import org.gringlobal.api.v1.FilteredCRUDController;
import org.gringlobal.api.v1.FilteredPage;
import org.gringlobal.api.v1.MultiOp;
import org.gringlobal.api.v1.Pagination;
import org.gringlobal.api.v2.facade.APIFilteredTranslatedServiceFacade;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.CooperatorOwnedLang;
import org.gringlobal.model.TranslatedCooperatorOwnedModel;
import org.gringlobal.service.LanguageService;
import org.gringlobal.service.ShortFilterService;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public abstract class TranslatedCRUDController<
	DTO extends CooperatorOwnedDTO,
	TDTO extends Translated<DTO>,
	LDTO extends CooperatorOwnedLangDTO<DTO>,
	E extends TranslatedCooperatorOwnedModel<L, E>,
	L extends CooperatorOwnedLang<L, E>, 
	SF extends APIFilteredTranslatedServiceFacade<DTO, TDTO, LDTO, E, L, F>,
	F extends EmptyModelFilter<F, E>
> extends ApiBaseController {

	public static final String ENDPOINT_ID = "/{id:\\d+}";

	/**
	 * Filter type
	 *
	 * @return the class
	 */
	@SuppressWarnings("unchecked")
	protected Class<F> filterType() {
		return ((Class<F>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[6]);
	}

	/**
	 * Default order specifier for this entity.
	 *
	 * @return the order specifier
	 */
	protected OrderSpecifier<?>[] defaultSort() {
		return null;
	}

	@Autowired
	protected ShortFilterService shortFilterService;

	@Autowired
	protected LanguageService languageService;
	
	@Autowired
	protected SF translatedApiService;

	@GetMapping(value = ENDPOINT_ID, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "get", description = "Get translated record by ID", summary = "Get")
	public TDTO get(@PathVariable("id") final long id) {
		return translatedApiService.loadTranslated(id);
	}

	/**
	 * Remove the entity.
	 *
	 * @param id the id
	 * @return the removed record
	 */
	@DeleteMapping(value = ENDPOINT_ID, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "remove", description = "Delete existing record by ID", summary = "Delete")
	public DTO remove(@PathVariable("id") final long id) {
		return translatedApiService.remove(translatedApiService.get(id));
	}

	/**
	 * Register a new entity.
	 *
	 * @param entity the site
	 * @return the recorded record
	 */
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "create", description = "Create a record with translation", summary = "Add")
	public TDTO create(@RequestBody @Valid @NotNull final TDTO entity) {
		return translatedApiService.loadTranslated(translatedApiService.createTranslated(entity).getEntity().getId());
	}

	/**
	 * Update the entity.
	 *
	 * @param entity entity with updates
	 * @return the updated record
	 */
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "update", description = "Update an existing record", summary = "Update")
	public DTO update(@RequestBody @Valid @NotNull final DTO entity) {
		return translatedApiService.get(translatedApiService.update(entity).getId());
	}

	/**
	 * Get filtered list of entities.
	 *
	 * @param page the page
	 * @param filter the filter
	 * @return the page
	 * @throws SearchException
	 */
	@PostMapping(value = FilteredCRUDController.ENDPOINT_LIST, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter", summary = "List by filter")
	public FilteredPage<TDTO, F> list(@ParameterObject final Pagination page, @RequestBody(required = false) final F filter) throws SearchException, IOException {

		F normalizedFilter = shortFilterService.normalizeFilter(filter, filterType());
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, translatedApiService.listFiltered(filter, pageable));
	}

	/**
	 * Gets the langs.
	 *
	 * @param entityId the source descriptor id
	 * @return the langs
	 */
	@GetMapping(value = "/{entityId}/langs", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId="getTranslations", description = "Get translations for all languages by entity id", summary = "List of translations")
	public List<LDTO> getTranslations(@PathVariable("entityId") final long entityId) {
		return translatedApiService.getLangs(entityId);
	}

	/**
	 * Removes the source descriptor lang.
	 *
	 * @param entityId the source descriptor id
	 * @param sysLangId the sys lang id
	 * @return the source descriptor lang
	 */
	@PutMapping(value = "/{entityId}/lang/{sysLangId}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "updateLang", description = "Insert or update translation by entity id and language", summary = "Update translation")
	public LDTO updateLang(@PathVariable("entityId") final long entityId, @PathVariable("sysLangId") final long sysLangId, @RequestBody @NotNull LDTO input) {
		return translatedApiService.upsert(translatedApiService.get(entityId), languageService.get(sysLangId), input);
	}

	/**
	 * Removes the source descriptor lang.
	 *
	 * @param entityId the source descriptor id
	 * @param sysLangId the sys lang id
	 * @return the source descriptor lang
	 */
	@DeleteMapping(value = "/{entityId}/lang/{sysLangId}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "deleteLang", description = "Delete translation by entity id and language", summary = "Delete translation")
	public LDTO removeLang(@PathVariable("entityId") final long entityId, @PathVariable("sysLangId") final long sysLangId) {
		return translatedApiService.remove(translatedApiService.get(entityId), languageService.get(sysLangId));
	}

	/**
	 * Remove many.
	 *
	 * @param deletes the entities to remove
	 * @return the {@link MultiOp} response
	 */
	@DeleteMapping(value = "/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "removeMany", description = "Delete existing records", summary = "Delete many")
	public MultiOp<DTO> removeMany(@RequestBody @Valid @NotNull final List<DTO> deletes) {
		return MultiOp.multiOp(deletes, translatedApiService::remove, translatedApiService::remove);
	}
}