CRUDController.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.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.EmptyModel;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.model.RepositoryFile;
import org.genesys.filerepository.service.RepositoryService;
import org.gringlobal.service.CRUDService;
import org.gringlobal.service.JasperReportService;
import org.gringlobal.service.ShortFilterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import com.querydsl.core.types.OrderSpecifier;

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

/**
 * A basic API controller for CRUD operations
 *
 * @param <E> the entity type
 * @param <S> the CRUD service
 */
@Validated
public abstract class CRUDController<E extends EmptyModel, S extends CRUDService<E>> extends ApiBaseController {

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

	@Autowired
	protected ShortFilterService shortFilterService;

	@Autowired
	protected S crudService;

	@Autowired
	protected RepositoryService repositoryService;

	public CRUDController() {
		super();
	}

	/**
	 * 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 record by ID", summary = "Get")
	public E get(@PathVariable("id") final long id) {
		return crudService.load(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 crudService.remove(crudService.load(id));
	}

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

	/**
	 * 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", summary = "Add")
	public E create(@RequestBody @Valid @NotNull final E entity) {
		return crudService.load(crudService.create(entity).getId());
	}

	/**
	 * Register a new entity.
	 *
	 * @param inserts multiple entities to insert
	 * @return the {@link MultiOp} response
	 */
	@PostMapping(value = "/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "createMany", description = "Create multiple records", summary = "Add multiple")
	public MultiOp<E> createMany(@RequestBody @Valid @NotNull final List<E> inserts) {
		return MultiOp.multiOp(inserts, crudService::create, crudService::create);
	}

	/**
	 * 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 final E entity) {
		return crudService.load(crudService.update(entity).getId());
	}

	/**
	 * Update the entity.
	 *
	 * @param updates multiple entities with updates
	 * @return the {@link MultiOp} response
	 */
	@PutMapping(value = "/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "updateMany", description = "Update an existing record", summary = "Update")
	public MultiOp<E> updateMany(@RequestBody @Valid @NotNull final List<E> updates) {
		return MultiOp.multiOp(updates, crudService::update, crudService::update);
	}

	/**
	 * Insert new or update existing the records.
	 *
	 * @param updates multiple entities to insert or updates
	 * @return the {@link MultiOp} response
	 */
	@PutMapping(value = "/upsert", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "upsertMany", description = "Insert new or update existing records", summary = "Insert or update")
	public MultiOp<E> upsertMany(@RequestBody @Valid @NotNull final List<E> updates) {
		return MultiOp.upsert(updates, crudService::create, crudService::update);
	}

	/**
	 * Get list of entities.
	 *
	 * @param page the page
	 * @return the page
	 */
	@GetMapping(value = ENDPOINT_LIST, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records", summary = "List")
	public Page<E> list(@ParameterObject final Pagination page) {
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return crudService.list(pageable);
	}

	/**
	 * Get list of report templates for entity.
	 *
	 * @return the list of report templates
	 */
	@GetMapping(value = "/report/list", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records", summary = "List of templates")
	public List<RepositoryFile> getReportList() throws InvalidRepositoryPathException {
		String entityName = crudService.getServiceEntityName();
		Path path = Path.of(JasperReportService.REPORT_PATH, entityName).toAbsolutePath();
		// Only .jrxml files
		return repositoryService.getFiles(path, Sort.unsorted()).stream().filter(file -> file.getExtension().equalsIgnoreCase(".jrxml")).collect(Collectors.toList());
	}

	/**
	 * Generate report from template for entities.
	 */
	@PostMapping(value = "/report/generate/{reportTemplate}")
	@Operation(description = "Generate report by template", summary = "Generate PDF")
	public ResponseEntity<StreamingResponseBody> generateReport(@PathVariable String reportTemplate, @RequestBody Set<Long> entityIds, HttpServletResponse response) throws Exception {
		Locale targetLocale = LocaleContextHolder.getLocale();
		return crudService.generateReport(reportTemplate, entityIds, targetLocale, response);
	}

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

}