CRUDController.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 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.api.v1.ApiBaseController;
import org.gringlobal.api.v1.MultiOp;
import org.gringlobal.api.v1.Pagination;
import org.gringlobal.api.v2.facade.APIServiceFacade;
import org.gringlobal.service.JasperReportService;
import org.gringlobal.service.ShortFilterService;
import org.springdoc.api.annotations.ParameterObject;
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;
/**
* A basic API controller for CRUD operations
*
* @param <E> the entity type
* @param <DTO> the entity DTO type
* @param <S> the CRUD service
*/
@Validated
public abstract class CRUDController<DTO, E extends EmptyModel, S extends APIServiceFacade<DTO, 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 serviceFacade;
@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 DTO get(@PathVariable("id") final long id) {
return serviceFacade.get(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 serviceFacade.remove(serviceFacade.get(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<DTO> removeMany(@RequestBody @Valid @NotNull final List<DTO> deletes) {
return serviceFacade.remove(deletes);
}
/**
* 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 DTO create(@RequestBody @Valid @NotNull final DTO entity) {
return serviceFacade.get(serviceFacade.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<DTO> createMany(@RequestBody @Valid @NotNull final List<DTO> inserts) {
return serviceFacade.create(inserts).map(serviceFacade::get);
}
/**
* 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 final DTO entity) {
return serviceFacade.get(serviceFacade.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<DTO> updateMany(@RequestBody @Valid @NotNull final List<DTO> updates) {
return serviceFacade.update(updates).map(serviceFacade::get);
}
/**
* 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<DTO> upsertMany(@RequestBody @Valid @NotNull final List<DTO> updates) {
return serviceFacade.upsertMany(updates).map(serviceFacade::get);
}
/**
* 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<DTO> 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 serviceFacade.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 = serviceFacade.getServiceEntityName();
Path path = Path.of(JasperReportService.REPORT_PATH, entityName).toAbsolutePath();
// Only .jrxml files
return repositoryService.getFiles(path, Sort.unsorted()).stream().filter(file -> ".jrxml".equalsIgnoreCase(file.getExtension())).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 serviceFacade.generateReport(reportTemplate, entityIds, targetLocale, response);
}
/**
* Default order specifier for this entity.
*
* @return the order specifier
*/
protected OrderSpecifier<?>[] defaultSort() {
return null;
}
}