Commit a635b561 authored by Matija Obreza's avatar Matija Obreza
Browse files

Deleted ApiResult, return boolean or throw exception instead

parent b941993f
......@@ -24,8 +24,6 @@ import org.springframework.beans.factory.annotation.Value;
public abstract class ApiBaseController {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
protected static final ApiResult JSON_OK = new ApiResult(true);
public static final String APIv0_BASE = "/api/v0";
public static final String APIv0_ADMIN_BASE = APIv0_BASE + "/admin";
......
/*
* 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;
}
}
......@@ -85,7 +85,7 @@ public class CacheController extends ApiBaseController {
@RequestMapping(value = "/clearTilesCache", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
@PreAuthorize("hasRole('ADMINISTRATOR')")
public @ResponseBody Object clearTilesCache() {
public void clearTilesCache() {
final Cache tileServerCache = cacheManager.getCache("tileserver");
System.err.println("tileServerCache=" + tileServerCache.getNativeCache());
......@@ -102,19 +102,16 @@ public class CacheController extends ApiBaseController {
}
mappingService.clearCache();
LOG.info("Tiles cache size={}", hazelCache.size());
return JSON_OK;
}
@RequestMapping(method = RequestMethod.POST, value = "/clearCaches", produces = { MediaType.APPLICATION_JSON_VALUE })
@PreAuthorize("hasRole('ADMINISTRATOR')")
public @ResponseBody Object clearCaches() {
public void clearCaches() {
for (String cacheName : cacheManager.getCacheNames()) {
final Cache cache = cacheManager.getCache(cacheName);
LOG.info("Clearing cache {}", cacheName);
cache.clear();
}
return JSON_OK;
}
public static final class CacheStats {
......
......@@ -21,7 +21,6 @@ import java.util.List;
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.OAuth2Cleanup;
import org.genesys2.server.exception.AuthorizationException;
......@@ -206,9 +205,8 @@ public class CropsController extends ApiBaseController {
* @throws AuthorizationException
*/
@RequestMapping(value = "/rebuild", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody ApiResult rebuild() {
public void rebuild() {
cropService.rebuildTaxonomies();
return JSON_OK;
}
/**
......@@ -218,14 +216,13 @@ public class CropsController extends ApiBaseController {
* @throws AuthorizationException
*/
@RequestMapping(value = "{shortName}/rebuild", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody ApiResult rebuildCrop(@PathVariable("shortName") String shortName) {
public void rebuildCrop(@PathVariable("shortName") String shortName) {
LOG.info("Updating crop rules for {}", shortName);
final Crop crop = cropService.getCrop(shortName);
if (crop == null)
throw new ResourceNotFoundException("No crop " + shortName);
cropService.rebuildTaxonomies(crop);
return JSON_OK;
}
}
......@@ -137,11 +137,9 @@ public class MeController extends ApiBaseController {
}
@RequestMapping(value = "/teams/{teamId}/leave", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
Object leaveTeam(@PathVariable("teamId") Long teamId) {
public void leaveTeam(@PathVariable("teamId") Long teamId) {
LOG.info("Leaving team {}", teamId);
teamService.removeMe(teamId);
return JSON_OK;
}
public static class TeamJson {
......
......@@ -25,7 +25,6 @@ import org.genesys.blocks.security.model.AclObjectIdentity;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.security.service.CustomAclService;
import org.genesys2.server.api.ApiBaseController;
import org.genesys2.server.api.ApiResult;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.UserService;
import org.genesys2.server.servlet.model.PermissionJson;
......@@ -60,7 +59,7 @@ public class PermissionController extends ApiBaseController {
private OAuthClientDetailsService clientDetailsService;
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ApiResult addPermission(@RequestBody PermissionJson permissionJson) {
public void addPermission(@RequestBody PermissionJson permissionJson) {
LOG.info("Adding permission {}", permissionJson);
final AclObjectIdentity oid = aclService.ensureObjectIdentity(permissionJson.getOid(), permissionJson.getClazz());
......@@ -72,12 +71,10 @@ public class PermissionController extends ApiBaseController {
final AclSid sid = aclService.getSid(permissionJson.getSid());
aclService.setPermissions(oid, sid, permissionJson);
}
return JSON_OK;
}
@RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ApiResult updatePermissions(@RequestBody PermissionJson permissionJson) {
public void updatePermissions(@RequestBody PermissionJson permissionJson) {
final AclObjectIdentity objectIdentity = aclService.ensureObjectIdentity(permissionJson.getOid(), permissionJson.getClazz());
if (permissionJson.getAuthority() != null) {
......@@ -88,8 +85,6 @@ public class PermissionController extends ApiBaseController {
final AclSid sid = aclService.getSid(permissionJson.getSid());
aclService.setPermissions(objectIdentity, sid, permissionJson);
}
return JSON_OK;
}
@RequestMapping(value = "/autocompleteuser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
......
......@@ -25,7 +25,6 @@ import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.api.ApiBaseController;
import org.genesys2.server.api.ApiResult;
import org.genesys2.server.api.model.UserChangedDataJson;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.EMailVerificationService;
......@@ -47,136 +46,120 @@ import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
@RestController("userApi0")
@PreAuthorize("isAuthenticated() && hasRole('ADMINISTRATOR')")
@RequestMapping(value = {UsersController.CONTROLLER_URL, "/json/v0/users"})
@RequestMapping(value = { UsersController.CONTROLLER_URL, "/json/v0/users" })
@Api(tags = { "user" })
public class UsersController extends ApiBaseController {
// Rest controller base URL
protected static final String CONTROLLER_URL = ApiBaseController.APIv0_BASE + "/users";
@Value("${base.url}")
private String baseUrl;
@Autowired
protected UserService userService;
@Autowired
private EMailVerificationService emailVerificationService;
@Autowired
private TeamService teamService;
@RequestMapping(value = "", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public Object getUsers(@RequestParam(value = "startRow", required = false, defaultValue = "0") Integer startRow,
@RequestParam(value = "pageSize", required = false, defaultValue = "0") Integer pageSize) throws UserException {
return new UserList(userService.listWrapped(startRow, pageSize));
}
@RequestMapping(value = "/available_roles", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public Object getAvailableRoles() throws UserException {
return userService.listAvailableRoles();
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public Object getUser(@PathVariable Long id) throws UserException {
Map <String, Object> resultMap = new HashMap<>();
User user = userService.getUser(id);
resultMap.put("user", user);
resultMap.put("userTeams", teamService.listUserTeams(user));
return resultMap;
}
@RequestMapping(value = "/user/uuid/{id:.+}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public Object getUserByUuid(@PathVariable String id) throws UserException {
return userService.getUserByUuid(id);
}
@RequestMapping(value = "/user/data", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ApiResult updateData(@RequestBody UserChangedDataJson userData) throws PasswordPolicyException, UserException {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
try {
userService.updateUser(user, userData.getEmail(), userData.getName());
} catch (NotUniqueUserException e) {
LOG.warn("User with e-mail address {} already exists", e.getEmail());
throw e;
}
if (StringUtils.isNotBlank(userData.getPwd1())) {
if (userData.getPwd1().equals(userData.getPwd2())) {
try {
LOG.info("Updating password for {}", user);
userService.changePassword(user, userData.getPwd1());
LOG.warn("Password updated for {}", user);
} catch (PasswordPolicyException e) {
LOG.error(e.getMessage());
throw e;
}
} else {
LOG.warn("Passwords didn't match for {}", user);
}
}
@Value("${base.url}")
private String baseUrl;
@Autowired
protected UserService userService;
@Autowired
private EMailVerificationService emailVerificationService;
@Autowired
private TeamService teamService;
@RequestMapping(value = "", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Object getUsers(@RequestParam(value = "startRow", required = false, defaultValue = "0") Integer startRow,
@RequestParam(value = "pageSize", required = false, defaultValue = "0") Integer pageSize) throws UserException {
return new UserList(userService.listWrapped(startRow, pageSize));
}
@RequestMapping(value = "/available_roles", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Object getAvailableRoles() throws UserException {
return userService.listAvailableRoles();
}
return JSON_OK;
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Object getUser(@PathVariable Long id) throws UserException {
Map<String, Object> resultMap = new HashMap<>();
User user = userService.getUser(id);
resultMap.put("user", user);
resultMap.put("userTeams", teamService.listUserTeams(user));
return resultMap;
}
@RequestMapping(value = "/user/roles", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ApiResult updateRoles(@RequestBody UserChangedDataJson userData) {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
@RequestMapping(value = "/user/uuid/{id:.+}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Object getUserByUuid(@PathVariable String id) throws UserException {
return userService.getUserByUuid(id);
}
userService.setRoles(user, userData.getRoles());
return JSON_OK;
}
@RequestMapping(value = "/user/data", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
public void updateData(@RequestBody UserChangedDataJson userData) throws PasswordPolicyException, UserException {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
try {
userService.updateUser(user, userData.getEmail(), userData.getName());
} catch (NotUniqueUserException e) {
LOG.warn("User with e-mail address {} already exists", e.getEmail());
throw e;
}
if (StringUtils.isNotBlank(userData.getPwd1())) {
if (userData.getPwd1().equals(userData.getPwd2())) {
try {
LOG.info("Updating password for {}", user);
userService.changePassword(user, userData.getPwd1());
LOG.warn("Password updated for {}", user);
} catch (PasswordPolicyException e) {
LOG.error(e.getMessage());
throw e;
}
} else {
LOG.warn("Passwords didn't match for {}", user);
}
}
}
@RequestMapping(value = "/user/{uuid:.+}/send", method = RequestMethod.GET)
@ResponseBody
public ApiResult sendEmail(@PathVariable("uuid") String uuid) {
@RequestMapping(value = "/user/roles", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
public void updateRoles(@RequestBody UserChangedDataJson userData) {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
final User user = userService.getUserByUuid(uuid);
emailVerificationService.sendVerificationEmail(user);
userService.setRoles(user, userData.getRoles());
}
return JSON_OK;
}
@RequestMapping(value = "/user/{uuid:.+}/send", method = RequestMethod.GET)
public void sendEmail(@PathVariable("uuid") String uuid) {
@RequestMapping("/user/{uuid:.+}/vetted-user")
@ResponseBody
public ApiResult addRoleVettedUser(@PathVariable("uuid") String uuid) {
userService.addVettedUserRole(uuid);
return JSON_OK;
}
final User user = userService.getUserByUuid(uuid);
emailVerificationService.sendVerificationEmail(user);
}
@RequestMapping("/user/{uuid:.+}/vetted-user")
public void addRoleVettedUser(@PathVariable("uuid") String uuid) {
userService.addVettedUserRole(uuid);
}
@PreAuthorize("hasRole('ADMINISTRATOR')")
@RequestMapping(value = "/user/{uuid}/locked", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
boolean changeLock(@PathVariable("uuid") String uuid, @RequestBody boolean locked) throws NoUserFoundException {
User user = userService.getUserByUuid(uuid);
public void changeLock(@PathVariable("uuid") String uuid, @RequestBody boolean locked) throws NoUserFoundException {
User user = userService.getUserByUuid(uuid);
userService.setAccountLock(user.getId(), locked);
return true;
}
@PreAuthorize("hasRole('ADMINISTRATOR')")
@RequestMapping(value = "/user/{uuid}/enabled", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
boolean changeEnabled(@PathVariable("uuid") String uuid, @RequestBody boolean enabled) {
public void changeEnabled(@PathVariable("uuid") String uuid, @RequestBody boolean enabled) {
userService.setAccountActive(uuid, enabled);
return true;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment