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