DescriptorController.java

/*
 * Copyright 2018 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.genesys.server.api.v1;

import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.genesys.blocks.model.JsonViews;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.model.RepositoryImage;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.FilteredPage;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v1.facade.DescriptorApiService;
import org.genesys.server.api.v1.mapper.APIv1Mapper;
import org.genesys.server.api.v1.model.DatasetInfo;
import org.genesys.server.api.v1.model.Descriptor;
import org.genesys.server.api.v1.model.DescriptorListInfo;
import org.genesys.server.component.aspect.DownloadEndpoint;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.filters.DescriptorFilter;
import org.genesys.server.service.ShortFilterService.FilterInfo;
import org.genesys.server.exception.SearchException;
import org.genesys.server.service.worker.ShortFilterProcessor;
import org.genesys.server.service.worker.dupe.DescriptorDuplicateFinder;
import org.genesys.server.service.worker.dupe.DuplicateFinder;
import org.genesys.server.service.worker.dupe.DuplicateFinder.Hit;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.annotation.JsonView;

import io.swagger.annotations.Api;

/**
 * The Class DescriptorController.
 *
 * @author Matija Obreza
 * @author Maxym Borodenko
 * @author Alex Prendetskiy
 */
@RestController("descriptorApi1")
@RequestMapping(org.genesys.server.api.v1.DescriptorController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated()")
@Api(tags = { "descriptor" })
public class DescriptorController extends ApiBaseController {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/descriptor";
	public static final String IMAGE_URL = "/{uuid}/image";

	@Autowired
	private DescriptorApiService descriptorApiService;
	
	@Autowired
	private APIv1Mapper mapper;

	/** The short filter service. */
	@Autowired
	protected ShortFilterProcessor shortFilterProcessor;

	@Autowired
	private DescriptorDuplicateFinder duplicateFinder;

	/**
	 * Gets the descriptor.
	 *
	 * @param uuid the uuid
	 * @return the descriptor
	 */
	@RequestMapping(value = "/{uuid}", method = RequestMethod.GET)
	public Descriptor getDescriptor(@PathVariable("uuid") final UUID uuid) {
		return descriptorApiService.loadDescriptor(uuid);
	}

	/**
	 * Delete descriptor.
	 *
	 * @param uuid the uuid
	 * @param version the version
	 * @return the descriptor
	 * @throws IOException 
	 * @throws InvalidRepositoryPathException 
	 * @throws NotFoundElement 
	 */
	@DeleteMapping(value = "/{uuid},{version}")
	public Descriptor deleteDescriptor(@PathVariable("uuid") final UUID uuid, @PathVariable("version") final int version) throws NotFoundElement, InvalidRepositoryPathException, IOException {
		try {
			return descriptorApiService.removeDescriptor(descriptorApiService.loadDescriptor(uuid, version));
		} catch (DataIntegrityViolationException e) {
			throw new InvalidApiUsageException("Cannot delete a referenced descriptor");
		}
	}

	/**
	 * Loads descriptor by uuid and version and tries to publish it.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return published Descriptor (admin-only)
	 */
	@RequestMapping(value = "/approve", method = RequestMethod.POST)
	public Descriptor approveDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final Descriptor descriptor = descriptorApiService.loadDescriptor(uuid, version);
		return descriptorApiService.approveDescriptor(descriptor);
	}

	/**
	 * Loads descriptor by uuid and version and send to review.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return descriptor in review state
	 */
	@RequestMapping(value = "/for-review", method = RequestMethod.POST)
	public Descriptor reviewDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final Descriptor descriptor = descriptorApiService.loadDescriptor(uuid, version);
		return descriptorApiService.reviewDescriptor(descriptor);
	}

	/**
	 * Loads descriptor by uuid and version and unpublish it.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return unpublished descriptor
	 */
	@RequestMapping(value = "/reject", method = RequestMethod.POST)
	public Descriptor rejectDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final Descriptor descriptor = descriptorApiService.loadDescriptor(uuid, version);
		return descriptorApiService.rejectDescriptor(descriptor);
	}

	/**
	 * List categories.
	 *
	 * @return the category[]
	 */
	@GetMapping(value = "/categories")
	public org.genesys.server.model.traits.Descriptor.Category[] listCategories() {
		return org.genesys.server.model.traits.Descriptor.Category.values();
	}

	/**
	 * Make a new version of a descriptor.
	 *
	 * @param major make a new major version
	 * @param source the descriptor to copy
	 * @return the descriptor
	 */
	@RequestMapping(value = "/copy", method = RequestMethod.POST)
	public Descriptor copyDescriptor(@RequestParam(name = "major", defaultValue = "true", required = false) final boolean major, @RequestBody final Descriptor source) {
		return descriptorApiService.nextVersion(source, major);
	}

	/**
	 * Creates the descriptor.
	 *
	 * @param source the source
	 * @return the descriptor
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public Descriptor createDescriptor(@RequestBody final Descriptor source) {
		return descriptorApiService.create(source);
	}

	/**
	 * Update descriptor.
	 *
	 * @param source the source
	 * @return the descriptor
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Descriptor updateDescriptor(@RequestBody final Descriptor source) {
		return descriptorApiService.update(source);
	}

	/**
	 * Update descriptor.
	 *
	 * @param source the source
	 * @return the descriptor
	 */
	@RequestMapping(value = "/force-update", method = RequestMethod.POST)
	public Descriptor forceUpdateDescriptor(@RequestBody final Descriptor source) {
		return descriptorApiService.forceUpdateDescriptor(source);
	}

	/**
	 * Update descriptor.
	 *
	 * @param source the source
	 * @return the list
	 */
	@RequestMapping(value = "/upsert", method = RequestMethod.POST)
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public List<Descriptor> updateDescriptors(@RequestBody final List<Descriptor> source) {
		return descriptorApiService.upsertDescriptors(source);
	}

	@DownloadEndpoint
	@PostMapping(value = "/export", produces = { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
	public void exportDescriptors(@RequestParam(name = "f", required = false) String filterCode,
			@RequestBody(required = false) DescriptorFilter filter, HttpServletResponse response) throws IOException {

		var filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"genesys-descriptors-" + filterInfo.filterCode + ".xlsx\""));
		response.flushBuffer();

		// Write XLSX to the stream.
		final OutputStream outputStream = response.getOutputStream();

		try {
			descriptorApiService.exportDescriptors(filterInfo.filter, outputStream);
			response.flushBuffer();
		} catch (EOFException e) {
			LOG.warn("Download was aborted", e);
			throw e;
		}
	}

	/**
	 * List descriptors.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list")
	public FilteredPage<Descriptor, DescriptorFilter> listDescriptors(@RequestParam(name = "f", required = false) String filterCode, final Pagination page,
			@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, descriptorApiService.listDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * List descriptors details.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list/details")
	public FilteredPage<Descriptor, DescriptorFilter> listDescriptorsDetails(@RequestParam(name = "f", required = false) String filterCode, final Pagination page,
		@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, descriptorApiService.listDescriptorsDetails(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * List descriptors accessible to user
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list-accessible")
	public FilteredPage<Descriptor, DescriptorFilter> listAccessibleDescriptors(@RequestParam(name = "f", required = false) String filterCode, final Pagination page,
			@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, descriptorApiService.listAccessibleDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * My descriptors.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list-mine")
	public FilteredPage<Descriptor, DescriptorFilter> myDescriptors(@RequestParam(name = "f", required = false) String filterCode, final Pagination page,
			@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, descriptorApiService.listDescriptorsForCurrentUser(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.DESC, "lastModifiedDate")));
	}

	/**
	 * Filter descriptors by filter code.
	 *
	 * @param page the page
	 * @param filterCode the filter code
	 * @return the filtered page
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @deprecated Use {@link #listDescriptors(int, int, org.springframework.data.domain.Sort.Direction, String[], DescriptorFilter)}
	 */
	@Deprecated
	@PostMapping(value = "/list/{filterCode}")
	public FilteredPage<Descriptor, DescriptorFilter> listDescriptorsByShort(@ParameterObject final Pagination page, @PathVariable("filterCode") final String filterCode) throws IOException, SearchException {
		final DescriptorFilter filter = shortFilterProcessor.filterByCode(filterCode, DescriptorFilter.class);
		FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, descriptorApiService.listDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * Search matching descriptors.
	 *
	 * @param source the source
	 * @return matching descriptors
	 */
	@RequestMapping(value = "/search-matching", method = RequestMethod.POST)
	public List<Descriptor> searchMatchingDescriptor(@RequestBody final Descriptor source) {
		return descriptorApiService.searchMatchingDescriptor(source).stream().filter(d -> d != null).collect(Collectors.toList());
	}

	/**
	 * Get additional information about descriptor that is not provided in the
	 * {@link #getDescriptor(UUID)} call.
	 *
	 * @param uuid descriptor UUID
	 * @return the other descriptor info
	 */
	@RequestMapping(value = "/extra/{uuid}", method = RequestMethod.GET)
	@SuppressWarnings("unused")
	@JsonView(JsonViews.Minimal.class)
	public Object getOtherDescriptorInfo(@PathVariable("uuid") final UUID uuid) {
		final Descriptor descriptor = descriptorApiService.getDescriptor(uuid);

		return new Object() {
			public List<DescriptorListInfo> descriptorLists = descriptorApiService.getDescriptorLists(descriptor);
			public List<DatasetInfo> datasets = descriptorApiService.getDatasets(descriptor);
		};
	}

	@PostMapping(value = IMAGE_URL)
	public Descriptor updateImage(@PathVariable("uuid") final UUID descriptorUuid, @RequestPart(name = "image", required = true) final MultipartFile image,
			@RequestPart(name = "metadata", required = false) final RepositoryImage metadata) throws InvalidRepositoryPathException,
			InvalidRepositoryFileDataException, IOException, NotFoundElement, NoSuchRepositoryFileException {

		return descriptorApiService.updateImage(descriptorApiService.loadDescriptor(descriptorUuid), image, metadata);
	}

	@DeleteMapping(value = IMAGE_URL)
	public Descriptor removeImage(@PathVariable("uuid") final UUID descriptorUuid) throws NoSuchRepositoryFileException, IOException, NotFoundElement, InvalidRepositoryPathException {
		return descriptorApiService.removeImage(descriptorApiService.loadDescriptor(descriptorUuid));
	}

	@PostMapping(value = "/find-similar", produces = MediaType.APPLICATION_JSON_VALUE)
	public List<Hit<Descriptor>> findSimilar(@RequestBody SimilarRequest similarRequest) throws Exception {
		Descriptor target = similarRequest.select;
		if (target.getUuid() != null) {
			target = descriptorApiService.loadDescriptor(target.getUuid());
		}
		var result = duplicateFinder.findSimilar(mapper.map(target), similarRequest.target);
		return result.stream().map(hit -> {
			var dtoHit = new DuplicateFinder.Hit<>(mapper.map(hit.result), hit.score);
			dtoHit.hitRating = hit.hitRating;
			dtoHit.matches = hit.matches;
			return dtoHit;
		}).collect(Collectors.toList());
	}

	public static class SimilarRequest {
		public Descriptor select;
		public DescriptorFilter target;
	}
}