Commit 118dd0eb authored by kezhenxu94's avatar kezhenxu94 Committed by Jason Song

Cleanup for 1.3.0 (#1969)

* replace some guava API with new Java 1.7 native API
* replace Collections.sort with List.sort(Java 1.7)
* replace annonymous inner types with lambdas
* use try-with-resources where possible
* replace explicit types with diamond operators
parent 72d32a56
...@@ -390,7 +390,7 @@ public class ReleaseService { ...@@ -390,7 +390,7 @@ public class ReleaseService {
private Map<String, String> getNamespaceItems(Namespace namespace) { private Map<String, String> getNamespaceItems(Namespace namespace) {
List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId()); List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId());
Map<String, String> configurations = new HashMap<String, String>(); Map<String, String> configurations = new HashMap<>();
for (Item item : items) { for (Item item : items) {
if (StringUtils.isEmpty(item.getKey())) { if (StringUtils.isEmpty(item.getKey())) {
continue; continue;
......
...@@ -66,7 +66,7 @@ public class YamlParser { ...@@ -66,7 +66,7 @@ public class YamlParser {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, Object> asMap(Object object) { private Map<String, Object> asMap(Object object) {
// YAML can have numbers as keys // YAML can have numbers as keys
Map<String, Object> result = new LinkedHashMap<String, Object>(); Map<String, Object> result = new LinkedHashMap<>();
if (!(object instanceof Map)) { if (!(object instanceof Map)) {
// A document can be a text literal // A document can be a text literal
result.put("document", object); result.put("document", object);
...@@ -102,7 +102,7 @@ public class YamlParser { ...@@ -102,7 +102,7 @@ public class YamlParser {
} }
private Map<String, Object> getFlattenedMap(Map<String, Object> source) { private Map<String, Object> getFlattenedMap(Map<String, Object> source) {
Map<String, Object> result = new LinkedHashMap<String, Object>(); Map<String, Object> result = new LinkedHashMap<>();
buildFlattenedMap(result, source, null); buildFlattenedMap(result, source, null);
return result; return result;
} }
......
...@@ -446,14 +446,8 @@ public class ConfigIntegrationTest extends BaseIntegrationTest { ...@@ -446,14 +446,8 @@ public class ConfigIntegrationTest extends BaseIntegrationTest {
private File createLocalCachePropertyFile(Properties properties) throws IOException { private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(configDir, assembleLocalCacheFileName()); File file = new File(configDir, assembleLocalCacheFileName());
FileOutputStream in = null; try (FileOutputStream in = new FileOutputStream(file)) {
try {
in = new FileOutputStream(file);
properties.store(in, "Persisted by ConfigIntegrationTest"); properties.store(in, "Persisted by ConfigIntegrationTest");
} finally {
if (in != null) {
in.close();
}
} }
return file; return file;
} }
......
...@@ -25,7 +25,7 @@ public class BeanUtils { ...@@ -25,7 +25,7 @@ public class BeanUtils {
* List<UserDTO> userDTOs = BeanUtil.batchTransform(UserDTO.class, userBeans); * List<UserDTO> userDTOs = BeanUtil.batchTransform(UserDTO.class, userBeans);
* </pre> * </pre>
*/ */
public static <T> List<T> batchTransform(final Class<T> clazz, List<? extends Object> srcList) { public static <T> List<T> batchTransform(final Class<T> clazz, List<?> srcList) {
if (CollectionUtils.isEmpty(srcList)) { if (CollectionUtils.isEmpty(srcList)) {
return Collections.emptyList(); return Collections.emptyList();
} }
...@@ -49,7 +49,7 @@ public class BeanUtils { ...@@ -49,7 +49,7 @@ public class BeanUtils {
if (src == null) { if (src == null) {
return null; return null;
} }
T instance = null; T instance;
try { try {
instance = clazz.newInstance(); instance = clazz.newInstance();
} catch (Exception e) { } catch (Exception e) {
...@@ -63,7 +63,7 @@ public class BeanUtils { ...@@ -63,7 +63,7 @@ public class BeanUtils {
final BeanWrapper src = new BeanWrapperImpl(source); final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors(); PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>(); Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor pd : pds) { for (PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName()); Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName()); if (srcValue == null) emptyNames.add(pd.getName());
...@@ -83,13 +83,13 @@ public class BeanUtils { ...@@ -83,13 +83,13 @@ public class BeanUtils {
* @param key 属性名 * @param key 属性名
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <K, V> Map<K, V> mapByKey(String key, List<? extends Object> list) { public static <K, V> Map<K, V> mapByKey(String key, List<?> list) {
Map<K, V> map = new HashMap<K, V>(); Map<K, V> map = new HashMap<>();
if (CollectionUtils.isEmpty(list)) { if (CollectionUtils.isEmpty(list)) {
return map; return map;
} }
try { try {
Class<? extends Object> clazz = list.get(0).getClass(); Class<?> clazz = list.get(0).getClass();
Field field = deepFindField(clazz, key); Field field = deepFindField(clazz, key);
if (field == null) throw new IllegalArgumentException("Could not find the key"); if (field == null) throw new IllegalArgumentException("Could not find the key");
field.setAccessible(true); field.setAccessible(true);
...@@ -111,21 +111,19 @@ public class BeanUtils { ...@@ -111,21 +111,19 @@ public class BeanUtils {
* </pre> * </pre>
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <K, V> Map<K, List<V>> aggByKeyToList(String key, List<? extends Object> list) { public static <K, V> Map<K, List<V>> aggByKeyToList(String key, List<?> list) {
Map<K, List<V>> map = new HashMap<K, List<V>>(); Map<K, List<V>> map = new HashMap<>();
if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list
return map; return map;
} }
try { try {
Class<? extends Object> clazz = list.get(0).getClass(); Class<?> clazz = list.get(0).getClass();
Field field = deepFindField(clazz, key); Field field = deepFindField(clazz, key);
if (field == null) throw new IllegalArgumentException("Could not find the key"); if (field == null) throw new IllegalArgumentException("Could not find the key");
field.setAccessible(true); field.setAccessible(true);
for (Object o : list) { for (Object o : list) {
K k = (K) field.get(o); K k = (K) field.get(o);
if (map.get(k) == null) { map.computeIfAbsent(k, k1 -> new ArrayList<>());
map.put(k, new ArrayList<V>());
}
map.get(k).add((V) o); map.get(k).add((V) o);
} }
} catch (Exception e) { } catch (Exception e) {
...@@ -143,13 +141,13 @@ public class BeanUtils { ...@@ -143,13 +141,13 @@ public class BeanUtils {
* </pre> * </pre>
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <K> Set<K> toPropertySet(String key, List<? extends Object> list) { public static <K> Set<K> toPropertySet(String key, List<?> list) {
Set<K> set = new HashSet<K>(); Set<K> set = new HashSet<>();
if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list if (CollectionUtils.isEmpty(list)) {// 防止外面传入空list
return set; return set;
} }
try { try {
Class<? extends Object> clazz = list.get(0).getClass(); Class<?> clazz = list.get(0).getClass();
Field field = deepFindField(clazz, key); Field field = deepFindField(clazz, key);
if (field == null) throw new IllegalArgumentException("Could not find the key"); if (field == null) throw new IllegalArgumentException("Could not find the key");
field.setAccessible(true); field.setAccessible(true);
...@@ -163,7 +161,7 @@ public class BeanUtils { ...@@ -163,7 +161,7 @@ public class BeanUtils {
} }
private static Field deepFindField(Class<? extends Object> clazz, String key) { private static Field deepFindField(Class<?> clazz, String key) {
Field field = null; Field field = null;
while (!clazz.getName().equals(Object.class.getName())) { while (!clazz.getName().equals(Object.class.getName())) {
try { try {
......
...@@ -14,7 +14,6 @@ import com.ctrip.framework.apollo.core.ConfigConsts; ...@@ -14,7 +14,6 @@ import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.Tracer;
import com.google.common.base.Function;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
...@@ -45,6 +44,7 @@ import java.util.Set; ...@@ -45,6 +44,7 @@ import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
......
...@@ -5,7 +5,6 @@ import com.ctrip.framework.apollo.configservice.service.AppNamespaceServiceWithC ...@@ -5,7 +5,6 @@ import com.ctrip.framework.apollo.configservice.service.AppNamespaceServiceWithC
import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.ConfigConsts;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
...@@ -15,6 +14,7 @@ import java.util.Collections; ...@@ -15,6 +14,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -137,6 +137,6 @@ public class WatchKeysUtil { ...@@ -137,6 +137,6 @@ public class WatchKeysUtil {
return Collections.emptySet(); return Collections.emptySet();
} }
return FluentIterable.from(appNamespaces).transform(AppNamespace::getName).toSet(); return appNamespaces.stream().map(AppNamespace::getName).collect(Collectors.toSet());
} }
} }
...@@ -17,6 +17,14 @@ public class ServiceController { ...@@ -17,6 +17,14 @@ public class ServiceController {
private final DiscoveryService discoveryService; private final DiscoveryService discoveryService;
private static Function<InstanceInfo, ServiceDTO> instanceInfoToServiceDTOFunc = instance -> {
ServiceDTO service = new ServiceDTO();
service.setAppName(instance.getAppName());
service.setInstanceId(instance.getInstanceId());
service.setHomepageUrl(instance.getHomePageUrl());
return service;
};
public ServiceController(final DiscoveryService discoveryService) { public ServiceController(final DiscoveryService discoveryService) {
this.discoveryService = discoveryService; this.discoveryService = discoveryService;
} }
...@@ -25,7 +33,7 @@ public class ServiceController { ...@@ -25,7 +33,7 @@ public class ServiceController {
@RequestMapping("/meta") @RequestMapping("/meta")
public List<ServiceDTO> getMetaService() { public List<ServiceDTO> getMetaService() {
List<InstanceInfo> instances = discoveryService.getMetaServiceInstances(); List<InstanceInfo> instances = discoveryService.getMetaServiceInstances();
List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); List<ServiceDTO> result = instances.stream().map(instanceInfoToServiceDTOFunc).collect(Collectors.toList());
return result; return result;
} }
...@@ -34,26 +42,14 @@ public class ServiceController { ...@@ -34,26 +42,14 @@ public class ServiceController {
@RequestParam(value = "appId", defaultValue = "") String appId, @RequestParam(value = "appId", defaultValue = "") String appId,
@RequestParam(value = "ip", required = false) String clientIp) { @RequestParam(value = "ip", required = false) String clientIp) {
List<InstanceInfo> instances = discoveryService.getConfigServiceInstances(); List<InstanceInfo> instances = discoveryService.getConfigServiceInstances();
List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); List<ServiceDTO> result = instances.stream().map(instanceInfoToServiceDTOFunc).collect(Collectors.toList());
return result; return result;
} }
@RequestMapping("/admin") @RequestMapping("/admin")
public List<ServiceDTO> getAdminService() { public List<ServiceDTO> getAdminService() {
List<InstanceInfo> instances = discoveryService.getAdminServiceInstances(); List<InstanceInfo> instances = discoveryService.getAdminServiceInstances();
List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); List<ServiceDTO> result = instances.stream().map(instanceInfoToServiceDTOFunc).collect(Collectors.toList());
return result; return result;
} }
private static Function<InstanceInfo, ServiceDTO> InstanceInfo_To_ServiceDTO_Func = new Function<InstanceInfo, ServiceDTO>() {
@Override
public ServiceDTO apply(InstanceInfo instance) {
ServiceDTO service = new ServiceDTO();
service.setAppName(instance.getAppName());
service.setInstanceId(instance.getInstanceId());
service.setHomepageUrl(instance.getHomePageUrl());
return service;
}
};
} }
...@@ -244,8 +244,8 @@ public class AppNamespaceServiceWithCacheTest { ...@@ -244,8 +244,8 @@ public class AppNamespaceServiceWithCacheTest {
} }
private void check(List<AppNamespace> someList, List<AppNamespace> anotherList) { private void check(List<AppNamespace> someList, List<AppNamespace> anotherList) {
Collections.sort(someList, appNamespaceComparator); someList.sort(appNamespaceComparator);
Collections.sort(anotherList, appNamespaceComparator); anotherList.sort(appNamespaceComparator);
assertEquals(someList, anotherList); assertEquals(someList, anotherList);
} }
......
...@@ -33,8 +33,8 @@ public class ApolloThreadFactory implements ThreadFactory { ...@@ -33,8 +33,8 @@ public class ApolloThreadFactory implements ThreadFactory {
ThreadGroup group = getThreadGroup(); ThreadGroup group = getThreadGroup();
Thread[] activeThreads = new Thread[group.activeCount()]; Thread[] activeThreads = new Thread[group.activeCount()];
group.enumerate(activeThreads); group.enumerate(activeThreads);
Set<Thread> alives = new HashSet<Thread>(Arrays.asList(activeThreads)); Set<Thread> alives = new HashSet<>(Arrays.asList(activeThreads));
Set<Thread> dies = new HashSet<Thread>(); Set<Thread> dies = new HashSet<>();
log.info("Current ACTIVE thread count is: {}", alives.size()); log.info("Current ACTIVE thread count is: {}", alives.size());
long expire = System.currentTimeMillis() + timeoutInMillis; long expire = System.currentTimeMillis() + timeoutInMillis;
while (System.currentTimeMillis() < expire) { while (System.currentTimeMillis() < expire) {
......
...@@ -8,7 +8,7 @@ import java.util.List; ...@@ -8,7 +8,7 @@ import java.util.List;
public class DNSUtil { public class DNSUtil {
public static List<String> resolve(String domainName) throws UnknownHostException { public static List<String> resolve(String domainName) throws UnknownHostException {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
InetAddress[] addresses = InetAddress.getAllByName(domainName); InetAddress[] addresses = InetAddress.getAllByName(domainName);
if (addresses != null) { if (addresses != null) {
......
...@@ -13,8 +13,7 @@ import org.slf4j.LoggerFactory; ...@@ -13,8 +13,7 @@ import org.slf4j.LoggerFactory;
public class DefaultProviderManager implements ProviderManager { public class DefaultProviderManager implements ProviderManager {
private static final Logger logger = LoggerFactory.getLogger(DefaultProviderManager.class); private static final Logger logger = LoggerFactory.getLogger(DefaultProviderManager.class);
private Map<Class<? extends Provider>, Provider> m_providers = private Map<Class<? extends Provider>, Provider> m_providers = new LinkedHashMap<>();
new LinkedHashMap<Class<? extends Provider>, Provider>();
public DefaultProviderManager() { public DefaultProviderManager() {
// Load per-application configuration, like app id, from classpath://META-INF/app.properties // Load per-application configuration, like app id, from classpath://META-INF/app.properties
......
...@@ -99,7 +99,7 @@ public enum NetworkInterfaceManager { ...@@ -99,7 +99,7 @@ public enum NetworkInterfaceManager {
try { try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
List<NetworkInterface> nis = interfaces == null ? Collections.<NetworkInterface>emptyList() : Collections.list(interfaces); List<NetworkInterface> nis = interfaces == null ? Collections.<NetworkInterface>emptyList() : Collections.list(interfaces);
List<InetAddress> addresses = new ArrayList<InetAddress>(); List<InetAddress> addresses = new ArrayList<>();
InetAddress local = null; InetAddress local = null;
try { try {
......
...@@ -6,12 +6,12 @@ import com.ctrip.framework.apollo.portal.entity.po.Permission; ...@@ -6,12 +6,12 @@ import com.ctrip.framework.apollo.portal.entity.po.Permission;
import com.ctrip.framework.apollo.portal.entity.po.RolePermission; import com.ctrip.framework.apollo.portal.entity.po.RolePermission;
import com.ctrip.framework.apollo.portal.repository.PermissionRepository; import com.ctrip.framework.apollo.portal.repository.PermissionRepository;
import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository; import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository;
import com.google.common.collect.FluentIterable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -47,7 +47,7 @@ public class ConsumerRolePermissionService { ...@@ -47,7 +47,7 @@ public class ConsumerRolePermissionService {
} }
Set<Long> roleIds = Set<Long> roleIds =
FluentIterable.from(consumerRoles).transform(ConsumerRole::getRoleId).toSet(); consumerRoles.stream().map(ConsumerRole::getRoleId).collect(Collectors.toSet());
List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds); List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds);
if (CollectionUtils.isEmpty(rolePermissions)) { if (CollectionUtils.isEmpty(rolePermissions)) {
return false; return false;
......
...@@ -40,7 +40,7 @@ public class PropertyResolver implements ConfigTextResolver { ...@@ -40,7 +40,7 @@ public class PropertyResolver implements ConfigTextResolver {
} }
ItemChangeSets changeSets = new ItemChangeSets(); ItemChangeSets changeSets = new ItemChangeSets();
Map<Integer, String> newLineNumMapItem = new HashMap<Integer, String>();//use for delete blank and comment item Map<Integer, String> newLineNumMapItem = new HashMap<>();//use for delete blank and comment item
int lineCounter = 1; int lineCounter = 1;
for (String newItem : newItems) { for (String newItem : newItems) {
newItem = newItem.trim(); newItem = newItem.trim();
......
...@@ -117,7 +117,7 @@ public class ItemController { ...@@ -117,7 +117,7 @@ public class ItemController {
List<ItemDTO> items = configService.findItems(appId, Env.valueOf(env), clusterName, namespaceName); List<ItemDTO> items = configService.findItems(appId, Env.valueOf(env), clusterName, namespaceName);
if ("lastModifiedTime".equals(orderBy)) { if ("lastModifiedTime".equals(orderBy)) {
Collections.sort(items, (o1, o2) -> { items.sort((o1, o2) -> {
if (o1.getDataChangeLastModifiedTime().after(o2.getDataChangeLastModifiedTime())) { if (o1.getDataChangeLastModifiedTime().after(o2.getDataChangeLastModifiedTime())) {
return -1; return -1;
} }
......
...@@ -13,7 +13,6 @@ import com.ctrip.framework.apollo.portal.service.RoleInitializationService; ...@@ -13,7 +13,6 @@ import com.ctrip.framework.apollo.portal.service.RoleInitializationService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService; import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.util.RoleUtils; import com.ctrip.framework.apollo.portal.util.RoleUtils;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -22,6 +21,7 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -22,6 +21,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* Created by timothy on 2017/4/26. * Created by timothy on 2017/4/26.
...@@ -109,9 +109,8 @@ public class DefaultRoleInitializationService implements RoleInitializationServi ...@@ -109,9 +109,8 @@ public class DefaultRoleInitializationService implements RoleInitializationServi
private void createAppMasterRole(String appId, String operator) { private void createAppMasterRole(String appId, String operator) {
Set<Permission> appPermissions = Set<Permission> appPermissions =
FluentIterable.from(Lists.newArrayList( Stream.of(PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE)
PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE)) .map(permissionType -> createPermission(appId, permissionType, operator)).collect(Collectors.toSet());
.transform(permissionType -> createPermission(appId, permissionType, operator)).toSet();
Set<Permission> createdAppPermissions = rolePermissionService.createPermissions(appPermissions); Set<Permission> createdAppPermissions = rolePermissionService.createPermissions(appPermissions);
Set<Long> Set<Long>
appPermissionIds = appPermissionIds =
......
...@@ -13,7 +13,6 @@ import com.ctrip.framework.apollo.portal.repository.RoleRepository; ...@@ -13,7 +13,6 @@ import com.ctrip.framework.apollo.portal.repository.RoleRepository;
import com.ctrip.framework.apollo.portal.repository.UserRoleRepository; import com.ctrip.framework.apollo.portal.repository.UserRoleRepository;
import com.ctrip.framework.apollo.portal.service.RolePermissionService; import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
...@@ -28,6 +27,7 @@ import java.util.Date; ...@@ -28,6 +27,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/** /**
* Created by timothy on 2017/4/26. * Created by timothy on 2017/4/26.
...@@ -57,15 +57,14 @@ public class DefaultRolePermissionService implements RolePermissionService { ...@@ -57,15 +57,14 @@ public class DefaultRolePermissionService implements RolePermissionService {
Role createdRole = roleRepository.save(role); Role createdRole = roleRepository.save(role);
if (!CollectionUtils.isEmpty(permissionIds)) { if (!CollectionUtils.isEmpty(permissionIds)) {
Iterable<RolePermission> rolePermissions = FluentIterable.from(permissionIds).transform( Iterable<RolePermission> rolePermissions = permissionIds.stream().map(permissionId -> {
permissionId -> {
RolePermission rolePermission = new RolePermission(); RolePermission rolePermission = new RolePermission();
rolePermission.setRoleId(createdRole.getId()); rolePermission.setRoleId(createdRole.getId());
rolePermission.setPermissionId(permissionId); rolePermission.setPermissionId(permissionId);
rolePermission.setDataChangeCreatedBy(createdRole.getDataChangeCreatedBy()); rolePermission.setDataChangeCreatedBy(createdRole.getDataChangeCreatedBy());
rolePermission.setDataChangeLastModifiedBy(createdRole.getDataChangeLastModifiedBy()); rolePermission.setDataChangeLastModifiedBy(createdRole.getDataChangeLastModifiedBy());
return rolePermission; return rolePermission;
}); }).collect(Collectors.toList());
rolePermissionRepository.saveAll(rolePermissions); rolePermissionRepository.saveAll(rolePermissions);
} }
...@@ -90,14 +89,14 @@ public class DefaultRolePermissionService implements RolePermissionService { ...@@ -90,14 +89,14 @@ public class DefaultRolePermissionService implements RolePermissionService {
Set<String> toAssignUserIds = Sets.difference(userIds, existedUserIds); Set<String> toAssignUserIds = Sets.difference(userIds, existedUserIds);
Iterable<UserRole> toCreate = FluentIterable.from(toAssignUserIds).transform(userId -> { Iterable<UserRole> toCreate = toAssignUserIds.stream().map(userId -> {
UserRole userRole = new UserRole(); UserRole userRole = new UserRole();
userRole.setRoleId(role.getId()); userRole.setRoleId(role.getId());
userRole.setUserId(userId); userRole.setUserId(userId);
userRole.setDataChangeCreatedBy(operatorUserId); userRole.setDataChangeCreatedBy(operatorUserId);
userRole.setDataChangeLastModifiedBy(operatorUserId); userRole.setDataChangeLastModifiedBy(operatorUserId);
return userRole; return userRole;
}); }).collect(Collectors.toList());
userRoleRepository.saveAll(toCreate); userRoleRepository.saveAll(toCreate);
return toAssignUserIds; return toAssignUserIds;
...@@ -135,11 +134,11 @@ public class DefaultRolePermissionService implements RolePermissionService { ...@@ -135,11 +134,11 @@ public class DefaultRolePermissionService implements RolePermissionService {
List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId()); List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId());
Set<UserInfo> users = FluentIterable.from(userRoles).transform(userRole -> { Set<UserInfo> users = userRoles.stream().map(userRole -> {
UserInfo userInfo = new UserInfo(); UserInfo userInfo = new UserInfo();
userInfo.setUserId(userRole.getUserId()); userInfo.setUserId(userRole.getUserId());
return userInfo; return userInfo;
}).toSet(); }).collect(Collectors.toSet());
return users; return users;
} }
...@@ -237,7 +236,7 @@ public class DefaultRolePermissionService implements RolePermissionService { ...@@ -237,7 +236,7 @@ public class DefaultRolePermissionService implements RolePermissionService {
} }
Iterable<Permission> results = permissionRepository.saveAll(permissions); Iterable<Permission> results = permissionRepository.saveAll(permissions);
return FluentIterable.from(results).toSet(); return StreamSupport.stream(results.spliterator(), false).collect(Collectors.toSet());
} }
@Transactional @Transactional
......
...@@ -61,14 +61,11 @@ public class ConsumerAuditUtilTest { ...@@ -61,14 +61,11 @@ public class ConsumerAuditUtilTest {
SettableFuture<List<ConsumerAudit>> result = SettableFuture.create(); SettableFuture<List<ConsumerAudit>> result = SettableFuture.create();
doAnswer(new Answer<Void>() { doAnswer((Answer<Void>) invocation -> {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments(); Object[] args = invocation.getArguments();
result.set((List<ConsumerAudit>) args[0]); result.set((List<ConsumerAudit>) args[0]);
return null; return null;
}
}).when(consumerService).createConsumerAudits(anyCollection()); }).when(consumerService).createConsumerAudits(anyCollection());
consumerAuditUtil.audit(request, someConsumerId); consumerAuditUtil.audit(request, someConsumerId);
......
package com.ctrip.framework.apollo.portal.spi.defaultImpl; package com.ctrip.framework.apollo.portal.spi.defaultImpl;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.common.entity.BaseEntity; import com.ctrip.framework.apollo.common.entity.BaseEntity;
import com.ctrip.framework.apollo.portal.AbstractIntegrationTest; import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.Permission; import com.ctrip.framework.apollo.portal.entity.po.Permission;
import com.ctrip.framework.apollo.portal.entity.po.Role; import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.entity.po.RolePermission; import com.ctrip.framework.apollo.portal.entity.po.RolePermission;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.UserRole; import com.ctrip.framework.apollo.portal.entity.po.UserRole;
import com.ctrip.framework.apollo.portal.repository.PermissionRepository; import com.ctrip.framework.apollo.portal.repository.PermissionRepository;
import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository; import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository;
import com.ctrip.framework.apollo.portal.repository.RoleRepository; import com.ctrip.framework.apollo.portal.repository.RoleRepository;
import com.ctrip.framework.apollo.portal.repository.UserRoleRepository; import com.ctrip.framework.apollo.portal.repository.UserRoleRepository;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.google.common.collect.Sets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -23,6 +20,7 @@ import org.springframework.test.context.jdbc.Sql; ...@@ -23,6 +20,7 @@ import org.springframework.test.context.jdbc.Sql;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
...@@ -99,9 +97,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest { ...@@ -99,9 +97,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest {
Set<Permission> created = Set<Permission> created =
rolePermissionService.createPermissions(Sets.newHashSet(somePermission, anotherPermission)); rolePermissionService.createPermissions(Sets.newHashSet(somePermission, anotherPermission));
Set<Long> permissionIds = Set<Long> permissionIds = created.stream().map(BaseEntity::getId).collect(Collectors.toSet());
FluentIterable.from(created).transform(BaseEntity::getId)
.toSet();
Iterable<Permission> permissionsFromDB = permissionRepository.findAllById(permissionIds); Iterable<Permission> permissionsFromDB = permissionRepository.findAllById(permissionIds);
...@@ -149,9 +145,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest { ...@@ -149,9 +145,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest {
List<RolePermission> rolePermissions = List<RolePermission> rolePermissions =
rolePermissionRepository.findByRoleIdIn(Sets.newHashSet(createdFromDB.getId())); rolePermissionRepository.findByRoleIdIn(Sets.newHashSet(createdFromDB.getId()));
Set<Long> rolePermissionIds = Set<Long> rolePermissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toSet());
FluentIterable.from(rolePermissions)
.transform(RolePermission::getPermissionId).toSet();
assertEquals(someRoleName, createdFromDB.getRoleName()); assertEquals(someRoleName, createdFromDB.getRoleName());
assertEquals(2, rolePermissionIds.size()); assertEquals(2, rolePermissionIds.size());
...@@ -279,7 +273,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest { ...@@ -279,7 +273,7 @@ public class RolePermissionServiceTest extends AbstractIntegrationTest {
Set<UserInfo> users = rolePermissionService.queryUsersWithRole(someRoleName); Set<UserInfo> users = rolePermissionService.queryUsersWithRole(someRoleName);
Set<String> userIds = FluentIterable.from(users).transform(UserInfo::getUserId).toSet(); Set<String> userIds = users.stream().map(UserInfo::getUserId).collect(Collectors.toSet());
assertTrue(userIds.containsAll(Sets.newHashSet("someUser", "anotherUser"))); assertTrue(userIds.containsAll(Sets.newHashSet("someUser", "anotherUser")));
} }
......
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