InstituteController.java

/*
 * Copyright 2019 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.Map;

import javax.servlet.http.HttpServletResponse;

import org.genesys.blocks.model.JsonViews;
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.InstituteApiService;
import org.genesys.server.api.v1.model.FaoInstitute;
import org.genesys.server.component.aspect.DownloadEndpoint;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.service.DownloadService;
import org.genesys.server.service.GenesysService;
import org.genesys.server.service.ShortFilterService.FilterInfo;
import org.genesys.server.service.filter.AccessionFilter;
import org.genesys.server.service.filter.InstituteFilter;
import org.genesys.server.exception.SearchException;
import org.genesys.server.service.worker.ShortFilterProcessor;
import org.genesys.spring.CSVMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
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.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.google.common.collect.Sets;

import io.swagger.annotations.Api;

/**
 * Institute API v1
 */
@RestController("instituteApi1")
@PreAuthorize("isAuthenticated()")
@RequestMapping(InstituteController.CONTROLLER_URL)
@Api(tags = { "institute" })
public class InstituteController extends ApiBaseController {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL =  ApiBaseController.APIv1_BASE + "/wiews";

	private static final Logger LOG = LoggerFactory.getLogger(InstituteController.class);

	@Autowired
	private InstituteApiService instituteApiService;

	@Autowired
	private GenesysService genesysService;

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

	@Autowired
	private DownloadService downloadService;

	/**
	 * List institutes by filterCode or filter
	 *
	 * @param page the page
	 * @param filterCode short filter code
	 * @param filter the filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list", produces = { MediaType.APPLICATION_JSON_VALUE, CSVMessageConverter.TEXT_CSV_VALUE })
	@JsonView({ JsonViews.Public.class })
	public FilteredPage<FaoInstitute, InstituteFilter> list(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
			@RequestBody(required = false) InstituteFilter filter) throws IOException, SearchException {

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

	@JsonView({ JsonViews.Protected.class })
	@GetMapping(value ="/{code:[A-Z]+[0-9]+}", produces = MediaType.APPLICATION_JSON_VALUE)
	public FaoInstitute get(@PathVariable(value = "code") String code){
		return instituteApiService.findInstitute(code);
	}

	@GetMapping(value ="/{code:[A-Z]+[0-9]+}/details", produces = MediaType.APPLICATION_JSON_VALUE)
	public InstituteApiService.InstituteDetails details(@PathVariable(value = "code") String code) {
		return instituteApiService.details(code);
	}

	/**
	 * Gets the passport data coverage for the institute.
	 *
	 * @param code the institute WIEWS code
	 * @return the coverage
	 */
	@JsonView({ JsonViews.Protected.class })
	@GetMapping(value = "/{code:[A-Z]+[0-9]+}/coverage", produces = MediaType.APPLICATION_JSON_VALUE)
	@PreAuthorize("hasRole('USER')")
	public Map<String, Long> getCoverage(@PathVariable(value = "code") String code) {
		return instituteApiService.getCoverage(code);
	}

	@DownloadEndpoint
	@RequestMapping(value = "/{wiewsCode}/download", method = RequestMethod.POST, params = { "dwca" })
	public void downloadDwca(@PathVariable(value = "wiewsCode", required = true) String wiewsCode, HttpServletResponse response) throws Exception {
		final FaoInstitute faoInstitute = instituteApiService.getInstitute(wiewsCode);
		if (faoInstitute == null) {
			throw new NotFoundElement();
		}
		LOG.warn("Downloading DwC-A accessions of: {}", faoInstitute);

		// Create JSON filter
		final AccessionFilter filter = new AccessionFilter();
		filter.holder().code(Sets.newHashSet(faoInstitute.getCode()));

		// Write Darwin Core Archive to the stream.
		response.setContentType("application/zip");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"genesys-accessions-%1$s.zip\"", faoInstitute.getCode()));

		final OutputStream outputStream = response.getOutputStream();
		genesysService.writeAccessions(filter, outputStream, null, "/wiews/" + faoInstitute.getCode());
		response.flushBuffer();
	}

	@DownloadEndpoint
	@RequestMapping(value = "/{wiewsCode}/download", method = RequestMethod.POST, params = { "pdci" })
	public void downloadPdci(@PathVariable(value = "wiewsCode", required = true) String wiewsCode, HttpServletResponse response) throws IOException {
		final FaoInstitute faoInstitute = instituteApiService.getInstitute(wiewsCode);
		if (faoInstitute == null) {
			throw new NotFoundElement();
		}
		LOG.warn("Downloading PDCI for: {}", faoInstitute);

		// Create JSON filter
		final AccessionFilter filter = new AccessionFilter();
		filter.holder().code(Sets.newHashSet(faoInstitute.getCode()));

		// Write MCPD to the stream.
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"genesys-pdci-%1$s.xlsx\"", faoInstitute.getCode()));
		// response.flushBuffer();

		final OutputStream outputStream = response.getOutputStream();
		try {
			downloadService.writeXlsxPDCI(filter, outputStream, null, "/wiews/" + faoInstitute.getCode());
			response.flushBuffer();
		} catch (EOFException e) {
			LOG.warn("Download was aborted", e);
			throw e;
		}
	}

	@DownloadEndpoint
	@RequestMapping(value = "/{wiewsCode}/download", method = RequestMethod.POST, params = { "mcpd" })
	public void downloadMcpd(@PathVariable(value = "wiewsCode", required = true) String wiewsCode, HttpServletResponse response) throws IOException {
		final FaoInstitute faoInstitute = instituteApiService.getInstitute(wiewsCode);
		if (faoInstitute == null) {
			throw new NotFoundElement();
		}
		LOG.warn("Downloading MCPD accessions of: {}", faoInstitute);

		// Create JSON filter
		final AccessionFilter filter = new AccessionFilter();
		filter.holder().code(Sets.newHashSet(faoInstitute.getCode()));

		// Write MCPD to the stream.
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"genesys-accessions-%1$s.xlsx\"", faoInstitute.getCode()));
		// response.flushBuffer();

		final OutputStream outputStream = response.getOutputStream();
		try {
			downloadService.writeXlsxMCPD(filter, outputStream, null, "/wiews/" + faoInstitute.getCode());
			response.flushBuffer();
		} catch (EOFException e) {
			LOG.warn("Download was aborted", e);
			throw e;
		}
	}


	@DownloadEndpoint
	@RequestMapping(value = "/{wiewsCode}/download", method = RequestMethod.POST, params = { "auditlog" })
	public void downloadAuditLog(@PathVariable(value = "wiewsCode", required = true) String wiewsCode, HttpServletResponse response) throws IOException {
		instituteApiService.downloadAuditLog(wiewsCode, response);
	}

	
	@JsonView({JsonViews.Protected.class})
	@PostMapping(value = "/{code:[A-Z]+[0-9]+}/update")
	public FaoInstitute update(@PathVariable(value = "code") String code, @RequestBody FaoInstitute institute) {
		return instituteApiService.update(code, institute);
	}

//	/**
//	 * Update the article.
//	 *
//	 * @param article the article
//	 * @param className the className of article
//	 * @return the updated article
//	 */
//	@RequestMapping(value = "/{code:[A-Z]+[0-9]+}/update-article", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
//	public Article updateArticle(@PathVariable(value = "code") String code, @RequestBody final Article article) throws NotFoundElement, ClassNotFoundException, CRMException {
//		final FaoInstitute faoInstitute = instituteService.getInstitute(code);
//		if (faoInstitute == null) {
//			throw new NotFoundElement();
//		}
//		return instituteService.updateAbout(faoInstitute, article.getSummary(), article.getBody(), new Locale(article.getLang()));
//	}

}