CachedUserNameToIdResolver .java

net.minecraft.server.players.CachedUserNameToIdResolver (class, 244 lines): members: GAMEPROFILES_EXPIRATION_MONTHS, GAMEPROFILES_MRU_LIMIT, gson, file.

net.minecraft.server.playersclass244 linesserver8.1 KB

Implements

API Surface (9)

void resolveOfflineUsers(final boolean value)
void add(final NameAndId nameAndId)
Optional<NameAndId> get(final String name)
Optional<NameAndId> get(final UUID id)
void save()
NameAndId nameAndId()
Date expirationDate()
void setLastAccess(final long currentOperation)
long lastAccess()

Fields & Constants (10)

LOGGER
GAMEPROFILES_MRU_LIMIT
GAMEPROFILES_EXPIRATION_MONTHS
resolveOfflineUsers
profilesByName
profilesByUUID
profileRepository
gson
file
operationCount

String literals (2)

"yyyy-MM-dd HH:mm:ss Z"
"expiresOn"

Code Graph: Dependencies (3)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

CachedUserNameToIdResolver.java244 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.players;
2
3
import com.google.common.collect.ImmutableList;
4
import com.google.common.collect.Lists;
5
import com.google.common.io.Files;
6
import com.google.gson.Gson;
7
import com.google.gson.GsonBuilder;
8
import com.google.gson.JsonArray;
9
import com.google.gson.JsonElement;
10
import com.google.gson.JsonObject;
11
import com.google.gson.JsonParseException;
12
import com.mojang.authlib.GameProfileRepository;
13
import com.mojang.logging.LogUtils;
14
import java.io.File;
15
import java.io.FileNotFoundException;
16
import java.io.IOException;
17
import java.io.Reader;
18
import java.io.Writer;
19
import java.nio.charset.StandardCharsets;
20
import java.text.DateFormat;
21
import java.text.ParseException;
22
import java.text.SimpleDateFormat;
23
import java.util.Calendar;
24
import java.util.Comparator;
25
import java.util.Date;
26
import java.util.List;
27
import java.util.Locale;
28
import java.util.Map;
29
import java.util.Optional;
30
import java.util.TimeZone;
31
import java.util.UUID;
32
import java.util.concurrent.ConcurrentHashMap;
33
import java.util.concurrent.atomic.AtomicLong;
34
import java.util.stream.Stream;
35
import net.minecraft.util.StringUtil;
36
import org.slf4j.Logger;
37
38
public class CachedUserNameToIdResolver implements UserNameToIdResolver {
39
	private static final Logger LOGGER = LogUtils.getLogger();
40
	private static final int GAMEPROFILES_MRU_LIMIT = 1000;
41
	private static final int GAMEPROFILES_EXPIRATION_MONTHS = 1;
42
	private boolean resolveOfflineUsers = true;
43
	private final Map<String, CachedUserNameToIdResolver.GameProfileInfo> profilesByName = new ConcurrentHashMap<>();
44
	private final Map<UUID, CachedUserNameToIdResolver.GameProfileInfo> profilesByUUID = new ConcurrentHashMap<>();
45
	private final GameProfileRepository profileRepository;
46
	private final Gson gson = new GsonBuilder().create();
47
	private final File file;
48
	private final AtomicLong operationCount = new AtomicLong();
49
50
	public CachedUserNameToIdResolver(final GameProfileRepository profileRepository, final File file) {
51
		this.profileRepository = profileRepository;
52
		this.file = file;
53
		Lists.reverse(this.load()).forEach(this::safeAdd);
54
	}
55
56
	private void safeAdd(final CachedUserNameToIdResolver.GameProfileInfo profileInfo) {
57
		NameAndId nameAndId = profileInfo.nameAndId();
58
		profileInfo.setLastAccess(this.getNextOperation());
59
		this.profilesByName.put(nameAndId.name().toLowerCase(Locale.ROOT), profileInfo);
60
		this.profilesByUUID.put(nameAndId.id(), profileInfo);
61
	}
62
63
	private Optional<NameAndId> lookupGameProfile(final GameProfileRepository profileRepository, final String name) {
64
		if (!StringUtil.isValidPlayerName(name)) {
65
			return this.createUnknownProfile(name);
66
		}
67
68
		Optional<NameAndId> profile = profileRepository.findProfileByName(name).map(NameAndId::new);
69
		return profile.isEmpty() ? this.createUnknownProfile(name) : profile;
70
	}
71
72
	private Optional<NameAndId> createUnknownProfile(final String name) {
73
		return this.resolveOfflineUsers ? Optional.of(NameAndId.createOffline(name)) : Optional.empty();
74
	}
75
76
	@Override
77
	public void resolveOfflineUsers(final boolean value) {
78
		this.resolveOfflineUsers = value;
79
	}
80
81
	@Override
82
	public void add(final NameAndId nameAndId) {
83
		this.addInternal(nameAndId);
84
	}
85
86
	private CachedUserNameToIdResolver.GameProfileInfo addInternal(final NameAndId profile) {
87
		Calendar c = Calendar.getInstance(TimeZone.getDefault(), Locale.ROOT);
88
		c.setTime(new Date());
89
		c.add(2, 1);
90
		Date expirationDate = c.getTime();
91
		CachedUserNameToIdResolver.GameProfileInfo profileInfo = new CachedUserNameToIdResolver.GameProfileInfo(profile, expirationDate);
92
		this.safeAdd(profileInfo);
93
		this.save();
94
		return profileInfo;
95
	}
96
97
	private long getNextOperation() {
98
		return this.operationCount.incrementAndGet();
99
	}
100
101
	@Override
102
	public Optional<NameAndId> get(final String name) {
103
		String userName = name.toLowerCase(Locale.ROOT);
104
		CachedUserNameToIdResolver.GameProfileInfo profileInfo = this.profilesByName.get(userName);
105
		boolean needsSave = false;
106
		if (profileInfo != null && new Date().getTime() >= profileInfo.expirationDate.getTime()) {
107
			this.profilesByUUID.remove(profileInfo.nameAndId().id());
108
			this.profilesByName.remove(profileInfo.nameAndId().name().toLowerCase(Locale.ROOT));
109
			needsSave = true;
110
			profileInfo = null;
111
		}
112
113
		Optional<NameAndId> result;
114
		if (profileInfo != null) {
115
			profileInfo.setLastAccess(this.getNextOperation());
116
			result = Optional.of(profileInfo.nameAndId());
117
		} else {
118
			Optional<NameAndId> profile = this.lookupGameProfile(this.profileRepository, userName);
119
			if (profile.isPresent()) {
120
				result = Optional.of(this.addInternal(profile.get()).nameAndId());
121
				needsSave = false;
122
			} else {
123
				result = Optional.empty();
124
			}
125
		}
126
127
		if (needsSave) {
128
			this.save();
129
		}
130
131
		return result;
132
	}
133
134
	@Override
135
	public Optional<NameAndId> get(final UUID id) {
136
		CachedUserNameToIdResolver.GameProfileInfo profileInfo = this.profilesByUUID.get(id);
137
		if (profileInfo == null) {
138
			return Optional.empty();
139
		}
140
141
		profileInfo.setLastAccess(this.getNextOperation());
142
		return Optional.of(profileInfo.nameAndId());
143
	}
144
145
	private static DateFormat createDateFormat() {
146
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ROOT);
147
	}
148
149
	private List<CachedUserNameToIdResolver.GameProfileInfo> load() {
150
		List<CachedUserNameToIdResolver.GameProfileInfo> result = Lists.newArrayList();
151
152
		try (Reader reader = Files.newReader(this.file, StandardCharsets.UTF_8)) {
153
			JsonArray entryList = this.gson.fromJson(reader, JsonArray.class);
154
			if (entryList == null) {
155
				return result;
156
			}
157
158
			DateFormat dateFormat = createDateFormat();
159
			entryList.forEach(element -> readGameProfile(element, dateFormat).ifPresent(result::add));
160
		} catch (FileNotFoundException var7) {
161
		} catch (IOException | JsonParseException e) {
162
			LOGGER.warn("Failed to load profile cache {}", this.file, e);
163
		}
164
165
		return result;
166
	}
167
168
	@Override
169
	public void save() {
170
		JsonArray entryList = new JsonArray();
171
		DateFormat dateFormat = createDateFormat();
172
		this.getTopMRUProfiles(1000).forEach(entry -> entryList.add(writeGameProfile(entry, dateFormat)));
173
		String toSave = this.gson.toJson(entryList);
174
175
		try (Writer writer = Files.newWriter(this.file, StandardCharsets.UTF_8)) {
176
			writer.write(toSave);
177
		} catch (IOException var9) {
178
		}
179
	}
180
181
	private Stream<CachedUserNameToIdResolver.GameProfileInfo> getTopMRUProfiles(final int limit) {
182
		return ImmutableList.copyOf(this.profilesByUUID.values())
183
			.stream()
184
			.sorted(Comparator.comparing(CachedUserNameToIdResolver.GameProfileInfo::lastAccess).reversed())
185
			.limit(limit);
186
	}
187
188
	private static JsonElement writeGameProfile(final CachedUserNameToIdResolver.GameProfileInfo src, final DateFormat dateFormat) {
189
		JsonObject object = new JsonObject();
190
		src.nameAndId().appendTo(object);
191
		object.addProperty("expiresOn", dateFormat.format(src.expirationDate()));
192
		return object;
193
	}
194
195
	private static Optional<CachedUserNameToIdResolver.GameProfileInfo> readGameProfile(final JsonElement json, final DateFormat dateFormat) {
196
		if (json.isJsonObject()) {
197
			JsonObject object = json.getAsJsonObject();
198
			NameAndId nameAndId = NameAndId.fromJson(object);
199
			if (nameAndId != null) {
200
				JsonElement expirationElement = object.get("expiresOn");
201
				if (expirationElement != null) {
202
					String dateAsString = expirationElement.getAsString();
203
204
					try {
205
						Date expirationDate = dateFormat.parse(dateAsString);
206
						return Optional.of(new CachedUserNameToIdResolver.GameProfileInfo(nameAndId, expirationDate));
207
					} catch (ParseException e) {
208
						LOGGER.warn("Failed to parse date {}", dateAsString, e);
209
					}
210
				}
211
			}
212
		}
213
214
		return Optional.empty();
215
	}
216
217
	private static class GameProfileInfo {
218
		private final NameAndId nameAndId;
219
		private final Date expirationDate;
220
		private volatile long lastAccess;
221
222
		private GameProfileInfo(final NameAndId nameAndId, final Date expirationDate) {
223
			this.nameAndId = nameAndId;
224
			this.expirationDate = expirationDate;
225
		}
226
227
		public NameAndId nameAndId() {
228
			return this.nameAndId;
229
		}
230
231
		public Date expirationDate() {
232
			return this.expirationDate;
233
		}
234
235
		public void setLastAccess(final long currentOperation) {
236
			this.lastAccess = currentOperation;
237
		}
238
239
		public long lastAccess() {
240
			return this.lastAccess;
241
		}
242
	}
243
}
244

Decompiled Minecraft 26.3 source of CachedUserNameToIdResolver (net/minecraft/server/players/CachedUserNameToIdResolver.java) with Mojang official mappings, stored verbatim on the site.