Commit 2a0b2c22 authored by Alexander Dolzhenko's avatar Alexander Dolzhenko
Browse files

add rest controllers for oauth

parent 531e204f
/**
* 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.servlet.controller.rest;
import com.hazelcast.core.DistributedObject;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.monitor.LocalMapStats;
import org.genesys2.server.service.MappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
@Controller("restCacheController")
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/api/v0/cache", "/json/v0/cache" })
public class CacheController extends RestController {
@Autowired
private MappingService mappingService;
@Autowired
private CacheManager cacheManager;
@RequestMapping(value = "", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Object cacheStats() {
List<CacheStats> cacheMaps = new ArrayList<>();
List<Object> cacheOther = new ArrayList<>();
HashMap<String, Object> response = new HashMap<>();
Set<HazelcastInstance> instances = Hazelcast.getAllHazelcastInstances();
for (HazelcastInstance hz : instances) {
if (LOG.isDebugEnabled())
LOG.debug("\n\nCache stats Instance: " + hz.getName());
for (DistributedObject o : hz.getDistributedObjects()) {
if (o instanceof IMap) {
IMap imap = (IMap) o;
cacheMaps.add(new CacheStats(imap));
} else {
// cacheOther.add(o); //todo, error when transforming to json
LOG.info(o.getClass() + " " + o);
}
}
}
response.put("cacheMaps", cacheMaps);
response.put("cacheOther", cacheOther);
return response;
}
@RequestMapping( value = "/clearTilesCache", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody Object clearTilesCache() {
final Cache tileServerCache = cacheManager.getCache("tileserver");
System.err.println("tileServerCache=" + tileServerCache.getNativeCache());
@SuppressWarnings("rawtypes")
final IMap hazelCache = (IMap) tileServerCache.getNativeCache();
LOG.info("Tiles cache size=" + hazelCache.size());
int count = 0;
for (final Object key : hazelCache.keySet()) {
LOG.info("\tkey=" + key);
if (++count > 20) {
break;
}
}
mappingService.clearCache();
LOG.info("Tiles cache size=" + hazelCache.size());
return JSON_OK;
}
@RequestMapping(method = RequestMethod.POST, value = "/clearCaches")
public @ResponseBody Object 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 {
private String serviceName;
private String name;
private LocalMapStats mapStats;
public CacheStats(IMap<?, ?> imap) {
this.serviceName = imap.getServiceName();
this.name = imap.getName();
this.mapStats = imap.getLocalMapStats();
}
public String getServiceName() {
return serviceName;
}
public String getName() {
return name;
}
public LocalMapStats getMapStats() {
return mapStats;
}
}
}
/**
* 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.servlet.controller.rest;
import org.apache.commons.lang.StringUtils;
import org.genesys2.server.exception.NotUniqueUserException;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.OAuth2ClientDetailsService;
import org.genesys2.server.service.UserService;
import org.genesys2.server.servlet.controller.rest.model.UserChangedDataJson;
import org.genesys2.server.servlet.model.UserList;
import org.genesys2.spring.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
@Controller("restUsersController")
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = {"/api/v0/users", "/json/v0/users"})
public class UsersController extends RestController {
@Value("${base.url}")
private String baseUrl;
@Autowired
protected UserService userService;
@Autowired
private OAuth2ClientDetailsService clientDetailsService;
@RequestMapping(value = "", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
@PreAuthorize("hasRole('ADMINISTRATOR')")
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
@PreAuthorize("hasRole('ADMINISTRATOR')")
public Object getAvailableRoles() throws UserException {
return userService.listAvailableRoles();
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
@PreAuthorize("hasRole('ADMINISTRATOR')")
public Object getUser(@PathVariable Long id) throws UserException {
return userService.getUserById(id);
}
@RequestMapping(value = "/user", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public void saveUser(@RequestBody @Validated User user) throws UserException {
userService.addUser(user);
}
@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public void updateUser(@RequestBody @Validated User user) throws UserException {
try {
userService.updateUser(user);
} catch (final DataIntegrityViolationException e) { // for some reasons it's
// not caught in service
throw new NotUniqueUserException(e, user.getEmail());
}
}
@RequestMapping(value = "/user/data", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
@PreAuthorize("hasRole('ADMINISTRATOR')")
public String updateData(@RequestBody UserChangedDataJson userData) {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
userService.updateData(user.getId(), userData.getName(), userData.getEmail());
if (StringUtils.isNotBlank(userData.getPwd1())) {
if (userData.getPwd1().equals(userData.getPwd2())) {
try {
LOG.info("Updating password for " + user);
userService.updatePassword(user.getId(), userData.getPwd1());
LOG.warn("Password updated for " + user);
} catch (final UserException e) {
LOG.error(e.getMessage(), e);
}
} else {
LOG.warn("Passwords didn't match for " + user);
}
}
return JSON_OK;
}
@RequestMapping(value = "/user/roles", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
@PreAuthorize("hasRole('ADMINISTRATOR')")
public String updateRoles(@RequestBody UserChangedDataJson userData) {
final User user = userService.getUserByUuid(userData.getUuid());
if (user == null) {
throw new ResourceNotFoundException();
}
userService.updateRoles(user, Arrays.asList(userData.getRoles()));
return JSON_OK;
}
@RequestMapping(value = "/user",
/* method = RequestMethod.DELETE) */
// only GET, POST, PUT allowed
method = RequestMethod.POST)
@PreAuthorize("hasRole('ADMINISTRATOR')")
@ResponseBody
public void removeUser(@RequestParam("id") Long userId) throws UserException {
userService.removeUserById(userId);
}
}
package org.genesys2.server.servlet.controller.rest.model;
public class UserChangedDataJson {
private String uuid;
private String name;
private String email;
private String pwd1;
private String pwd2;
private String[] roles;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPwd1() {
return pwd1;
}
public void setPwd1(String pwd1) {
this.pwd1 = pwd1;
}
public String getPwd2() {
return pwd2;
}
public void setPwd2(String pwd2) {
this.pwd2 = pwd2;
}
public String[] getRoles() {
return roles;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
}
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