TranslatedCRUDController.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.api.v1;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.CooperatorOwnedLang;
import org.gringlobal.model.TranslatedCooperatorOwnedModel;
import org.gringlobal.service.FilteredTranslatedCRUDService;
import org.gringlobal.service.LanguageService;
import org.gringlobal.service.ShortFilterService;
import org.gringlobal.service.TranslationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
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 com.querydsl.core.types.OrderSpecifier;

import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.api.annotations.ParameterObject;

/**
 * A base controller for CRUD operations for entities with `xxxLang` translations.
 * 
 * @param <E> the entity type
 * @param <T> the translated entity model
 * @param <L> the entityLang type
 * @param <S> the CRUD service
 * @param <F> the entityFilter type
 */
@Validated
public abstract class TranslatedCRUDController<E extends TranslatedCooperatorOwnedModel<L, E>, T extends TranslationService.Translation<E, L>, L extends CooperatorOwnedLang<L, E>, S extends FilteredTranslatedCRUDService<E, L, T, F>, F extends EmptyModelFilter<F, E>> extends ApiBaseController {

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

	@Autowired
	protected ShortFilterService shortFilterService;

	@Autowired
	protected LanguageService languageService;

	@Autowired
	protected S translatedCrudService;

	/**
	 * Get entity by id
	 *
	 * @param id the id
	 * @return the loaded record
	 */
	@GetMapping(value = ENDPOINT_ID, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "get", description = "Get translated record by ID", summary = "Get")
	public T get(@PathVariable("id") final long id) {
		return translatedCrudService.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 E remove(@PathVariable("id") final long id) {
		return translatedCrudService.remove(translatedCrudService.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 T create(@RequestBody @Valid @NotNull final T entity) {
		return translatedCrudService.reload(translatedCrudService.create(entity));
	}

	/**
	 * 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 E update(@RequestBody @Valid @NotNull final E entity) {
		return translatedCrudService.load(translatedCrudService.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<T, 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);
		FilteredPage<T, F> results = new FilteredPage<>(normalizedFilter, translatedCrudService.listFiltered(filter, pageable));
		return results;
	}

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

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

	/**
	 * Gets the langs.
	 *
	 * @param entityId the source descriptor id
	 * @return the langs
	 */
	@GetMapping(value = "/{entityId}/langs", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId="listLang", description = "Get translations for all languages by entity id", summary = "List of translations")
	public List<L> getLangs(@PathVariable("entityId") final long entityId) {
		return translatedCrudService.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 L updateLang(@PathVariable("entityId") final long entityId, @PathVariable("sysLangId") final long sysLangId, @RequestBody @NotNull L input) {
		return translatedCrudService.upsert(translatedCrudService.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 L removeLang(@PathVariable("entityId") final long entityId, @PathVariable("sysLangId") final long sysLangId) {
		return translatedCrudService.remove(translatedCrudService.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<E> removeMany(@RequestBody @Valid @NotNull final List<E> deletes) {
		return MultiOp.multiOp(deletes, translatedCrudService::remove, translatedCrudService::remove);
	}
}