Commit 533e54c3 authored by Matija Obreza's avatar Matija Obreza

API classes refactored

- extend ApiBaseController to free @RestController import
parent c215e1be
/*
* 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.catalog.api.v0;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.genesys.catalog.model.vocab.VocabularyTerm;
import org.genesys.catalog.service.VocabularyService;
import org.genesys.catalog.service.worker.ISO639VocabularyUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* The Class LanguagesController.
*
* @author Maxym Borodenko
*/
@RestController
@RequestMapping(LanguagesController.API_BASE)
@PreAuthorize("isAuthenticated()")
public class LanguagesController {
/** The Constant API_BASE. */
protected static final String API_BASE = "/api/v0/lang";
/** The Constant ISO639_3. */
public static final UUID ISO639_3 = ISO639VocabularyUpdater.ISO639_3;
private static final Logger LOG = LoggerFactory.getLogger(LanguagesController.class);
@Autowired
private ISO639VocabularyUpdater iso639VocabularyUpdater;
@Autowired
private VocabularyService vocabularyService;
/**
* Update languages.
*
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
@PreAuthorize("hasRole('ADMINISTRATOR')")
@PostMapping(value = "/update")
public @ResponseBody String updateLanguages() throws IOException {
LOG.info("Updating ISO language codes");
vocabularyService.autoUpdateOrCreateVocabulary(ISO639_3, iso639VocabularyUpdater.getISO639Vocabulary());
return "OK";
}
/**
* Gets the.
*
* @param code the code
* @return the vocabulary term
*/
@GetMapping(value = "/{code}", produces = MediaType.APPLICATION_JSON_VALUE)
public VocabularyTerm get(@PathVariable("code") final String code) {
return vocabularyService.getVocabularyTerm(ISO639_3, code);
}
/**
* Autocomplete.
*
* @param text the text
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
@GetMapping(value = "/autocomplete", produces = MediaType.APPLICATION_JSON_VALUE)
public List<VocabularyTerm> autocomplete(@RequestParam("l") final String text) throws IOException {
if (text.length() < 3) {
return Collections.emptyList();
}
return vocabularyService.autocompleteTerms(ISO639_3, text);
}
}
/*
* 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.catalog.api.v0;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.genesys.catalog.model.vocab.VocabularyTerm;
import org.genesys.catalog.service.VocabularyService;
import org.genesys.catalog.service.worker.WiewsVocabularyUpdater;
import org.genesys2.server.model.impl.FaoInstitute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* The Class WiewsController.
*
* TODO Use {@link FaoInstitute} here?
*
* @author Maxym Borodenko
*/
@RestController("wiewsApi0")
@RequestMapping(WiewsController.API_BASE)
@PreAuthorize("isAuthenticated()")
public class WiewsController {
/** The Constant API_BASE. */
public static final String API_BASE = "/api/v0/wiews";
/** The Constant FAO_WIEWS_UUID. */
public static final UUID FAO_WIEWS_UUID = WiewsVocabularyUpdater.FAO_WIEWS_UUID;
private static final Logger LOG = LoggerFactory.getLogger(WiewsController.class);
@Autowired
private VocabularyService vocabularyService;
@Autowired
private WiewsVocabularyUpdater wiewsVocabularyUpdater;
/**
* Update languages.
*
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
@PreAuthorize("hasRole('ADMINISTRATOR')")
@PostMapping(value = "/update")
public @ResponseBody String updateLanguages() throws IOException {
LOG.info("Updating FAO WIEWS codes");
vocabularyService.autoUpdateOrCreateVocabulary(FAO_WIEWS_UUID, wiewsVocabularyUpdater.getWiewsVocabulary());
return "OK";
}
/**
* Gets the.
*
* @param code the code
* @return the vocabulary term
*/
@GetMapping(value = "/{code}", produces = MediaType.APPLICATION_JSON_VALUE)
public VocabularyTerm get(@PathVariable("code") final String code) {
return vocabularyService.getVocabularyTerm(FAO_WIEWS_UUID, code);
}
/**
* Autocomplete.
*
* @param text the text
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
@GetMapping(value = "/autocomplete", produces = MediaType.APPLICATION_JSON_VALUE)
public List<VocabularyTerm> autocomplete(@RequestParam("term") final String text) throws IOException {
if (text.length() < 3) {
return Collections.emptyList();
}
return vocabularyService.autocompleteTerms(FAO_WIEWS_UUID, text);
}
}
/**
* Copyright 2014 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.genesys2.server.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
/// Base class for API controllers
public abstract class ApiBaseController {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
protected static final ApiResult JSON_OK = new ApiResult(true);
@Value("${paginator.api.maxPageSize}")
protected int maxPageSize;
public ApiBaseController() {
super();
}
public void setMaxPageSize(int maxPageSize) {
this.maxPageSize = maxPageSize;
}
}
/*
* 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.genesys2.server.api;
/**
* Used sometimes
*/
public class ApiResult {
public boolean result = false;
public ApiResult(boolean b) {
result = b;
}
}
/**
* Copyright 2014 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.genesys2.server.api;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.genesys2.server.exception.NotFoundElement;
import org.genesys2.server.service.impl.RESTApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
public abstract class RestController {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
protected static final ApiResult JSON_OK = new ApiResult(true);
@Value("${paginator.api.maxPageSize}")
protected int maxPageSize;
public static class ApiResult {
public boolean result = false;
public ApiResult(boolean b) {
result=b;
}
}
public RestController() {
super();
}
public void setMaxPageSize(int maxPageSize) {
this.maxPageSize = maxPageSize;
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ExceptionJson handleIOException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException {
LOG.error(ex.getMessage(), ex);
response.setStatus(400); // ?
return new ExceptionJson(ex);
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public ExceptionJson handleAccessDeniedException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LOG.warn("{} {} for {}", request.getRequestURI(), ex.getMessage(), (authentication != null ? ((UserDetails) authentication.getPrincipal()).getUsername() : "null"));
response.setStatus(404); // ?
return new ExceptionJson(ex);
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
public ExceptionJson handleHttpRequestMethodNotSupportedException(Exception ex, HttpServletRequest request, HttpServletResponse response)
throws IOException {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LOG.warn("{} {} for {}", request.getRequestURI(), ex.getMessage(), (authentication != null ? ((UserDetails) authentication.getPrincipal()).getUsername() : "null"));
response.setStatus(400); // ?
return new ExceptionJson(ex);
}
@ExceptionHandler(RESTApiException.class)
@ResponseBody
public ExceptionJson handleRESTApiException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LOG.warn("{} {} for {}", request.getRequestURI(), ex.getMessage(), (authentication != null ? ((UserDetails) authentication.getPrincipal()).getUsername() : "null"));
response.setStatus(400); // ?
return new ExceptionJson(ex);
}
@ResponseStatus(code = HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundElement.class)
@ResponseBody
public ExceptionJson handleNotFound(final Exception e, final HttpServletRequest request) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LOG.warn("{} {} for {}", request.getRequestURI(), e.getMessage(), (authentication != null ? ((UserDetails) authentication.getPrincipal()).getUsername() : "null"));
return new ExceptionJson(e);
}
}
...@@ -26,8 +26,8 @@ import javax.persistence.RollbackException; ...@@ -26,8 +26,8 @@ import javax.persistence.RollbackException;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.genesys2.server.api.ApiBaseController;
import org.genesys2.server.api.PleaseRetryException; import org.genesys2.server.api.PleaseRetryException;
import org.genesys2.server.api.RestController;
import org.genesys2.server.api.model.AccessionHeaderJson; import org.genesys2.server.api.model.AccessionHeaderJson;
import org.genesys2.server.exception.InvalidApiUsageException; import org.genesys2.server.exception.InvalidApiUsageException;
import org.genesys2.server.model.elastic.AccessionDetails; import org.genesys2.server.model.elastic.AccessionDetails;
...@@ -59,7 +59,6 @@ import org.springframework.data.domain.PageRequest; ...@@ -59,7 +59,6 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionException;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
...@@ -68,6 +67,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -68,6 +67,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
...@@ -75,10 +75,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; ...@@ -75,10 +75,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
@Controller("restAccessionController") @RestController("accessionApi0")
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/api/v0/acn", "/json/v0/acn" }) @RequestMapping(value = { "/api/v0/acn", "/json/v0/acn" })
public class AccessionController extends RestController { public class AccessionController extends ApiBaseController {
private static final int UPLOAD_RETRIES = 10; private static final int UPLOAD_RETRIES = 10;
private final ObjectMapper mapper = new ObjectMapper(); private final ObjectMapper mapper = new ObjectMapper();
......
...@@ -21,7 +21,7 @@ import java.util.HashMap; ...@@ -21,7 +21,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.genesys2.server.api.RestController; import org.genesys2.server.api.ApiBaseController;
import org.genesys2.server.service.MappingService; import org.genesys2.server.service.MappingService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
...@@ -42,7 +42,7 @@ import com.hazelcast.monitor.LocalMapStats; ...@@ -42,7 +42,7 @@ import com.hazelcast.monitor.LocalMapStats;
@Controller("restCacheController") @Controller("restCacheController")
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/api/v0/cache", "/json/v0/cache" }) @RequestMapping(value = { "/api/v0/cache", "/json/v0/cache" })
public class CacheController extends RestController { public class CacheController extends ApiBaseController {
@Autowired @Autowired
private MappingService mappingService; private MappingService mappingService;
......
...@@ -20,9 +20,10 @@ import java.util.List; ...@@ -20,9 +20,10 @@ import java.util.List;
import javax.xml.bind.ValidationException; import javax.xml.bind.ValidationException;
import org.genesys2.server.api.ApiBaseController;
import org.genesys2.server.api.ApiResult;
import org.genesys2.server.api.ModelValidationException; import org.genesys2.server.api.ModelValidationException;
import org.genesys2.server.api.OAuth2Cleanup; import org.genesys2.server.api.OAuth2Cleanup;
import org.genesys2.server.api.RestController;
import org.genesys2.server.exception.AuthorizationException; import org.genesys2.server.exception.AuthorizationException;
import org.genesys2.server.model.genesys.Parameter; import org.genesys2.server.model.genesys.Parameter;
import org.genesys2.server.model.impl.Crop; import org.genesys2.server.model.impl.Crop;
...@@ -38,20 +39,20 @@ import org.springframework.data.domain.Page; ...@@ -38,20 +39,20 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import net.sf.oval.ConstraintViolation; import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator; import net.sf.oval.Validator;
@Controller @RestController("cropApi0")
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/api/v0/crops", "/json/v0/crops" }) @RequestMapping(value = { "/api/v0/crops", "/json/v0/crops" })
public class CropsController extends RestController { public class CropsController extends ApiBaseController {
@Autowired @Autowired
GenesysService genesysService; GenesysService genesysService;
......
...@@ -27,16 +27,9 @@ import java.util.Map.Entry; ...@@ -27,16 +27,9 @@ import java.util.Map.Entry;
import javax.xml.bind.ValidationException; import javax.xml.bind.ValidationException;
import net.sf.oval.ConstraintViolation; import org.genesys2.server.api.ApiBaseController;
import net.sf.oval.Validator;
import net.sf.oval.constraint.MaxLength;
import net.sf.oval.constraint.MinLength;
import net.sf.oval.constraint.NotBlank;
import net.sf.oval.constraint.NotNull;
import org.genesys2.server.api.ModelValidationException; import org.genesys2.server.api.ModelValidationException;
import org.genesys2.server.api.OAuth2Cleanup; import org.genesys2.server.api.OAuth2Cleanup;
import org.genesys2.server.api.RestController;
import org.genesys2.server.exception.AuthorizationException; import org.genesys2.server.exception.AuthorizationException;
import org.genesys2.server.model.genesys.Accession; import org.genesys2.server.model.genesys.Accession;
import org.genesys2.server.model.genesys.Metadata; import org.genesys2.server.model.genesys.Metadata;
...@@ -54,20 +47,26 @@ import org.genesys2.spring.ResourceNotFoundException; ...@@ -54,20 +47,26 @@ import org.genesys2.spring.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller("restDatasetController") import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.constraint.MaxLength;
import net.sf.oval.constraint.MinLength;
import net.sf.oval.constraint.NotBlank;
import net.sf.oval.constraint.NotNull;
@RestController("datasetApi0")
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/api/v0/datasets", "/json/v0/datasets" }) @RequestMapping(value = { "/api/v0/datasets", "/json/v0/datasets" })
public class DatasetController extends RestController { public class DatasetController extends ApiBaseController {