NetworkController.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.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.genesys.blocks.model.JsonViews;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v1.mapper.APIv1Mapper;
import org.genesys.server.api.v1.model.Article;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.impl.FaoInstitute;
import org.genesys.server.model.impl.PGRFANetwork;
import org.genesys.server.service.CRMException;
import org.genesys.server.service.ContentService;
import org.genesys.server.service.ElasticsearchService;
import org.genesys.server.service.PGRFANetworkService;
import org.springdoc.api.annotations.ParameterObject;
import org.genesys.server.exception.SearchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.PutMapping;
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 io.swagger.annotations.Api;

@RestController("networkApi1")
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = { NetworkController.CONTROLLER_URL, "/json/v1/network" })
@Api(tags = { "network" })
public class NetworkController extends ApiBaseController {

	// Rest controller base URL
	public static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/network";

	@Autowired
	private PGRFANetworkService networkService;

	@Autowired
	private ContentService contentService;

	@Autowired
	private APIv1Mapper apiV1Mapper;

	/**
	 * List organizations
	 *
	 * @return
	 */
	@GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	public List<PGRFANetwork> listNetworks(@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
		return networkService.list(PageRequest.of(page - 1, 50)).getContent();
	}

	/**
	 * Create or update network
	 *
	 * @return
	 */
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	public PGRFANetwork updateNetwork(@RequestBody @Valid PGRFANetwork organizationJson) {
		PGRFANetwork network = networkService.getNetwork(organizationJson.getSlug());
		if (network == null) {
			return networkService.create(organizationJson.getSlug(), organizationJson.getTitle());
		}

		if (!network.getId().equals(organizationJson.getId())) {
			throw new InvalidApiUsageException("Cannot overwrite existing record");
		}
		return networkService.update(network.getId(), network.getSlug(), organizationJson.getTitle(), organizationJson.getAccessionFilter());
	}

	/**
	 * Get network
	 *
	 * @return
	 */
	@GetMapping(value = "/{shortName}", produces = { MediaType.APPLICATION_JSON_VALUE })
	public PGRFANetwork getNetwork(@PathVariable("shortName") String shortName) {
		PGRFANetwork network = networkService.getNetwork(shortName);
		if (network == null)
			throw new NotFoundElement("Network not found");
		return network;
	}

	/**
	 * Get network details
	 *
	 * @return
	 */
	@GetMapping(value = "/{shortName}/details", produces = { MediaType.APPLICATION_JSON_VALUE })
	public NetworkDetails getNetworkDetails(@PathVariable("shortName") String shortName, @RequestParam(value = "language", defaultValue = "en") String language) throws SearchException {
		PGRFANetwork network = networkService.getNetwork(shortName);
		if (network == null) {
			throw new NotFoundElement("Network not found");
		}
		Page<FaoInstitute> members = networkService.getInstitutes(network, PageRequest.of(0, 50, Sort.Direction.DESC, "accessionCount"));
		var blurb = networkService.getBlurb(network, new Locale(language));
		Map<String, ElasticsearchService.TermResult> overview =  networkService.overview(network.getSlug());

		return NetworkDetails.from(network, apiV1Mapper.map(blurb), members, overview);
	}

	/**
	 * Get network blurb
	 *
	 * @return
	 */
	@GetMapping(value = "/{shortName}/blurb/{language}", produces = { MediaType.APPLICATION_JSON_VALUE })
	public Article getBlurb(@PathVariable("shortName") String shortName, @PathVariable("language") String language) {
		PGRFANetwork network = networkService.getNetwork(shortName);
		if (network == null) {
			throw new NotFoundElement("Network not found");
		}
		return apiV1Mapper.map(networkService.getBlurb(network, new Locale(language)));
	}

	/**
	 * Update blurb
	 *
	 */
	@PutMapping(value = "/{shortName}/blurb", produces = { MediaType.APPLICATION_JSON_VALUE })
	public Article updateBlurb(@PathVariable("shortName") String shortName, @RequestBody Article blurb) throws CRMException {
		PGRFANetwork network = networkService.getNetwork(shortName);
		if (network == null) {
			throw new NotFoundElement("Network not found");
		}
		return contentService.updateArticle(network, ContentService.ENTITY_BLURB_SLUG, blurb.getTitle(), blurb.getSummary(), blurb.getBody(), new Locale(blurb.getLang()));
	}

	/**
	 * Get network details
	 *
	 * @return
	 */
	@DeleteMapping(value = "/{shortName}", produces = { MediaType.APPLICATION_JSON_VALUE })
	public PGRFANetwork deleteNetwork(@PathVariable("shortName") String shortName) {
		return networkService.delete(networkService.getNetwork(shortName));
	}

	/**
	 * Get network institutes' codes
	 *
	 * @return
	 */
	@GetMapping(value = "/{shortName}/institutes/codes", produces = { MediaType.APPLICATION_JSON_VALUE })
	public Set<String> getNetworkInstitutesCodes(@PathVariable("shortName") String shortName) {
		PGRFANetwork org = networkService.getNetwork(shortName);
		return networkService.getInstitutes(org).stream().map(FaoInstitute::getCode).collect(Collectors.toSet());
	}

	/**
	 * Get network details
	 *
	 * @return
	 */
	@GetMapping(value = "/{shortName}/institutes", produces = { MediaType.APPLICATION_JSON_VALUE })
	public Page<FaoInstitute> getNetworkInstitutes(@PathVariable("shortName") String shortName, @ParameterObject final Pagination page) {
		PGRFANetwork org = networkService.getNetwork(shortName);
		return networkService.getInstitutes(org, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.DESC, "accessionCount"));
	}

	/**
	 * Add Institutes to Network
	 *
	 * @return
	 */
	@RequestMapping(value = "/{slug}/add-institutes", method = { RequestMethod.POST, RequestMethod.PUT }, produces = { MediaType.APPLICATION_JSON_VALUE })
	public PGRFANetwork addNetworkInstitutes(@PathVariable(value = "slug") String slug, @RequestBody List<String> instituteList) {
		final PGRFANetwork network = networkService.getNetwork(slug);
		if (network == null) {
			throw new NotFoundElement("Network cannot be found");
		}

		return networkService.addInstitutes(network, instituteList);
	}

	/**
	 * Set Institutes of Network
	 *
	 * @return
	 */
	@RequestMapping(value = "/{slug}/set-institutes", method = { RequestMethod.POST, RequestMethod.PUT }, produces = { MediaType.APPLICATION_JSON_VALUE })
	public PGRFANetwork setNetworkInstitutes(@PathVariable(value = "slug") String slug, @RequestBody List<String> instituteList) {
		final PGRFANetwork network = networkService.getNetwork(slug);
		if (network == null) {
			throw new NotFoundElement();
		}

		return networkService.setInstitutes(network, instituteList);
	}

	public static class NetworkDetails {
		public PGRFANetwork network;
		public Article blurb;
		public Page<FaoInstitute> institutes;

		@JsonView({ JsonViews.Public.class })
		public Map<String, ElasticsearchService.TermResult> overview;


		public static NetworkDetails from(PGRFANetwork network, Article blurb, Page<FaoInstitute> institutes, Map<String, ElasticsearchService.TermResult> overview) {
			NetworkDetails details = new NetworkDetails();
			details.network = network;
			details.blurb = blurb;
			details.institutes = institutes;
			details.overview = overview;

			return details;
		}
	}
}