刘光辉
昨天 bb638871a7fb692d80f1b7a758f991dc0879002c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package jnpf.dmsPermission;
 
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
@Slf4j
@Component
@RequiredArgsConstructor
public class DmsUserDisplayNameResolver {
    private final UserApi userApi;
 
    public Map<String, String> resolve(Collection<String> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return Collections.emptyMap();
        }
        Set<String> uniqueIds = userIds.stream()
                .map(this::trimToNull)
                .filter(value -> value != null)
                .collect(Collectors.toCollection(LinkedHashSet::new));
        if (uniqueIds.isEmpty()) {
            return Collections.emptyMap();
        }
 
        List<UserEntity> users;
        try {
            users = userApi.getUserName(uniqueIds.stream().collect(Collectors.toList()));
        } catch (RuntimeException ex) {
            log.warn("DMS user display name lookup failed for {} users", uniqueIds.size(), ex);
            return Collections.emptyMap();
        }
        if (users == null || users.isEmpty()) {
            return Collections.emptyMap();
        }
 
        Map<String, String> result = new LinkedHashMap<>();
        for (UserEntity user : users) {
            if (user == null) {
                continue;
            }
            String userId = trimToNull(user.getId());
            String displayName = displayName(user);
            if (userId != null && displayName != null) {
                result.putIfAbsent(userId, displayName);
            }
        }
        return result;
    }
 
    String displayName(UserEntity user) {
        String realName = trimToNull(user.getRealName());
        String account = trimToNull(user.getAccount());
        if (realName != null && account != null) {
            return realName + "(" + account + ")";
        }
        return realName != null ? realName : account;
    }
 
    private String trimToNull(String value) {
        return value == null || value.trim().isEmpty() ? null : value.trim();
    }
}