Skip to content

Commit

Permalink
Cleanup for 1.3.0 (#1969)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
kezhenxu94 authored and nobodyiam committed Feb 16, 2019
1 parent 72d32a5 commit 118dd0e
Show file tree
Hide file tree
Showing 19 changed files with 72 additions and 96 deletions.
Expand Up @@ -390,7 +390,7 @@ private Map<String, String> mergeConfiguration(Map<String, String> baseConfigura

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;
Expand Down
Expand Up @@ -66,7 +66,7 @@ private boolean process(MatchCallback callback, Yaml yaml, String content) {
@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);
Expand Down Expand Up @@ -102,7 +102,7 @@ private boolean process(Map<String, Object> map, MatchCallback callback) {
}

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;
}
Expand Down
Expand Up @@ -446,14 +446,8 @@ private ApolloConfig assembleApolloConfig(Map<String, String> configurations) {

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;
}
Expand Down
Expand Up @@ -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();
}
Expand All @@ -49,7 +49,7 @@ public static <T> T transform(Class<T> clazz, Object src) {
if (src == null) {
return null;
}
T instance = null;
T instance;
try {
instance = clazz.newInstance();
} catch (Exception e) {
Expand All @@ -63,7 +63,7 @@ private static String[] getNullPropertyNames(Object source) {
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());
Expand All @@ -83,13 +83,13 @@ private static String[] getNullPropertyNames(Object source) {
* @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);
Expand All @@ -111,21 +111,19 @@ public static <K, V> Map<K, V> mapByKey(String key, List<? extends Object> list)
* </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) {
Expand All @@ -143,13 +141,13 @@ public static <K, V> Map<K, List<V>> aggByKeyToList(String key, List<? extends O
* </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);
Expand All @@ -163,7 +161,7 @@ public static <K> Set<K> toPropertySet(String key, List<? extends Object> list)
}


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 {
Expand Down
Expand Up @@ -14,7 +14,6 @@
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;
Expand Down Expand Up @@ -45,6 +44,7 @@
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)
Expand Down
Expand Up @@ -5,7 +5,6 @@
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;
Expand All @@ -15,6 +14,7 @@
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Jason Song(song_s@ctrip.com)
Expand Down Expand Up @@ -137,6 +137,6 @@ private Set<String> namespacesBelongToAppId(String appId, Set<String> namespaces
return Collections.emptySet();
}

return FluentIterable.from(appNamespaces).transform(AppNamespace::getName).toSet();
return appNamespaces.stream().map(AppNamespace::getName).collect(Collectors.toSet());
}
}
Expand Up @@ -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;
}
Expand All @@ -25,7 +33,7 @@ public ServiceController(final DiscoveryService discoveryService) {
@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;
}

Expand All @@ -34,26 +42,14 @@ public List<ServiceDTO> getConfigService(
@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;
}
};

}
Expand Up @@ -244,8 +244,8 @@ public void testAppNamespace() throws Exception {
}

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);
}

Expand Down
Expand Up @@ -33,8 +33,8 @@ public static boolean waitAllShutdown(int timeoutInMillis) {
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) {
Expand Down
Expand Up @@ -8,7 +8,7 @@
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) {
Expand Down
Expand Up @@ -13,8 +13,7 @@

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
Expand Down
Expand Up @@ -99,7 +99,7 @@ private void load() {
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 {
Expand Down
Expand Up @@ -6,12 +6,12 @@
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)
Expand Down Expand Up @@ -47,7 +47,7 @@ public boolean consumerHasPermission(long consumerId, String permissionType, Str
}

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;
Expand Down
Expand Up @@ -40,7 +40,7 @@ public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO>
}

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();
Expand Down
Expand Up @@ -117,7 +117,7 @@ public List<ItemDTO> findItems(@PathVariable String appId, @PathVariable String

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;
}
Expand Down
Expand Up @@ -13,7 +13,6 @@
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;
Expand All @@ -22,6 +21,7 @@
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.
Expand Down Expand Up @@ -109,9 +109,8 @@ public void initNamespaceSpecificEnvRoles(String appId, String namespaceName, St

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 =
Expand Down

0 comments on commit 118dd0e

Please sign in to comment.