FilteredCRUDController.java

/*
 * Copyright 2020 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 org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.EmptyModel;
import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.gringlobal.api.PageableAsQueryParam;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.service.FilteredCRUDService;
import org.gringlobal.service.ShortFilterService.FilterInfo;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;

/**
 * A basic API controller for CRUD operations with filtering
 *
 * @param <E> the entity type
 * @param <S> the CRUD service
 * @param <F> the generic type
 */
@Validated
public abstract class FilteredCRUDController<E extends EmptyModel, S extends FilteredCRUDService<E, F>, F extends EmptyModelFilter<F, E>> extends CRUDController<E, S> {

	public static final String ENDPOINT_FILTER = "/filter";
	protected static final int FILTER_GENERIC_INDEX = 2;

	/**
	 * Get filtered list of entities.
	 *
	 * @param page the page
	 * @param filter the filter
	 * @return the page
	 * @throws SearchException 
	 */
	@PostMapping(value = ENDPOINT_LIST, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter", summary = "List by filter")
	@PageableAsQueryParam
	public FilteredPage<E, F> list(@Parameter(hidden = true) 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<E, F> results = new FilteredPage<>(normalizedFilter, crudService.list(filter, pageable));
		return results;
	}


	/**
	 * Get filtered list of entities by filterCode or filter.
	 *
	 * @param page the page
	 * @param filterCode short filter code
	 * @param filter the filter
	 * @return the page
	 * @throws IOException
	 * @throws SearchException 
	 */
	@PostMapping(value = ENDPOINT_FILTER, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter or filter code", summary = "List by filter code or filter")
	@PageableAsQueryParam
	public FilteredPage<E, F> filter(@RequestParam(name = "f", required = false) String filterCode, @Parameter(hidden = true) final Pagination page,
			@RequestBody(required = false) F filter) throws IOException, SearchException {

		if (filterCode != null) {
			filter = shortFilterService.filterByCode(filterCode, filterType());
		} else {
			filterCode = shortFilterService.getCode(filter);
		}
		FilterInfo<F> filterInfo = shortFilterService.processFilter(filterCode, 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<E, F> results = new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, crudService.list(filterInfo.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]);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param entity the site
	 * @return the recorded record
	 */
	@Override
	public E create(@RequestBody E entity) {
		return super.create(entity);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param inserts multiple entities to insert
	 * @return the {@link MultiOp} response
	 */
	@Override
	public MultiOp<E> createMany(@RequestBody final List<E> inserts) {
		return super.createMany(inserts);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param entity the entity
	 * @return the updated record
	 */
	@Override
	public E update(@RequestBody E entity) {
		return super.update(entity);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param updates multiple entities with updates
	 * @return the {@link MultiOp} response
	 */
	@Override
	public MultiOp<E> updateMany(@RequestBody final List<E> updates) {
		return super.updateMany(updates);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param updates multiple entities to insert or update
	 * @return the {@link MultiOp} response
	 */
	@Override
	public MultiOp<E> upsertMany(@RequestBody final List<E> updates) {
		return super.upsertMany(updates);
	}

	/**
	 * Override to assist Jackson with type detection
	 *
	 * @param deletes records to delete
	 * @return the {@link MultiOp} result
	 */
	@Override
	public MultiOp<E> removeMany(@RequestBody final List<E> deletes) {
		return super.removeMany(deletes);
	}

}