UserTokenService { String mergeStoredTokensWith(String tokens, UserToken userToken) { if (StringUtils.isBlank(tokens)) { return userToken.toStoreValue(); } Map<String, UserToken> userTokenMap = Arrays.stream(tokens.split(":")) .map(v -> UserToken.fromStoreValue(v, 0)) .filter(v -> v.isNotExpired(sessionExpireSec)) .collect(Collectors.toMap(UserToken::getToken, Function.identity())); userTokenMap.put(userToken.getToken(), userToken); return userTokenMap.values().stream() .map(UserToken::toStoreValue) .collect(Collectors.joining(":")); }  String publishToken(final Server server, final SUser user); void validateToken(UserToken token); public int sessionExpireSec; public int SessionTouchThresholdSec; }
@Test public void getAndMergeToStoredValue_with_expired_tokens() { UserToken userToken = UserToken.newToken(vutUserId, sessionIdGenerator.generateSessionId(), server.getId()); UserToken token0 = UserToken.newToken(vutUserId, sessionIdGenerator.generateSessionId(), server.getId()); UserToken token1 = UserToken.newToken(vutUserId, sessionIdGenerator.generateSessionId(), server.getId()); UserToken token2 = UserToken.newToken(vutUserId, sessionIdGenerator.generateSessionId(), server.getId()); token0.setFootprintSec(System.currentTimeMillis()/1000L - sut.sessionExpireSec - 1); token1.setFootprintSec(System.currentTimeMillis()/1000L - sut.sessionExpireSec - 1); token2.setFootprintSec(System.currentTimeMillis()/1000L - sut.sessionExpireSec - 1); String tokens = token0.toStoreValue() + ":" + token1.toStoreValue() + ":" + token2.toStoreValue(); String merged = sut.mergeStoredTokensWith(tokens, userToken); assertEquals(merged, userToken.toStoreValue()); }