Make AccountState an AutoValue

AccountState is a cached entity that is shared between different
threads. We therefore want it to be immutable. AutoValue is the
preferred way of generating immutable entities that have equals and
toString implementations and is used for almost all other caches. Hence,
we use it for AccountState too.

Change-Id: I3b19ef34791c8800667fdcf9ad8beade8539af13
This commit is contained in:
Patrick Hiesel
2019-08-07 15:25:07 +02:00
parent a5dd85e5d2
commit 3e64fd492b
82 changed files with 253 additions and 278 deletions

View File

@@ -805,7 +805,7 @@ public abstract class AbstractDaemonTest {
} }
protected Account getAccount(Account.Id accountId) { protected Account getAccount(Account.Id accountId) {
return getAccountState(accountId).getAccount(); return getAccountState(accountId).account();
} }
protected AccountState getAccountState(Account.Id accountId) { protected AccountState getAccountState(Account.Id accountId) {

View File

@@ -61,9 +61,9 @@ public class AccountOperationsImpl implements AccountOperations {
private Account.Id createAccount(TestAccountCreation accountCreation) throws Exception { private Account.Id createAccount(TestAccountCreation accountCreation) throws Exception {
AccountsUpdate.AccountUpdater accountUpdater = AccountsUpdate.AccountUpdater accountUpdater =
(account, updateBuilder) -> (account, updateBuilder) ->
fillBuilder(updateBuilder, accountCreation, account.getAccount().id()); fillBuilder(updateBuilder, accountCreation, account.account().id());
AccountState createdAccount = createAccount(accountUpdater); AccountState createdAccount = createAccount(accountUpdater);
return createdAccount.getAccount().id(); return createdAccount.account().id();
} }
private AccountState createAccount(AccountsUpdate.AccountUpdater accountUpdater) private AccountState createAccount(AccountsUpdate.AccountUpdater accountUpdater)
@@ -129,13 +129,13 @@ public class AccountOperationsImpl implements AccountOperations {
} }
private TestAccount toTestAccount(AccountState accountState) { private TestAccount toTestAccount(AccountState accountState) {
Account account = accountState.getAccount(); Account account = accountState.account();
return TestAccount.builder() return TestAccount.builder()
.accountId(account.id()) .accountId(account.id())
.preferredEmail(Optional.ofNullable(account.preferredEmail())) .preferredEmail(Optional.ofNullable(account.preferredEmail()))
.fullname(Optional.ofNullable(account.fullName())) .fullname(Optional.ofNullable(account.fullName()))
.username(accountState.getUserName()) .username(accountState.userName())
.active(accountState.getAccount().isActive()) .active(accountState.account().isActive())
.build(); .build();
} }

View File

@@ -85,7 +85,7 @@ public class ElasticAccountIndex extends AbstractElasticIndex<Account.Id, Accoun
throw new StorageException( throw new StorageException(
String.format( String.format(
"Failed to replace account %s in index %s: %s", "Failed to replace account %s in index %s: %s",
as.getAccount().id(), indexName, statusCode)); as.account().id(), indexName, statusCode));
} }
} }
@@ -108,7 +108,7 @@ public class ElasticAccountIndex extends AbstractElasticIndex<Account.Id, Accoun
@Override @Override
protected String getId(AccountState as) { protected String getId(AccountState as) {
return as.getAccount().id().toString(); return as.account().id().toString();
} }
@Override @Override

View File

@@ -201,7 +201,7 @@ public class GerritPublicKeyChecker extends PublicKeyChecker {
private Set<String> getAllowedUserIds(IdentifiedUser user) { private Set<String> getAllowedUserIds(IdentifiedUser user) {
Set<String> result = new HashSet<>(); Set<String> result = new HashSet<>();
result.addAll(user.getEmailAddresses()); result.addAll(user.getEmailAddresses());
for (ExternalId extId : user.state().getExternalIds()) { for (ExternalId extId : user.state().externalIds()) {
if (extId.isScheme(SCHEME_GPGKEY)) { if (extId.isScheme(SCHEME_GPGKEY)) {
continue; // Omit GPG keys. continue; // Omit GPG keys.
} }

View File

@@ -304,12 +304,12 @@ public class PostGpgKeys implements RestModifyView<AccountResource, GpgKeysInput
String msg = "GPG key " + extIdKey.get() + " associated with multiple accounts: ["; String msg = "GPG key " + extIdKey.get() + " associated with multiple accounts: [";
msg = msg =
accountStates.stream() accountStates.stream()
.map(a -> a.getAccount().id().toString()) .map(a -> a.account().id().toString())
.collect(joining(", ", msg, "]")); .collect(joining(", ", msg, "]"));
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
return accountStates.get(0).getAccount(); return accountStates.get(0).account();
} }
private Map<String, GpgKeyInfo> toJson( private Map<String, GpgKeyInfo> toJson(

View File

@@ -112,13 +112,13 @@ class ContainerAuthFilter implements Filter {
username = username.toLowerCase(Locale.US); username = username.toLowerCase(Locale.US);
} }
Optional<AccountState> who = Optional<AccountState> who =
accountCache.getByUsername(username).filter(a -> a.getAccount().isActive()); accountCache.getByUsername(username).filter(a -> a.account().isActive());
if (!who.isPresent()) { if (!who.isPresent()) {
rsp.sendError(SC_UNAUTHORIZED); rsp.sendError(SC_UNAUTHORIZED);
return false; return false;
} }
WebSession ws = session.get(); WebSession ws = session.get();
ws.setUserAccountId(who.get().getAccount().id()); ws.setUserAccountId(who.get().account().id());
ws.setAccessPathOk(AccessPath.GIT, true); ws.setAccessPathOk(AccessPath.GIT, true);
ws.setAccessPathOk(AccessPath.REST_API, true); ws.setAccessPathOk(AccessPath.REST_API, true);
return true; return true;

View File

@@ -129,7 +129,7 @@ class ProjectBasicAuthFilter implements Filter {
} }
Optional<AccountState> accountState = Optional<AccountState> accountState =
accountCache.getByUsername(username).filter(a -> a.getAccount().isActive()); accountCache.getByUsername(username).filter(a -> a.account().isActive());
if (!accountState.isPresent()) { if (!accountState.isPresent()) {
logger.atWarning().log( logger.atWarning().log(
"Authentication failed for %s: account inactive or not provisioned in Gerrit", username); "Authentication failed for %s: account inactive or not provisioned in Gerrit", username);
@@ -141,7 +141,7 @@ class ProjectBasicAuthFilter implements Filter {
GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy(); GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP
|| gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) { || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
if (PasswordVerifier.checkPassword(who.getExternalIds(), username, password)) { if (PasswordVerifier.checkPassword(who.externalIds(), username, password)) {
return succeedAuthentication(who); return succeedAuthentication(who);
} }
} }
@@ -158,7 +158,7 @@ class ProjectBasicAuthFilter implements Filter {
setUserIdentified(whoAuthResult.getAccountId()); setUserIdentified(whoAuthResult.getAccountId());
return true; return true;
} catch (NoSuchUserException e) { } catch (NoSuchUserException e) {
if (PasswordVerifier.checkPassword(who.getExternalIds(), username, password)) { if (PasswordVerifier.checkPassword(who.externalIds(), username, password)) {
return succeedAuthentication(who); return succeedAuthentication(who);
} }
logger.atWarning().withCause(e).log(authenticationFailedMsg(username, req)); logger.atWarning().withCause(e).log(authenticationFailedMsg(username, req));
@@ -178,7 +178,7 @@ class ProjectBasicAuthFilter implements Filter {
} }
private boolean succeedAuthentication(AccountState who) { private boolean succeedAuthentication(AccountState who) {
setUserIdentified(who.getAccount().id()); setUserIdentified(who.account().id());
return true; return true;
} }

View File

@@ -152,7 +152,7 @@ class ProjectOAuthFilter implements Filter {
} }
Optional<AccountState> who = Optional<AccountState> who =
accountCache.getByUsername(authInfo.username).filter(a -> a.getAccount().isActive()); accountCache.getByUsername(authInfo.username).filter(a -> a.account().isActive());
if (!who.isPresent()) { if (!who.isPresent()) {
logger.atWarning().log( logger.atWarning().log(
authenticationFailedMsg(authInfo.username, req) authenticationFailedMsg(authInfo.username, req)
@@ -161,7 +161,7 @@ class ProjectOAuthFilter implements Filter {
return false; return false;
} }
Account account = who.get().getAccount(); Account account = who.get().account();
AuthRequest authRequest = AuthRequest.forExternalUser(authInfo.username); AuthRequest authRequest = AuthRequest.forExternalUser(authInfo.username);
authRequest.setEmailAddress(account.preferredEmail()); authRequest.setEmailAddress(account.preferredEmail());
authRequest.setDisplayName(account.fullName()); authRequest.setDisplayName(account.fullName());

View File

@@ -105,7 +105,7 @@ class RunAsFilter implements Filter {
Account.Id target; Account.Id target;
try { try {
target = accountResolver.resolve(runas).asUnique().getAccount().id(); target = accountResolver.resolve(runas).asUnique().account().id();
} catch (UnprocessableEntityException e) { } catch (UnprocessableEntityException e) {
replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null); replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null);
return; return;

View File

@@ -153,10 +153,10 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
if (!accountState.isPresent()) { if (!accountState.isPresent()) {
continue; continue;
} }
Account account = accountState.get().getAccount(); Account account = accountState.get().account();
String displayName; String displayName;
if (accountState.get().getUserName().isPresent()) { if (accountState.get().userName().isPresent()) {
displayName = accountState.get().getUserName().get(); displayName = accountState.get().userName().get();
} else if (account.fullName() != null && !account.fullName().isEmpty()) { } else if (account.fullName() != null && !account.fullName().isEmpty()) {
displayName = account.fullName(); displayName = account.fullName();
} else if (account.preferredEmail() != null) { } else if (account.preferredEmail() != null) {
@@ -176,7 +176,7 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
} }
private Optional<AuthResult> auth(Optional<AccountState> account) { private Optional<AuthResult> auth(Optional<AccountState> account) {
return account.map(a -> new AuthResult(a.getAccount().id(), null, false)); return account.map(a -> new AuthResult(a.account().id(), null, false));
} }
private AuthResult auth(Account.Id account) { private AuthResult auth(Account.Id account) {
@@ -196,7 +196,7 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
getServletContext().log("Multiple accounts with username " + userName + " found"); getServletContext().log("Multiple accounts with username " + userName + " found");
return null; return null;
} }
return auth(accountStates.get(0).getAccount().id()); return auth(accountStates.get(0).account().id());
} }
private Optional<AuthResult> byPreferredEmail(String email) { private Optional<AuthResult> byPreferredEmail(String email) {

View File

@@ -62,7 +62,7 @@ public class LuceneAccountIndex extends AbstractLuceneIndex<Account.Id, AccountS
private static final String ID_SORT_FIELD = sortFieldName(ID); private static final String ID_SORT_FIELD = sortFieldName(ID);
private static Term idTerm(AccountState as) { private static Term idTerm(AccountState as) {
return idTerm(as.getAccount().id()); return idTerm(as.account().id());
} }
private static Term idTerm(Account.Id id) { private static Term idTerm(Account.Id id) {

View File

@@ -234,7 +234,7 @@ public class IdentifiedUser extends CurrentUser {
groupBackend, groupBackend,
enableReverseDnsLookup, enableReverseDnsLookup,
remotePeerProvider, remotePeerProvider,
state.getAccount().id(), state.account().id(),
realUser); realUser);
this.state = state; this.state = state;
} }
@@ -323,7 +323,7 @@ public class IdentifiedUser extends CurrentUser {
*/ */
@Override @Override
public Optional<String> getUserName() { public Optional<String> getUserName() {
return state().getUserName(); return state().userName();
} }
/** @return unique name of the user for logging, never {@code null} */ /** @return unique name of the user for logging, never {@code null} */
@@ -339,7 +339,7 @@ public class IdentifiedUser extends CurrentUser {
* @return the account of the identified user, an empty account if the account is missing * @return the account of the identified user, an empty account if the account is missing
*/ */
public Account getAccount() { public Account getAccount() {
return state().getAccount(); return state().account();
} }
public boolean hasEmailAddress(String email) { public boolean hasEmailAddress(String email) {
@@ -376,7 +376,7 @@ public class IdentifiedUser extends CurrentUser {
@Override @Override
public GroupMembership getEffectiveGroups() { public GroupMembership getEffectiveGroups() {
if (effectiveGroups == null) { if (effectiveGroups == null) {
if (authConfig.isIdentityTrustable(state().getExternalIds())) { if (authConfig.isIdentityTrustable(state().externalIds())) {
effectiveGroups = groupBackend.membershipsOf(this); effectiveGroups = groupBackend.membershipsOf(this);
logger.atFinest().log( logger.atFinest().log(
"Known groups of %s: %s", getLoggableName(), lazy(effectiveGroups::getKnownGroups)); "Known groups of %s: %s", getLoggableName(), lazy(effectiveGroups::getKnownGroups));

View File

@@ -53,7 +53,7 @@ public abstract class AbstractRealm implements Realm {
@Override @Override
public boolean hasEmailAddress(IdentifiedUser user, String email) { public boolean hasEmailAddress(IdentifiedUser user, String email) {
for (ExternalId ext : user.state().getExternalIds()) { for (ExternalId ext : user.state().externalIds()) {
if (email != null && email.equalsIgnoreCase(ext.email())) { if (email != null && email.equalsIgnoreCase(ext.email())) {
return true; return true;
} }
@@ -63,7 +63,7 @@ public abstract class AbstractRealm implements Realm {
@Override @Override
public Set<String> getEmailAddresses(IdentifiedUser user) { public Set<String> getEmailAddresses(IdentifiedUser user) {
Collection<ExternalId> ids = user.state().getExternalIds(); Collection<ExternalId> ids = user.state().externalIds();
Set<String> emails = Sets.newHashSetWithExpectedSize(ids.size()); Set<String> emails = Sets.newHashSetWithExpectedSize(ids.size());
for (ExternalId ext : ids) { for (ExternalId ext : ids) {
if (!Strings.isNullOrEmpty(ext.email())) { if (!Strings.isNullOrEmpty(ext.email())) {

View File

@@ -133,7 +133,7 @@ public class AccountCacheImpl implements AccountCache {
} }
for (Future<Optional<AccountState>> f : futures) { for (Future<Optional<AccountState>> f : futures) {
try { try {
f.get().ifPresent(s -> accountStates.put(s.getAccount().id(), s)); f.get().ifPresent(s -> accountStates.put(s.account().id(), s));
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
logger.atSevere().withCause(e).log("Cannot load AccountState"); logger.atSevere().withCause(e).log("Cannot load AccountState");
} }

View File

@@ -133,7 +133,7 @@ public class AccountControl {
new OtherUser() { new OtherUser() {
@Override @Override
Account.Id getId() { Account.Id getId() {
return otherUser.getAccount().id(); return otherUser.account().id();
} }
@Override @Override

View File

@@ -100,15 +100,15 @@ public class AccountDeactivator implements Runnable {
} }
private boolean processAccount(AccountState accountState) { private boolean processAccount(AccountState accountState) {
if (!accountState.getUserName().isPresent()) { if (!accountState.userName().isPresent()) {
return false; return false;
} }
String userName = accountState.getUserName().get(); String userName = accountState.userName().get();
logger.atFine().log("processing account %s", userName); logger.atFine().log("processing account %s", userName);
try { try {
if (realm.accountBelongsToRealm(accountState.getExternalIds()) && !realm.isActive(userName)) { if (realm.accountBelongsToRealm(accountState.externalIds()) && !realm.isActive(userName)) {
sif.deactivate(accountState.getAccount().id()); sif.deactivate(accountState.account().id());
logger.atInfo().log("deactivated account %s", userName); logger.atInfo().log("deactivated account %s", userName);
return true; return true;
} }
@@ -117,7 +117,7 @@ public class AccountDeactivator implements Runnable {
} catch (Exception e) { } catch (Exception e) {
logger.atSevere().withCause(e).log( logger.atSevere().withCause(e).log(
"Error deactivating account: %s (%s) %s", "Error deactivating account: %s (%s) %s",
userName, accountState.getAccount().id(), e.getMessage()); userName, accountState.account().id(), e.getMessage());
} }
return false; return false;
} }

View File

@@ -151,7 +151,7 @@ public class AccountManager {
} }
// Account exists // Account exists
Optional<Account> act = updateAccountActiveStatus(who, accountState.get().getAccount()); Optional<Account> act = updateAccountActiveStatus(who, accountState.get().account());
if (!act.isPresent()) { if (!act.isPresent()) {
// The account was deleted since we checked for it last time. This should never happen // The account was deleted since we checked for it last time. This should never happen
// since we don't support deletion of accounts. // since we don't support deletion of accounts.
@@ -207,7 +207,7 @@ public class AccountManager {
throw new AccountException("Unable to deactivate account " + account.id(), e); throw new AccountException("Unable to deactivate account " + account.id(), e);
} }
} }
return byIdCache.get(account.id()).map(AccountState::getAccount); return byIdCache.get(account.id()).map(AccountState::account);
} }
private boolean shouldUpdateActiveStatus(AuthRequest authRequest) { private boolean shouldUpdateActiveStatus(AuthRequest authRequest) {
@@ -337,7 +337,7 @@ public class AccountManager {
addGroupMember(adminGroupUuid, user); addGroupMember(adminGroupUuid, user);
} }
realm.onCreateAccount(who, accountState.getAccount()); realm.onCreateAccount(who, accountState.account());
return new AuthResult(newId, extId.key(), true); return new AuthResult(newId, extId.key(), true);
} }
@@ -421,7 +421,7 @@ public class AccountManager {
to, to,
(a, u) -> { (a, u) -> {
u.addExternalId(newExtId); u.addExternalId(newExtId);
if (who.getEmailAddress() != null && a.getAccount().preferredEmail() == null) { if (who.getEmailAddress() != null && a.account().preferredEmail() == null) {
u.setPreferredEmail(who.getEmailAddress()); u.setPreferredEmail(who.getEmailAddress());
} }
}); });
@@ -450,7 +450,7 @@ public class AccountManager {
to, to,
(a, u) -> { (a, u) -> {
Set<ExternalId> filteredExtIdsByScheme = Set<ExternalId> filteredExtIdsByScheme =
a.getExternalIds().stream() a.externalIds().stream()
.filter(e -> e.key().isScheme(who.getExternalIdKey().scheme())) .filter(e -> e.key().isScheme(who.getExternalIdKey().scheme()))
.collect(toImmutableSet()); .collect(toImmutableSet());
if (filteredExtIdsByScheme.isEmpty()) { if (filteredExtIdsByScheme.isEmpty()) {
@@ -514,9 +514,9 @@ public class AccountManager {
from, from,
(a, u) -> { (a, u) -> {
u.deleteExternalIds(extIds); u.deleteExternalIds(extIds);
if (a.getAccount().preferredEmail() != null if (a.account().preferredEmail() != null
&& extIds.stream() && extIds.stream()
.anyMatch(e -> a.getAccount().preferredEmail().equals(e.email()))) { .anyMatch(e -> a.account().preferredEmail().equals(e.email()))) {
u.setPreferredEmail(null); u.setPreferredEmail(null);
} }
}); });

View File

@@ -113,9 +113,9 @@ public class AccountResolver {
} }
private static String formatForException(Result result, AccountState state) { private static String formatForException(Result result, AccountState state) {
return state.getAccount().id() return state.account().id()
+ ": " + ": "
+ state.getAccount().getNameEmail(result.accountResolver().anonymousCowardName); + state.account().getNameEmail(result.accountResolver().anonymousCowardName);
} }
public static boolean isSelf(String input) { public static boolean isSelf(String input) {
@@ -135,7 +135,7 @@ public class AccountResolver {
} }
private ImmutableList<AccountState> canonicalize(List<AccountState> list) { private ImmutableList<AccountState> canonicalize(List<AccountState> list) {
TreeSet<AccountState> set = new TreeSet<>(comparing(a -> a.getAccount().id().get())); TreeSet<AccountState> set = new TreeSet<>(comparing(a -> a.account().id().get()));
set.addAll(requireNonNull(list)); set.addAll(requireNonNull(list));
return ImmutableList.copyOf(set); return ImmutableList.copyOf(set);
} }
@@ -160,7 +160,7 @@ public class AccountResolver {
} }
public ImmutableSet<Account.Id> asIdSet() { public ImmutableSet<Account.Id> asIdSet() {
return list.stream().map(a -> a.getAccount().id()).collect(toImmutableSet()); return list.stream().map(a -> a.account().id()).collect(toImmutableSet());
} }
public AccountState asUnique() throws UnresolvableAccountException { public AccountState asUnique() throws UnresolvableAccountException {
@@ -192,7 +192,7 @@ public class AccountResolver {
return self.get().asIdentifiedUser(); return self.get().asIdentifiedUser();
} }
return userFactory.runAs( return userFactory.runAs(
null, list.get(0).getAccount().id(), requireNonNull(caller).getRealUser()); null, list.get(0).account().id(), requireNonNull(caller).getRealUser());
} }
@VisibleForTesting @VisibleForTesting
@@ -349,7 +349,7 @@ public class AccountResolver {
String name = nameOrEmail.substring(0, lt - 1); String name = nameOrEmail.substring(0, lt - 1);
ImmutableList<AccountState> nameMatches = ImmutableList<AccountState> nameMatches =
allMatches.stream() allMatches.stream()
.filter(a -> name.equals(a.getAccount().fullName())) .filter(a -> name.equals(a.account().fullName()))
.collect(toImmutableList()); .collect(toImmutableList());
return !nameMatches.isEmpty() ? nameMatches.stream() : allMatches.stream(); return !nameMatches.isEmpty() ? nameMatches.stream() : allMatches.stream();
} }
@@ -558,7 +558,7 @@ public class AccountResolver {
} }
private Predicate<AccountState> accountActivityPredicate() { private Predicate<AccountState> accountActivityPredicate() {
return (AccountState accountState) -> accountState.getAccount().isActive(); return (AccountState accountState) -> accountState.account().isActive();
} }
@VisibleForTesting @VisibleForTesting

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.account; package com.google.gerrit.server.account;
import com.google.auto.value.AutoValue;
import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@@ -39,7 +40,8 @@ import org.eclipse.jgit.lib.ObjectId;
* <p>Most callers should not construct AccountStates directly but rather lookup accounts via the * <p>Most callers should not construct AccountStates directly but rather lookup accounts via the
* account cache (see {@link AccountCache#get(Account.Id)}). * account cache (see {@link AccountCache#get(Account.Id)}).
*/ */
public class AccountState { @AutoValue
public abstract class AccountState {
/** /**
* Creates an AccountState from the given account config. * Creates an AccountState from the given account config.
* *
@@ -90,13 +92,22 @@ public class AccountState {
// an open Repository instance. // an open Repository instance.
ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> projectWatches = ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> projectWatches =
accountConfig.getProjectWatches(); accountConfig.getProjectWatches();
GeneralPreferencesInfo generalPreferences = accountConfig.getGeneralPreferences(); Preferences.General generalPreferences =
DiffPreferencesInfo diffPreferences = accountConfig.getDiffPreferences(); Preferences.General.fromInfo(accountConfig.getGeneralPreferences());
EditPreferencesInfo editPreferences = accountConfig.getEditPreferences(); Preferences.Diff diffPreferences =
Preferences.Diff.fromInfo(accountConfig.getDiffPreferences());
Preferences.Edit editPreferences =
Preferences.Edit.fromInfo(accountConfig.getEditPreferences());
return Optional.of( return Optional.of(
new AccountState( new AutoValue_AccountState(
account, extIds, projectWatches, generalPreferences, diffPreferences, editPreferences)); account,
extIds,
ExternalId.getUserName(extIds),
projectWatches,
generalPreferences,
diffPreferences,
editPreferences));
} }
/** /**
@@ -118,44 +129,20 @@ public class AccountState {
* @return the account state * @return the account state
*/ */
public static AccountState forAccount(Account account, Collection<ExternalId> extIds) { public static AccountState forAccount(Account account, Collection<ExternalId> extIds) {
return new AccountState( return new AutoValue_AccountState(
account, account,
ImmutableSet.copyOf(extIds), ImmutableSet.copyOf(extIds),
ExternalId.getUserName(extIds),
ImmutableMap.of(), ImmutableMap.of(),
GeneralPreferencesInfo.defaults(), Preferences.General.fromInfo(GeneralPreferencesInfo.defaults()),
DiffPreferencesInfo.defaults(), Preferences.Diff.fromInfo(DiffPreferencesInfo.defaults()),
EditPreferencesInfo.defaults()); Preferences.Edit.fromInfo(EditPreferencesInfo.defaults()));
}
private final Account account;
private final ImmutableSet<ExternalId> externalIds;
private final Optional<String> userName;
private final ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> projectWatches;
private final Preferences.General generalPreferences;
private final Preferences.Diff diffPreferences;
private final Preferences.Edit editPreferences;
private AccountState(
Account account,
ImmutableSet<ExternalId> externalIds,
ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> projectWatches,
GeneralPreferencesInfo generalPreferences,
DiffPreferencesInfo diffPreferences,
EditPreferencesInfo editPreferences) {
this.account = account;
this.externalIds = externalIds;
this.userName = ExternalId.getUserName(externalIds);
this.projectWatches = projectWatches;
this.generalPreferences = Preferences.General.fromInfo(generalPreferences);
this.diffPreferences = Preferences.Diff.fromInfo(diffPreferences);
this.editPreferences = Preferences.Edit.fromInfo(editPreferences);
} }
/** Get the cached account metadata. */ /** Get the cached account metadata. */
public Account getAccount() { public abstract Account account();
return account; /** The external identities that identify the account holder. */
} public abstract ImmutableSet<ExternalId> externalIds();
/** /**
* Get the username, if one has been declared for this user. * Get the username, if one has been declared for this user.
* *
@@ -164,39 +151,36 @@ public class AccountState {
* @return the username, {@link Optional#empty()} if the user has no username, or if the username * @return the username, {@link Optional#empty()} if the user has no username, or if the username
* is empty * is empty
*/ */
public Optional<String> getUserName() { public abstract Optional<String> userName();
return userName;
}
/** The external identities that identify the account holder. */
public ImmutableSet<ExternalId> getExternalIds() {
return externalIds;
}
/** The project watches of the account. */ /** The project watches of the account. */
public ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> getProjectWatches() { public abstract ImmutableMap<ProjectWatchKey, ImmutableSet<NotifyType>> projectWatches();
return projectWatches; /** The general preferences of the account. */
}
/** The general preferences of the account. */ /** The general preferences of the account. */
public GeneralPreferencesInfo getGeneralPreferences() { public GeneralPreferencesInfo generalPreferences() {
return generalPreferences.toInfo(); return immutableGeneralPreferences().toInfo();
} }
/** The diff preferences of the account. */ /** The diff preferences of the account. */
public DiffPreferencesInfo getDiffPreferences() { public DiffPreferencesInfo diffPreferences() {
return diffPreferences.toInfo(); return immutableDiffPreferences().toInfo();
} }
/** The edit preferences of the account. */ /** The edit preferences of the account. */
public EditPreferencesInfo getEditPreferences() { public EditPreferencesInfo editPreferences() {
return editPreferences.toInfo(); return immutableEditPreferences().toInfo();
} }
@Override @Override
public String toString() { public final String toString() {
MoreObjects.ToStringHelper h = MoreObjects.toStringHelper(this); MoreObjects.ToStringHelper h = MoreObjects.toStringHelper(this);
h.addValue(getAccount().id()); h.addValue(account().id());
return h.toString(); return h.toString();
} }
protected abstract Preferences.General immutableGeneralPreferences();
protected abstract Preferences.Diff immutableDiffPreferences();
protected abstract Preferences.Edit immutableEditPreferences();
} }

View File

@@ -35,9 +35,9 @@ public class AccountsConsistencyChecker {
List<ConsistencyProblemInfo> problems = new ArrayList<>(); List<ConsistencyProblemInfo> problems = new ArrayList<>();
for (AccountState accountState : accounts.all()) { for (AccountState accountState : accounts.all()) {
Account account = accountState.getAccount(); Account account = accountState.account();
if (account.preferredEmail() != null) { if (account.preferredEmail() != null) {
if (!accountState.getExternalIds().stream() if (!accountState.externalIds().stream()
.anyMatch(e -> account.preferredEmail().equals(e.email()))) { .anyMatch(e -> account.preferredEmail().equals(e.email()))) {
addError( addError(
String.format( String.format(

View File

@@ -82,7 +82,7 @@ public class Emails {
} }
return executeIndexQuery(() -> queryProvider.get().byPreferredEmail(email).stream()) return executeIndexQuery(() -> queryProvider.get().byPreferredEmail(email).stream())
.map(a -> a.getAccount().id()) .map(a -> a.account().id())
.collect(toImmutableSet()); .collect(toImmutableSet());
} }
@@ -102,7 +102,7 @@ public class Emails {
if (!emailsToBackfill.isEmpty()) { if (!emailsToBackfill.isEmpty()) {
executeIndexQuery( executeIndexQuery(
() -> queryProvider.get().byPreferredEmail(emailsToBackfill).entries().stream()) () -> queryProvider.get().byPreferredEmail(emailsToBackfill).entries().stream())
.forEach(e -> result.put(e.getKey(), e.getValue().getAccount().id())); .forEach(e -> result.put(e.getKey(), e.getValue().account().id()));
} }
return ImmutableSetMultimap.copyOf(result); return ImmutableSetMultimap.copyOf(result);
} }

View File

@@ -131,7 +131,7 @@ public class GroupMembers {
.filter(groupControl::canSeeMember) .filter(groupControl::canSeeMember)
.map(accountCache::get) .map(accountCache::get)
.flatMap(Streams::stream) .flatMap(Streams::stream)
.map(AccountState::getAccount) .map(AccountState::account)
.collect(toImmutableSet()); .collect(toImmutableSet());
Set<Account> indirectMembers = new HashSet<>(); Set<Account> indirectMembers = new HashSet<>();

View File

@@ -105,7 +105,7 @@ public class InternalAccountDirectory extends AccountDirectory {
AccountState state = accountStates.get(id); AccountState state = accountStates.get(id);
if (state != null) { if (state != null) {
if (!options.contains(FillOptions.SECONDARY_EMAILS) if (!options.contains(FillOptions.SECONDARY_EMAILS)
|| Objects.equals(currentUserId, state.getAccount().id()) || Objects.equals(currentUserId, state.account().id())
|| canModifyAccount) { || canModifyAccount) {
fill(info, accountStates.get(id), options); fill(info, accountStates.get(id), options);
} else { } else {
@@ -120,7 +120,7 @@ public class InternalAccountDirectory extends AccountDirectory {
} }
private void fill(AccountInfo info, AccountState accountState, Set<FillOptions> options) { private void fill(AccountInfo info, AccountState accountState, Set<FillOptions> options) {
Account account = accountState.getAccount(); Account account = accountState.account();
if (options.contains(FillOptions.ID)) { if (options.contains(FillOptions.ID)) {
info._accountId = account.id().get(); info._accountId = account.id().get();
} else { } else {
@@ -130,17 +130,17 @@ public class InternalAccountDirectory extends AccountDirectory {
if (options.contains(FillOptions.NAME)) { if (options.contains(FillOptions.NAME)) {
info.name = Strings.emptyToNull(account.fullName()); info.name = Strings.emptyToNull(account.fullName());
if (info.name == null) { if (info.name == null) {
info.name = accountState.getUserName().orElse(null); info.name = accountState.userName().orElse(null);
} }
} }
if (options.contains(FillOptions.EMAIL)) { if (options.contains(FillOptions.EMAIL)) {
info.email = account.preferredEmail(); info.email = account.preferredEmail();
} }
if (options.contains(FillOptions.SECONDARY_EMAILS)) { if (options.contains(FillOptions.SECONDARY_EMAILS)) {
info.secondaryEmails = getSecondaryEmails(account, accountState.getExternalIds()); info.secondaryEmails = getSecondaryEmails(account, accountState.externalIds());
} }
if (options.contains(FillOptions.USERNAME)) { if (options.contains(FillOptions.USERNAME)) {
info.username = accountState.getUserName().orElse(null); info.username = accountState.userName().orElse(null);
} }
if (options.contains(FillOptions.STATUS)) { if (options.contains(FillOptions.STATUS)) {

View File

@@ -56,7 +56,7 @@ public class SetInactiveFlag {
"Deactivate Account via API", "Deactivate Account via API",
accountId, accountId,
(a, u) -> { (a, u) -> {
if (!a.getAccount().isActive()) { if (!a.account().isActive()) {
alreadyInactive.set(true); alreadyInactive.set(true);
} else { } else {
try { try {
@@ -89,7 +89,7 @@ public class SetInactiveFlag {
"Activate Account via API", "Activate Account via API",
accountId, accountId,
(a, u) -> { (a, u) -> {
if (a.getAccount().isActive()) { if (a.account().isActive()) {
alreadyActive.set(true); alreadyActive.set(true);
} else { } else {
try { try {

View File

@@ -141,7 +141,7 @@ class GroupsImpl implements Groups {
if (req.getUser() != null) { if (req.getUser() != null) {
try { try {
list.setUser(accountResolver.resolve(req.getUser()).asUnique().getAccount().id()); list.setUser(accountResolver.resolve(req.getUser()).asUnique().account().id());
} catch (Exception e) { } catch (Exception e) {
throw asRestApiException("Error looking up user " + req.getUser(), e); throw asRestApiException("Error looking up user " + req.getUser(), e);
} }

View File

@@ -62,7 +62,7 @@ public class AccountIdHandler extends OptionHandler<Account.Id> {
Account.Id accountId; Account.Id accountId;
try { try {
try { try {
accountId = accountResolver.resolve(token).asUnique().getAccount().id(); accountId = accountResolver.resolve(token).asUnique().account().id();
} catch (UnprocessableEntityException e) { } catch (UnprocessableEntityException e) {
switch (authType) { switch (authType) {
case HTTP_LDAP: case HTTP_LDAP:

View File

@@ -56,14 +56,14 @@ public class InternalAuthBackend implements AuthBackend {
AccountState who = accountCache.getByUsername(username).orElseThrow(UnknownUserException::new); AccountState who = accountCache.getByUsername(username).orElseThrow(UnknownUserException::new);
if (!who.getAccount().isActive()) { if (!who.account().isActive()) {
throw new UserNotAllowedException( throw new UserNotAllowedException(
"Authentication failed for " "Authentication failed for "
+ username + username
+ ": account inactive or not provisioned in Gerrit"); + ": account inactive or not provisioned in Gerrit");
} }
if (!PasswordVerifier.checkPassword(who.getExternalIds(), username, req.getPassword().get())) { if (!PasswordVerifier.checkPassword(who.externalIds(), username, req.getPassword().get())) {
throw new InvalidCredentialsException(); throw new InvalidCredentialsException();
} }
return new AuthUser(AuthUser.UUID.create(username), username); return new AuthUser(AuthUser.UUID.create(username), username);

View File

@@ -179,7 +179,7 @@ public class LdapGroupBackend implements GroupBackend {
@Override @Override
public GroupMembership membershipsOf(IdentifiedUser user) { public GroupMembership membershipsOf(IdentifiedUser user) {
String id = findId(user.state().getExternalIds()); String id = findId(user.state().externalIds());
if (id == null) { if (id == null) {
return GroupMembership.EMPTY; return GroupMembership.EMPTY;
} }

View File

@@ -112,7 +112,7 @@ public class AbandonOp implements BatchUpdateOp {
try { try {
ReplyToChangeSender cm = abandonedSenderFactory.create(ctx.getProject(), change.getId()); ReplyToChangeSender cm = abandonedSenderFactory.create(ctx.getProject(), change.getId());
if (accountState != null) { if (accountState != null) {
cm.setFrom(accountState.getAccount().id()); cm.setFrom(accountState.account().id());
} }
cm.setChangeMessage(message.getMessage(), ctx.getWhen()); cm.setChangeMessage(message.getMessage(), ctx.getWhen());
cm.setNotify(notify); cm.setNotify(notify);

View File

@@ -223,9 +223,8 @@ public class ChangeResource implements RestResource, HasETag {
} }
private void hashAccount(Hasher h, AccountState accountState, byte[] buf) { private void hashAccount(Hasher h, AccountState accountState, byte[] buf) {
h.putInt(accountState.getAccount().id().get()); h.putInt(accountState.account().id().get());
h.putString( h.putString(MoreObjects.firstNonNull(accountState.account().metaId(), ZERO_ID_STRING), UTF_8);
MoreObjects.firstNonNull(accountState.getAccount().metaId(), ZERO_ID_STRING), UTF_8); accountState.externalIds().stream().forEach(e -> hashObjectId(h, e.blobId(), buf));
accountState.getExternalIds().stream().forEach(e -> hashObjectId(h, e.blobId(), buf));
} }
} }

View File

@@ -108,7 +108,7 @@ public class DeleteReviewerOp implements BatchUpdateOp {
@Override @Override
public boolean updateChange(ChangeContext ctx) public boolean updateChange(ChangeContext ctx)
throws AuthException, ResourceNotFoundException, PermissionBackendException, IOException { throws AuthException, ResourceNotFoundException, PermissionBackendException, IOException {
Account.Id reviewerId = reviewer.getAccount().id(); Account.Id reviewerId = reviewer.account().id();
// Check of removing this reviewer (even if there is no vote processed by the loop below) is OK // Check of removing this reviewer (even if there is no vote processed by the loop below) is OK
removeReviewerControl.checkRemoveReviewer(ctx.getNotes(), ctx.getUser(), reviewerId); removeReviewerControl.checkRemoveReviewer(ctx.getNotes(), ctx.getUser(), reviewerId);
@@ -125,7 +125,7 @@ public class DeleteReviewerOp implements BatchUpdateOp {
} }
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
msg.append("Removed reviewer " + reviewer.getAccount().fullName()); msg.append("Removed reviewer " + reviewer.account().fullName());
StringBuilder removedVotesMsg = new StringBuilder(); StringBuilder removedVotesMsg = new StringBuilder();
removedVotesMsg.append(" with the following votes:\n\n"); removedVotesMsg.append(" with the following votes:\n\n");
List<PatchSetApproval> del = new ArrayList<>(); List<PatchSetApproval> del = new ArrayList<>();
@@ -212,13 +212,13 @@ public class DeleteReviewerOp implements BatchUpdateOp {
NotifyResolver.Result notify) NotifyResolver.Result notify)
throws EmailException { throws EmailException {
Account.Id userId = user.get().getAccountId(); Account.Id userId = user.get().getAccountId();
if (userId.equals(reviewer.getAccount().id())) { if (userId.equals(reviewer.account().id())) {
// The user knows they removed themselves, don't bother emailing them. // The user knows they removed themselves, don't bother emailing them.
return; return;
} }
DeleteReviewerSender cm = deleteReviewerSenderFactory.create(projectName, change.getId()); DeleteReviewerSender cm = deleteReviewerSenderFactory.create(projectName, change.getId());
cm.setFrom(userId); cm.setFrom(userId);
cm.addReviewers(Collections.singleton(reviewer.getAccount().id())); cm.addReviewers(Collections.singleton(reviewer.account().id()));
cm.setChangeMessage(changeMessage.getMessage(), changeMessage.getWrittenOn()); cm.setChangeMessage(changeMessage.getMessage(), changeMessage.getWrittenOn());
cm.setNotify(notify); cm.setNotify(notify);
cm.send(); cm.send();

View File

@@ -99,7 +99,7 @@ public class NotifyResolver {
List<String> problems = new ArrayList<>(inputs.size()); List<String> problems = new ArrayList<>(inputs.size());
for (String nameOrEmail : inputs) { for (String nameOrEmail : inputs) {
try { try {
r.add(accountResolver.resolve(nameOrEmail).asUnique().getAccount().id()); r.add(accountResolver.resolve(nameOrEmail).asUnique().account().id());
} catch (UnprocessableEntityException e) { } catch (UnprocessableEntityException e) {
problems.add(e.getMessage()); problems.add(e.getMessage());
} }

View File

@@ -571,9 +571,9 @@ public class EventFactory {
*/ */
public AccountAttribute asAccountAttribute(AccountState accountState) { public AccountAttribute asAccountAttribute(AccountState accountState) {
AccountAttribute who = new AccountAttribute(); AccountAttribute who = new AccountAttribute();
who.name = accountState.getAccount().fullName(); who.name = accountState.account().fullName();
who.email = accountState.getAccount().preferredEmail(); who.email = accountState.account().preferredEmail();
who.username = accountState.getUserName().orElse(null); who.username = accountState.userName().orElse(null);
return who; return who;
} }

View File

@@ -89,14 +89,14 @@ public class EventUtil {
} }
public AccountInfo accountInfo(AccountState accountState) { public AccountInfo accountInfo(AccountState accountState) {
if (accountState == null || accountState.getAccount().id() == null) { if (accountState == null || accountState.account().id() == null) {
return null; return null;
} }
Account account = accountState.getAccount(); Account account = accountState.account();
AccountInfo accountInfo = new AccountInfo(account.id().get()); AccountInfo accountInfo = new AccountInfo(account.id().get());
accountInfo.email = account.preferredEmail(); accountInfo.email = account.preferredEmail();
accountInfo.name = account.fullName(); accountInfo.name = account.fullName();
accountInfo.username = accountState.getUserName().orElse(null); accountInfo.username = accountState.userName().orElse(null);
return accountInfo; return accountInfo;
} }
@@ -106,8 +106,7 @@ public class EventUtil {
for (Map.Entry<String, Short> e : approvals.entrySet()) { for (Map.Entry<String, Short> e : approvals.entrySet()) {
Integer value = e.getValue() != null ? Integer.valueOf(e.getValue()) : null; Integer value = e.getValue() != null ? Integer.valueOf(e.getValue()) : null;
result.put( result.put(
e.getKey(), e.getKey(), new ApprovalInfo(accountState.account().id().get(), value, null, null, ts));
new ApprovalInfo(accountState.getAccount().id().get(), value, null, null, ts));
} }
return result; return result;
} }

View File

@@ -1578,10 +1578,10 @@ class ReceiveCommits {
this.cmd = cmd; this.cmd = cmd;
this.draft = cmd.getRefName().startsWith(MagicBranch.NEW_DRAFT_CHANGE); this.draft = cmd.getRefName().startsWith(MagicBranch.NEW_DRAFT_CHANGE);
this.labelTypes = labelTypes; this.labelTypes = labelTypes;
GeneralPreferencesInfo prefs = user.state().getGeneralPreferences(); GeneralPreferencesInfo prefs = user.state().generalPreferences();
this.defaultPublishComments = this.defaultPublishComments =
prefs != null prefs != null
? firstNonNull(user.state().getGeneralPreferences().publishCommentsOnPush, false) ? firstNonNull(user.state().generalPreferences().publishCommentsOnPush, false)
: false; : false;
} }
@@ -1696,7 +1696,7 @@ class ReceiveCommits {
} }
return projectState.is(BooleanProjectConfig.WORK_IN_PROGRESS_BY_DEFAULT) return projectState.is(BooleanProjectConfig.WORK_IN_PROGRESS_BY_DEFAULT)
|| firstNonNull(user.state().getGeneralPreferences().workInProgressByDefault, false); || firstNonNull(user.state().generalPreferences().workInProgressByDefault, false);
} }
NotifyResolver.Result getNotifyForNewChange() { NotifyResolver.Result getNotifyForNewChange() {

View File

@@ -544,7 +544,7 @@ public class ReplaceOp implements BatchUpdateOp {
try { try {
ReplacePatchSetSender cm = ReplacePatchSetSender cm =
replacePatchSetFactory.create(projectState.getNameKey(), notes.getChangeId()); replacePatchSetFactory.create(projectState.getNameKey(), notes.getChangeId());
cm.setFrom(ctx.getAccount().getAccount().id()); cm.setFrom(ctx.getAccount().account().id());
cm.setPatchSet(newPatchSet, info); cm.setPatchSet(newPatchSet, info);
cm.setChangeMessage(msg.getMessage(), ctx.getWhen()); cm.setChangeMessage(msg.getMessage(), ctx.getWhen());
cm.setNotify(ctx.getNotify(notes.getChangeId())); cm.setNotify(ctx.getNotify(notes.getChangeId()));

View File

@@ -51,7 +51,7 @@ public class AuditLogFormatter {
} }
private static Optional<Account> getAccount(AccountCache accountCache, Account.Id accountId) { private static Optional<Account> getAccount(AccountCache accountCache, Account.Id accountId) {
return accountCache.get(accountId).map(AccountState::getAccount); return accountCache.get(accountId).map(AccountState::account);
} }
private static Optional<GroupDescription.Basic> getGroup( private static Optional<GroupDescription.Basic> getGroup(

View File

@@ -44,7 +44,7 @@ import org.eclipse.jgit.lib.ObjectId;
/** Secondary index schemas for accounts. */ /** Secondary index schemas for accounts. */
public class AccountField { public class AccountField {
public static final FieldDef<AccountState, Integer> ID = public static final FieldDef<AccountState, Integer> ID =
integer("id").stored().build(a -> a.getAccount().id().get()); integer("id").stored().build(a -> a.account().id().get());
/** /**
* External IDs. * External IDs.
@@ -54,7 +54,7 @@ public class AccountField {
*/ */
public static final FieldDef<AccountState, Iterable<String>> EXTERNAL_ID = public static final FieldDef<AccountState, Iterable<String>> EXTERNAL_ID =
exact("external_id") exact("external_id")
.buildRepeatable(a -> Iterables.transform(a.getExternalIds(), id -> id.key().get())); .buildRepeatable(a -> Iterables.transform(a.externalIds(), id -> id.key().get()));
/** /**
* Fuzzy prefix match on name and email parts. * Fuzzy prefix match on name and email parts.
@@ -69,7 +69,7 @@ public class AccountField {
public static final FieldDef<AccountState, Iterable<String>> NAME_PART = public static final FieldDef<AccountState, Iterable<String>> NAME_PART =
prefix("name") prefix("name")
.buildRepeatable( .buildRepeatable(
a -> getNameParts(a, Iterables.transform(a.getExternalIds(), ExternalId::email))); a -> getNameParts(a, Iterables.transform(a.externalIds(), ExternalId::email)));
/** /**
* Fuzzy prefix match on name and preferred email parts. Parts of secondary emails are not * Fuzzy prefix match on name and preferred email parts. Parts of secondary emails are not
@@ -77,13 +77,13 @@ public class AccountField {
*/ */
public static final FieldDef<AccountState, Iterable<String>> NAME_PART_NO_SECONDARY_EMAIL = public static final FieldDef<AccountState, Iterable<String>> NAME_PART_NO_SECONDARY_EMAIL =
prefix("name2") prefix("name2")
.buildRepeatable(a -> getNameParts(a, Arrays.asList(a.getAccount().preferredEmail()))); .buildRepeatable(a -> getNameParts(a, Arrays.asList(a.account().preferredEmail())));
public static final FieldDef<AccountState, String> FULL_NAME = public static final FieldDef<AccountState, String> FULL_NAME =
exact("full_name").build(a -> a.getAccount().fullName()); exact("full_name").build(a -> a.account().fullName());
public static final FieldDef<AccountState, String> ACTIVE = public static final FieldDef<AccountState, String> ACTIVE =
exact("inactive").build(a -> a.getAccount().isActive() ? "1" : "0"); exact("inactive").build(a -> a.account().isActive() ? "1" : "0");
/** /**
* All emails (preferred email + secondary emails). Use this field only if the current user is * All emails (preferred email + secondary emails). Use this field only if the current user is
@@ -95,9 +95,9 @@ public class AccountField {
prefix("email") prefix("email")
.buildRepeatable( .buildRepeatable(
a -> a ->
FluentIterable.from(a.getExternalIds()) FluentIterable.from(a.externalIds())
.transform(ExternalId::email) .transform(ExternalId::email)
.append(Collections.singleton(a.getAccount().preferredEmail())) .append(Collections.singleton(a.account().preferredEmail()))
.filter(Objects::nonNull) .filter(Objects::nonNull)
.transform(String::toLowerCase) .transform(String::toLowerCase)
.toSet()); .toSet());
@@ -106,24 +106,24 @@ public class AccountField {
prefix("preferredemail") prefix("preferredemail")
.build( .build(
a -> { a -> {
String preferredEmail = a.getAccount().preferredEmail(); String preferredEmail = a.account().preferredEmail();
return preferredEmail != null ? preferredEmail.toLowerCase() : null; return preferredEmail != null ? preferredEmail.toLowerCase() : null;
}); });
public static final FieldDef<AccountState, String> PREFERRED_EMAIL_EXACT = public static final FieldDef<AccountState, String> PREFERRED_EMAIL_EXACT =
exact("preferredemail_exact").build(a -> a.getAccount().preferredEmail()); exact("preferredemail_exact").build(a -> a.account().preferredEmail());
public static final FieldDef<AccountState, Timestamp> REGISTERED = public static final FieldDef<AccountState, Timestamp> REGISTERED =
timestamp("registered").build(a -> a.getAccount().registeredOn()); timestamp("registered").build(a -> a.account().registeredOn());
public static final FieldDef<AccountState, String> USERNAME = public static final FieldDef<AccountState, String> USERNAME =
exact("username").build(a -> a.getUserName().map(String::toLowerCase).orElse("")); exact("username").build(a -> a.userName().map(String::toLowerCase).orElse(""));
public static final FieldDef<AccountState, Iterable<String>> WATCHED_PROJECT = public static final FieldDef<AccountState, Iterable<String>> WATCHED_PROJECT =
exact("watchedproject") exact("watchedproject")
.buildRepeatable( .buildRepeatable(
a -> a ->
FluentIterable.from(a.getProjectWatches().keySet()) FluentIterable.from(a.projectWatches().keySet())
.transform(k -> k.project().get()) .transform(k -> k.project().get())
.toSet()); .toSet());
@@ -138,14 +138,14 @@ public class AccountField {
storedOnly("ref_state") storedOnly("ref_state")
.buildRepeatable( .buildRepeatable(
a -> { a -> {
if (a.getAccount().metaId() == null) { if (a.account().metaId() == null) {
return ImmutableList.of(); return ImmutableList.of();
} }
return ImmutableList.of( return ImmutableList.of(
RefState.create( RefState.create(
RefNames.refsUsers(a.getAccount().id()), RefNames.refsUsers(a.account().id()),
ObjectId.fromString(a.getAccount().metaId())) ObjectId.fromString(a.account().metaId()))
// We use the default AllUsers name to avoid having to pass around that // We use the default AllUsers name to avoid having to pass around that
// variable just for indexing. // variable just for indexing.
// This field is only used for staleness detection which will discover the // This field is only used for staleness detection which will discover the
@@ -163,13 +163,13 @@ public class AccountField {
storedOnly("external_id_state") storedOnly("external_id_state")
.buildRepeatable( .buildRepeatable(
a -> a ->
a.getExternalIds().stream() a.externalIds().stream()
.filter(e -> e.blobId() != null) .filter(e -> e.blobId() != null)
.map(ExternalId::toByteArray) .map(ExternalId::toByteArray)
.collect(toSet())); .collect(toSet()));
private static final Set<String> getNameParts(AccountState a, Iterable<String> emails) { private static final Set<String> getNameParts(AccountState a, Iterable<String> emails) {
String fullName = a.getAccount().fullName(); String fullName = a.account().fullName();
Set<String> parts = SchemaUtil.getNameParts(fullName, emails); Set<String> parts = SchemaUtil.getNameParts(fullName, emails);
// Additional values not currently added by getPersonParts. // Additional values not currently added by getPersonParts.

View File

@@ -62,7 +62,7 @@ public class MailUtil {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private static Account.Id toAccountId(AccountResolver accountResolver, String nameOrEmail) private static Account.Id toAccountId(AccountResolver accountResolver, String nameOrEmail)
throws UnprocessableEntityException, IOException, ConfigInvalidException { throws UnprocessableEntityException, IOException, ConfigInvalidException {
return accountResolver.resolveByNameOrEmail(nameOrEmail).asUnique().getAccount().id(); return accountResolver.resolveByNameOrEmail(nameOrEmail).asUnique().account().id();
} }
private static boolean isReviewer(FooterLine candidateFooterLine) { private static boolean isReviewer(FooterLine candidateFooterLine) {

View File

@@ -205,7 +205,7 @@ public class MailProcessor {
logger.atWarning().log("Mail: Account %s doesn't exist. Will delete message.", accountId); logger.atWarning().log("Mail: Account %s doesn't exist. Will delete message.", accountId);
return; return;
} }
if (!accountState.get().getAccount().isActive()) { if (!accountState.get().account().isActive()) {
logger.atWarning().log("Mail: Account %s is inactive. Will delete message.", accountId); logger.atWarning().log("Mail: Account %s is inactive. Will delete message.", accountId);
sendRejectionEmail(message, InboundEmailRejectionSender.Error.INACTIVE_ACCOUNT); sendRejectionEmail(message, InboundEmailRejectionSender.Error.INACTIVE_ACCOUNT);
return; return;

View File

@@ -334,7 +334,7 @@ public abstract class ChangeEmail extends NotificationEmail {
protected void removeUsersThatIgnoredTheChange() { protected void removeUsersThatIgnoredTheChange() {
for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) { for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) {
if (e.getValue().contains(StarredChangesUtil.IGNORE_LABEL)) { if (e.getValue().contains(StarredChangesUtil.IGNORE_LABEL)) {
args.accountCache.get(e.getKey()).ifPresent(a -> removeUser(a.getAccount())); args.accountCache.get(e.getKey()).ifPresent(a -> removeUser(a.account()));
} }
} }
} }

View File

@@ -123,7 +123,7 @@ public class FromAddressGeneratorProvider implements Provider<FromAddressGenerat
public Address from(Account.Id fromId) { public Address from(Account.Id fromId) {
String senderName; String senderName;
if (fromId != null) { if (fromId != null) {
Optional<Account> a = accountCache.get(fromId).map(AccountState::getAccount); Optional<Account> a = accountCache.get(fromId).map(AccountState::account);
String fullName = a.map(Account::fullName).orElse(null); String fullName = a.map(Account::fullName).orElse(null);
String userEmail = a.map(Account::preferredEmail).orElse(null); String userEmail = a.map(Account::preferredEmail).orElse(null);
if (canRelay(userEmail)) { if (canRelay(userEmail)) {
@@ -208,7 +208,7 @@ public class FromAddressGeneratorProvider implements Provider<FromAddressGenerat
final String senderName; final String senderName;
if (fromId != null) { if (fromId != null) {
String fullName = accountCache.get(fromId).map(a -> a.getAccount().fullName()).orElse(null); String fullName = accountCache.get(fromId).map(a -> a.account().fullName()).orElse(null);
if (fullName == null || "".equals(fullName)) { if (fullName == null || "".equals(fullName)) {
fullName = anonymousCowardName; fullName = anonymousCowardName;
} }

View File

@@ -116,7 +116,7 @@ public abstract class OutgoingEmail {
if (fromId != null) { if (fromId != null) {
Optional<AccountState> fromUser = args.accountCache.get(fromId); Optional<AccountState> fromUser = args.accountCache.get(fromId);
if (fromUser.isPresent()) { if (fromUser.isPresent()) {
GeneralPreferencesInfo senderPrefs = fromUser.get().getGeneralPreferences(); GeneralPreferencesInfo senderPrefs = fromUser.get().generalPreferences();
if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) { if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
// If we are impersonating a user, make sure they receive a CC of // If we are impersonating a user, make sure they receive a CC of
// this message so they can always review and audit what we sent // this message so they can always review and audit what we sent
@@ -127,7 +127,7 @@ public abstract class OutgoingEmail {
// If they don't want a copy, but we queued one up anyway, // If they don't want a copy, but we queued one up anyway,
// drop them from the recipient lists. // drop them from the recipient lists.
// //
removeUser(fromUser.get().getAccount()); removeUser(fromUser.get().account());
} }
} }
} }
@@ -137,8 +137,8 @@ public abstract class OutgoingEmail {
for (Account.Id id : rcptTo) { for (Account.Id id : rcptTo) {
Optional<AccountState> thisUser = args.accountCache.get(id); Optional<AccountState> thisUser = args.accountCache.get(id);
if (thisUser.isPresent()) { if (thisUser.isPresent()) {
Account thisUserAccount = thisUser.get().getAccount(); Account thisUserAccount = thisUser.get().account();
GeneralPreferencesInfo prefs = thisUser.get().getGeneralPreferences(); GeneralPreferencesInfo prefs = thisUser.get().generalPreferences();
if (prefs == null || prefs.getEmailStrategy() == DISABLED) { if (prefs == null || prefs.getEmailStrategy() == DISABLED) {
removeUser(thisUserAccount); removeUser(thisUserAccount);
} else if (useHtml() && prefs.getEmailFormat() == EmailFormat.PLAINTEXT) { } else if (useHtml() && prefs.getEmailFormat() == EmailFormat.PLAINTEXT) {
@@ -248,7 +248,7 @@ public abstract class OutgoingEmail {
protected String getFromLine() { protected String getFromLine() {
StringBuilder f = new StringBuilder(); StringBuilder f = new StringBuilder();
Optional<Account> account = args.accountCache.get(fromId).map(AccountState::getAccount); Optional<Account> account = args.accountCache.get(fromId).map(AccountState::account);
if (account.isPresent()) { if (account.isPresent()) {
String name = account.get().fullName(); String name = account.get().fullName();
String email = account.get().preferredEmail(); String email = account.get().preferredEmail();
@@ -324,7 +324,7 @@ public abstract class OutgoingEmail {
return args.gerritPersonIdent.getName(); return args.gerritPersonIdent.getName();
} }
Optional<Account> account = args.accountCache.get(accountId).map(AccountState::getAccount); Optional<Account> account = args.accountCache.get(accountId).map(AccountState::account);
String name = null; String name = null;
if (account.isPresent()) { if (account.isPresent()) {
name = account.get().fullName(); name = account.get().fullName();
@@ -346,7 +346,7 @@ public abstract class OutgoingEmail {
* @return name/email of account, or Anonymous Coward if unset. * @return name/email of account, or Anonymous Coward if unset.
*/ */
protected String getNameEmailFor(Account.Id accountId) { protected String getNameEmailFor(Account.Id accountId) {
Optional<Account> account = args.accountCache.get(accountId).map(AccountState::getAccount); Optional<Account> account = args.accountCache.get(accountId).map(AccountState::account);
if (account.isPresent()) { if (account.isPresent()) {
String name = account.get().fullName(); String name = account.get().fullName();
String email = account.get().preferredEmail(); String email = account.get().preferredEmail();
@@ -374,7 +374,7 @@ public abstract class OutgoingEmail {
return null; return null;
} }
Account account = accountState.get().getAccount(); Account account = accountState.get().account();
String name = account.fullName(); String name = account.fullName();
String email = account.preferredEmail(); String email = account.preferredEmail();
if (name != null && email != null) { if (name != null && email != null) {
@@ -384,7 +384,7 @@ public abstract class OutgoingEmail {
} else if (name != null) { } else if (name != null) {
return name; return name;
} }
return accountState.get().getUserName().orElse(null); return accountState.get().userName().orElse(null);
} }
protected boolean shouldSendMessage() { protected boolean shouldSendMessage() {
@@ -505,7 +505,7 @@ public abstract class OutgoingEmail {
} }
private Address toAddress(Account.Id id) { private Address toAddress(Account.Id id) {
Optional<Account> accountState = args.accountCache.get(id).map(AccountState::getAccount); Optional<Account> accountState = args.accountCache.get(id).map(AccountState::account);
if (!accountState.isPresent()) { if (!accountState.isPresent()) {
return null; return null;
} }

View File

@@ -66,9 +66,8 @@ public class ProjectWatch {
Set<Account.Id> projectWatchers = new HashSet<>(); Set<Account.Id> projectWatchers = new HashSet<>();
for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) { for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) {
Account.Id accountId = a.getAccount().id(); Account.Id accountId = a.account().id();
for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyType>> e : for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyType>> e : a.projectWatches().entrySet()) {
a.getProjectWatches().entrySet()) {
if (project.equals(e.getKey().project()) if (project.equals(e.getKey().project())
&& add(matching, accountId, e.getKey(), e.getValue(), type)) { && add(matching, accountId, e.getKey(), e.getValue(), type)) {
// We only want to prevent matching All-Projects if this filter hits // We only want to prevent matching All-Projects if this filter hits
@@ -78,10 +77,9 @@ public class ProjectWatch {
} }
for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) { for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) {
for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyType>> e : for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyType>> e : a.projectWatches().entrySet()) {
a.getProjectWatches().entrySet()) {
if (args.allProjectsName.equals(e.getKey().project())) { if (args.allProjectsName.equals(e.getKey().project())) {
Account.Id accountId = a.getAccount().id(); Account.Id accountId = a.account().id();
if (!projectWatchers.contains(accountId)) { if (!projectWatchers.contains(accountId)) {
add(matching, accountId, e.getKey(), e.getValue(), type); add(matching, accountId, e.getKey(), e.getValue(), type);
} }

View File

@@ -77,6 +77,6 @@ public class AccountQueryProcessor extends QueryProcessor<AccountState> {
@Override @Override
protected String formatForLogging(AccountState accountState) { protected String formatForLogging(AccountState accountState) {
return accountState.getAccount().id().toString(); return accountState.account().id().toString();
} }
} }

View File

@@ -37,7 +37,7 @@ public class CanSeeChangePredicate extends PostFilterPredicate<AccountState> {
public boolean match(AccountState accountState) { public boolean match(AccountState accountState) {
try { try {
permissionBackend permissionBackend
.absentUser(accountState.getAccount().id()) .absentUser(accountState.account().id())
.change(changeNotes) .change(changeNotes)
.check(ChangePermission.READ); .check(ChangePermission.READ);
return true; return true;

View File

@@ -76,8 +76,7 @@ public class InternalAccountQuery extends InternalQuery<AccountState, InternalAc
msg.append("Ambiguous external ID ").append(externalId).append(" for accounts: "); msg.append("Ambiguous external ID ").append(externalId).append(" for accounts: ");
Joiner.on(", ") Joiner.on(", ")
.appendTo( .appendTo(
msg, msg, accountStates.stream().map(a -> a.account().id().toString()).collect(toList()));
accountStates.stream().map(a -> a.getAccount().id().toString()).collect(toList()));
logger.atWarning().log(msg.toString()); logger.atWarning().log(msg.toString());
} }
return null; return null;
@@ -103,7 +102,7 @@ public class InternalAccountQuery extends InternalQuery<AccountState, InternalAc
} }
return query(AccountPredicates.preferredEmail(email)).stream() return query(AccountPredicates.preferredEmail(email)).stream()
.filter(a -> a.getAccount().preferredEmail().equals(email)) .filter(a -> a.account().preferredEmail().equals(email))
.collect(toList()); .collect(toList());
} }
@@ -136,7 +135,7 @@ public class InternalAccountQuery extends InternalQuery<AccountState, InternalAc
String email = emails.get(i); String email = emails.get(i);
Set<AccountState> matchingAccounts = Set<AccountState> matchingAccounts =
r.get(i).stream() r.get(i).stream()
.filter(a -> a.getAccount().preferredEmail().equals(email)) .filter(a -> a.account().preferredEmail().equals(email))
.collect(toSet()); .collect(toSet());
accountsByEmail.putAll(email, matchingAccounts); accountsByEmail.putAll(email, matchingAccounts);
} }

View File

@@ -93,7 +93,7 @@ public class IsWatchedByPredicate extends AndPredicate<ChangeData> {
throws QueryParseException { throws QueryParseException {
CurrentUser user = args.getUser(); CurrentUser user = args.getUser();
if (user.isIdentifiedUser()) { if (user.isIdentifiedUser()) {
return user.asIdentifiedUser().state().getProjectWatches().keySet(); return user.asIdentifiedUser().state().projectWatches().keySet();
} }
return Collections.emptySet(); return Collections.emptySet();
} }

View File

@@ -59,7 +59,7 @@ public class GetDiffPreferences implements RestReadView<AccountResource> {
return Response.ok( return Response.ok(
accountCache accountCache
.get(id) .get(id)
.map(AccountState::getDiffPreferences) .map(AccountState::diffPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))));
} }
} }

View File

@@ -59,7 +59,7 @@ public class GetEditPreferences implements RestReadView<AccountResource> {
return Response.ok( return Response.ok(
accountCache accountCache
.get(id) .get(id)
.map(AccountState::getEditPreferences) .map(AccountState::editPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))));
} }
} }

View File

@@ -65,7 +65,7 @@ public class GetPreferences implements RestReadView<AccountResource> {
GeneralPreferencesInfo preferencesInfo = GeneralPreferencesInfo preferencesInfo =
accountCache accountCache
.get(id) .get(id)
.map(AccountState::getGeneralPreferences) .map(AccountState::generalPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())));
return Response.ok(unsetDownloadSchemeIfUnsupported(preferencesInfo)); return Response.ok(unsetDownloadSchemeIfUnsupported(preferencesInfo));
} }

View File

@@ -66,7 +66,7 @@ public class GetWatchedProjects implements RestReadView<AccountResource> {
Account.Id accountId = rsrc.getUser().getAccountId(); Account.Id accountId = rsrc.getUser().getAccountId();
AccountState account = accounts.get(accountId).orElseThrow(ResourceNotFoundException::new); AccountState account = accounts.get(accountId).orElseThrow(ResourceNotFoundException::new);
return Response.ok( return Response.ok(
account.getProjectWatches().entrySet().stream() account.projectWatches().entrySet().stream()
.map(e -> toProjectWatchInfo(e.getKey(), e.getValue())) .map(e -> toProjectWatchInfo(e.getKey(), e.getValue()))
.sorted( .sorted(
comparing((ProjectWatchInfo pwi) -> pwi.project) comparing((ProjectWatchInfo pwi) -> pwi.project)

View File

@@ -93,7 +93,7 @@ public class PutAgreement implements RestModifyView<AccountResource, AgreementIn
AccountState accountState = self.get().state(); AccountState accountState = self.get().state();
try { try {
addMembers.addMembers(uuid, ImmutableSet.of(accountState.getAccount().id())); addMembers.addMembers(uuid, ImmutableSet.of(accountState.account().id()));
} catch (NoSuchGroupException e) { } catch (NoSuchGroupException e) {
throw new ResourceConflictException("autoverify group not found"); throw new ResourceConflictException("autoverify group not found");
} }

View File

@@ -84,8 +84,8 @@ public class PutName implements RestModifyView<AccountResource, NameInput> {
.get() .get()
.update("Set Full Name via API", user.getAccountId(), u -> u.setFullName(newName)) .update("Set Full Name via API", user.getAccountId(), u -> u.setFullName(newName))
.orElseThrow(() -> new ResourceNotFoundException("account not found")); .orElseThrow(() -> new ResourceNotFoundException("account not found"));
return Strings.isNullOrEmpty(accountState.getAccount().fullName()) return Strings.isNullOrEmpty(accountState.account().fullName())
? Response.none() ? Response.none()
: Response.ok(accountState.getAccount().fullName()); : Response.ok(accountState.account().fullName());
} }
} }

View File

@@ -85,13 +85,13 @@ public class PutPreferred implements RestModifyView<AccountResource.Email, Input
"Set Preferred Email via API", "Set Preferred Email via API",
user.getAccountId(), user.getAccountId(),
(a, u) -> { (a, u) -> {
if (preferredEmail.equals(a.getAccount().preferredEmail())) { if (preferredEmail.equals(a.account().preferredEmail())) {
alreadyPreferred.set(true); alreadyPreferred.set(true);
} else { } else {
// check if the user has a matching email // check if the user has a matching email
String matchingEmail = null; String matchingEmail = null;
for (String email : for (String email :
a.getExternalIds().stream() a.externalIds().stream()
.map(ExternalId::email) .map(ExternalId::email)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(toSet())) { .collect(toSet())) {
@@ -128,7 +128,7 @@ public class PutPreferred implements RestModifyView<AccountResource.Email, Input
} }
// claim the email now // claim the email now
u.addExternalId(ExternalId.createEmail(a.getAccount().id(), preferredEmail)); u.addExternalId(ExternalId.createEmail(a.account().id(), preferredEmail));
matchingEmail = preferredEmail; matchingEmail = preferredEmail;
} else { } else {
// Realm says that the email doesn't belong to the user. This can only happen as // Realm says that the email doesn't belong to the user. This can only happen as

View File

@@ -73,8 +73,8 @@ public class PutStatus implements RestModifyView<AccountResource, StatusInput> {
.get() .get()
.update("Set Status via API", user.getAccountId(), u -> u.setStatus(newStatus)) .update("Set Status via API", user.getAccountId(), u -> u.setStatus(newStatus))
.orElseThrow(() -> new ResourceNotFoundException("account not found")); .orElseThrow(() -> new ResourceNotFoundException("account not found"));
return Strings.isNullOrEmpty(accountState.getAccount().status()) return Strings.isNullOrEmpty(accountState.account().status())
? Response.none() ? Response.none()
: Response.ok(accountState.getAccount().status()); : Response.ok(accountState.account().status());
} }
} }

View File

@@ -210,7 +210,7 @@ public class QueryAccounts implements RestReadView<TopLevelResource> {
} }
QueryResult<AccountState> result = queryProcessor.query(queryPred); QueryResult<AccountState> result = queryProcessor.query(queryPred);
for (AccountState accountState : result.entities()) { for (AccountState accountState : result.entities()) {
Account.Id id = accountState.getAccount().id(); Account.Id id = accountState.account().id();
matches.put(id, accountLoader.get(id)); matches.put(id, accountLoader.get(id));
} }

View File

@@ -70,7 +70,7 @@ public class SetDiffPreferences implements RestModifyView<AccountResource, DiffP
accountsUpdateProvider accountsUpdateProvider
.get() .get()
.update("Set Diff Preferences via API", id, u -> u.setDiffPreferences(input)) .update("Set Diff Preferences via API", id, u -> u.setDiffPreferences(input))
.map(AccountState::getDiffPreferences) .map(AccountState::diffPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))));
} }
} }

View File

@@ -71,7 +71,7 @@ public class SetEditPreferences implements RestModifyView<AccountResource, EditP
accountsUpdateProvider accountsUpdateProvider
.get() .get()
.update("Set Edit Preferences via API", id, u -> u.setEditPreferences(input)) .update("Set Edit Preferences via API", id, u -> u.setEditPreferences(input))
.map(AccountState::getEditPreferences) .map(AccountState::editPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))));
} }
} }

View File

@@ -75,7 +75,7 @@ public class SetPreferences implements RestModifyView<AccountResource, GeneralPr
accountsUpdateProvider accountsUpdateProvider
.get() .get()
.update("Set General Preferences via API", id, u -> u.setGeneralPreferences(input)) .update("Set General Preferences via API", id, u -> u.setGeneralPreferences(input))
.map(AccountState::getGeneralPreferences) .map(AccountState::generalPreferences)
.orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString())))); .orElseThrow(() -> new ResourceNotFoundException(IdString.fromDecoded(id.toString()))));
} }

View File

@@ -258,7 +258,7 @@ public class CreateChange
input.workInProgress = true; input.workInProgress = true;
} else { } else {
input.workInProgress = input.workInProgress =
firstNonNull(me.state().getGeneralPreferences().workInProgressByDefault, false); firstNonNull(me.state().generalPreferences().workInProgressByDefault, false);
} }
} }
@@ -426,15 +426,14 @@ public class CreateChange
commitMessage = ChangeIdUtil.insertId(commitMessage, id); commitMessage = ChangeIdUtil.insertId(commitMessage, id);
} }
if (Boolean.TRUE.equals(me.state().getGeneralPreferences().signedOffBy)) { if (Boolean.TRUE.equals(me.state().generalPreferences().signedOffBy)) {
commitMessage = commitMessage =
Joiner.on("\n") Joiner.on("\n")
.join( .join(
commitMessage.trim(), commitMessage.trim(),
String.format( String.format(
"%s%s", "%s%s",
SIGNED_OFF_BY_TAG, SIGNED_OFF_BY_TAG, me.state().account().getNameEmail(anonymousCowardName)));
me.state().getAccount().getNameEmail(anonymousCowardName)));
} }
return commitMessage; return commitMessage;

View File

@@ -104,7 +104,7 @@ public class DeleteAssignee extends RetryingRestModifyView<ChangeResource, Input
} }
public Account.Id getDeletedAssignee() { public Account.Id getDeletedAssignee() {
return deletedAssignee != null ? deletedAssignee.getAccount().id() : null; return deletedAssignee != null ? deletedAssignee.account().id() : null;
} }
private void addMessage( private void addMessage(

View File

@@ -170,7 +170,7 @@ public class DeleteVote extends RetryingRestModifyView<VoteResource, DeleteVoteI
boolean found = false; boolean found = false;
LabelTypes labelTypes = projectState.getLabelTypes(ctx.getNotes()); LabelTypes labelTypes = projectState.getLabelTypes(ctx.getNotes());
Account.Id accountId = accountState.getAccount().id(); Account.Id accountId = accountState.account().id();
for (PatchSetApproval a : for (PatchSetApproval a :
approvalsUtil.byPatchSetUser( approvalsUtil.byPatchSetUser(

View File

@@ -146,7 +146,7 @@ public class AddMembers implements RestModifyView<GroupResource, Input> {
throws UnprocessableEntityException, IOException, ConfigInvalidException { throws UnprocessableEntityException, IOException, ConfigInvalidException {
AccountResolver.Result result = accountResolver.resolve(nameOrEmailOrId); AccountResolver.Result result = accountResolver.resolve(nameOrEmailOrId);
try { try {
return result.asUnique().getAccount(); return result.asUnique().account();
} catch (UnresolvableAccountException e) { } catch (UnresolvableAccountException e) {
switch (authType) { switch (authType) {
case HTTP_LDAP: case HTTP_LDAP:
@@ -193,7 +193,7 @@ public class AddMembers implements RestModifyView<GroupResource, Input> {
req.setSkipAuthentication(true); req.setSkipAuthentication(true);
return accountCache return accountCache
.get(accountManager.authenticate(req).getAccountId()) .get(accountManager.authenticate(req).getAccountId())
.map(AccountState::getAccount); .map(AccountState::account);
} catch (AccountException e) { } catch (AccountException e) {
return Optional.empty(); return Optional.empty();
} }

View File

@@ -68,7 +68,7 @@ public class DeleteMembers implements RestModifyView<GroupResource, Input> {
Set<Account.Id> membersToRemove = new HashSet<>(); Set<Account.Id> membersToRemove = new HashSet<>();
for (String nameOrEmail : input.members) { for (String nameOrEmail : input.members) {
membersToRemove.add(accountResolver.resolve(nameOrEmail).asUnique().getAccount().id()); membersToRemove.add(accountResolver.resolve(nameOrEmail).asUnique().account().id());
} }
AccountGroup.UUID groupUuid = internalGroup.getGroupUUID(); AccountGroup.UUID groupUuid = internalGroup.getGroupUUID();
try { try {

View File

@@ -73,7 +73,7 @@ public class CheckAccess implements RestModifyView<ProjectResource, AccessCheckI
throw new BadRequestException("input requires 'account'"); throw new BadRequestException("input requires 'account'");
} }
Account.Id match = accountResolver.resolve(input.account).asUnique().getAccount().id(); Account.Id match = accountResolver.resolve(input.account).asUnique().account().id();
AccessCheckInfo info = new AccessCheckInfo(); AccessCheckInfo info = new AccessCheckInfo();
try { try {

View File

@@ -396,7 +396,7 @@ abstract class SubmitStrategyOp implements BatchUpdateOp {
private String getByAccountName() { private String getByAccountName() {
requireNonNull(submitter, "getByAccountName called before submitter populated"); requireNonNull(submitter, "getByAccountName called before submitter populated");
Optional<Account> account = Optional<Account> account =
args.accountCache.get(submitter.accountId()).map(AccountState::getAccount); args.accountCache.get(submitter.accountId()).map(AccountState::account);
if (account.isPresent() && account.get().fullName() != null) { if (account.isPresent() && account.get().fullName() != null) {
return " by " + account.get().fullName(); return " by " + account.get().fullName();
} }

View File

@@ -114,7 +114,7 @@ public interface Context {
/** /**
* Get the account of the user performing the update. * Get the account of the user performing the update.
* *
* <p>Convenience method for {@code getIdentifiedUser().getAccount()}. * <p>Convenience method for {@code getIdentifiedUser().account()}.
* *
* @see CurrentUser#asIdentifiedUser() * @see CurrentUser#asIdentifiedUser()
* @return account. * @return account.

View File

@@ -66,7 +66,7 @@ class GerritGSSAuthenticator extends GSSAuthenticator {
} }
Optional<Account> account = Optional<Account> account =
accounts.getByUsername(username).map(AccountState::getAccount).filter(Account::isActive); accounts.getByUsername(username).map(AccountState::account).filter(Account::isActive);
if (!account.isPresent()) { if (!account.isPresent()) {
return false; return false;
} }

View File

@@ -76,7 +76,7 @@ public class LsUserRefs extends SshCommand {
protected void run() throws Failure { protected void run() throws Failure {
Account.Id userAccountId; Account.Id userAccountId;
try { try {
userAccountId = accountResolver.resolve(userName).asUnique().getAccount().id(); userAccountId = accountResolver.resolve(userName).asUnique().account().id();
} catch (UnprocessableEntityException e) { } catch (UnprocessableEntityException e) {
stdout.println(e.getMessage()); stdout.println(e.getMessage());
stdout.flush(); stdout.flush();

View File

@@ -140,7 +140,7 @@ public class SetMembersCommand extends SshCommand {
return "n/a"; return "n/a";
} }
return MoreObjects.firstNonNull( return MoreObjects.firstNonNull(
accountState.get().getAccount().preferredEmail(), "n/a"); accountState.get().account().preferredEmail(), "n/a");
}) })
.collect(joining(", ")); .collect(joining(", "));
out.write( out.write(

View File

@@ -433,7 +433,7 @@ public class AccountIT extends AbstractDaemonTest {
"Create Account Atomically", "Create Account Atomically",
accountId, accountId,
u -> u.setFullName(fullName).addExternalId(extId)); u -> u.setFullName(fullName).addExternalId(extId));
assertThat(accountState.getAccount().fullName()).isEqualTo(fullName); assertThat(accountState.account().fullName()).isEqualTo(fullName);
AccountInfo info = gApi.accounts().id(accountId.get()).get(); AccountInfo info = gApi.accounts().id(accountId.get()).get();
assertThat(info.name).isEqualTo(fullName); assertThat(info.name).isEqualTo(fullName);
@@ -473,7 +473,7 @@ public class AccountIT extends AbstractDaemonTest {
.get() .get()
.update("Set status", anonymousCoward.id(), u -> u.setStatus(status)); .update("Set status", anonymousCoward.id(), u -> u.setStatus(status));
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
Account account = accountState.get().getAccount(); Account account = accountState.get().account();
assertThat(account.fullName()).isNull(); assertThat(account.fullName()).isNull();
assertThat(account.status()).isEqualTo(status); assertThat(account.status()).isEqualTo(status);
assertUserBranch(anonymousCoward.id(), null, status); assertUserBranch(anonymousCoward.id(), null, status);
@@ -596,7 +596,7 @@ public class AccountIT extends AbstractDaemonTest {
new AccountActivationValidationListener() { new AccountActivationValidationListener() {
@Override @Override
public void validateActivation(AccountState account) throws ValidationException { public void validateActivation(AccountState account) throws ValidationException {
String preferredEmail = account.getAccount().preferredEmail(); String preferredEmail = account.account().preferredEmail();
if (preferredEmail == null || !preferredEmail.endsWith("@activatable.com")) { if (preferredEmail == null || !preferredEmail.endsWith("@activatable.com")) {
throw new ValidationException("not allowed to active account"); throw new ValidationException("not allowed to active account");
} }
@@ -604,7 +604,7 @@ public class AccountIT extends AbstractDaemonTest {
@Override @Override
public void validateDeactivation(AccountState account) throws ValidationException { public void validateDeactivation(AccountState account) throws ValidationException {
String preferredEmail = account.getAccount().preferredEmail(); String preferredEmail = account.account().preferredEmail();
if (preferredEmail == null || !preferredEmail.endsWith("@deactivatable.com")) { if (preferredEmail == null || !preferredEmail.endsWith("@deactivatable.com")) {
throw new ValidationException("not allowed to deactive account"); throw new ValidationException("not allowed to deactive account");
} }
@@ -2461,21 +2461,20 @@ public class AccountIT extends AbstractDaemonTest {
@Test @Test
public void checkMetaId() throws Exception { public void checkMetaId() throws Exception {
// metaId is set when account is loaded // metaId is set when account is loaded
assertThat(accounts.get(admin.id()).get().getAccount().metaId()) assertThat(accounts.get(admin.id()).get().account().metaId()).isEqualTo(getMetaId(admin.id()));
.isEqualTo(getMetaId(admin.id()));
// metaId is set when account is created // metaId is set when account is created
AccountsUpdate au = accountsUpdateProvider.get(); AccountsUpdate au = accountsUpdateProvider.get();
Account.Id accountId = Account.id(seq.nextAccountId()); Account.Id accountId = Account.id(seq.nextAccountId());
AccountState accountState = au.insert("Create Test Account", accountId, u -> {}); AccountState accountState = au.insert("Create Test Account", accountId, u -> {});
assertThat(accountState.getAccount().metaId()).isEqualTo(getMetaId(accountId)); assertThat(accountState.account().metaId()).isEqualTo(getMetaId(accountId));
// metaId is set when account is updated // metaId is set when account is updated
Optional<AccountState> updatedAccountState = Optional<AccountState> updatedAccountState =
au.update("Set Full Name", accountId, u -> u.setFullName("foo")); au.update("Set Full Name", accountId, u -> u.setFullName("foo"));
assertThat(updatedAccountState).isPresent(); assertThat(updatedAccountState).isPresent();
Account updatedAccount = updatedAccountState.get().getAccount(); Account updatedAccount = updatedAccountState.get().account();
assertThat(accountState.getAccount().metaId()).isNotEqualTo(updatedAccount.metaId()); assertThat(accountState.account().metaId()).isNotEqualTo(updatedAccount.metaId());
assertThat(updatedAccount.metaId()).isEqualTo(getMetaId(accountId)); assertThat(updatedAccount.metaId()).isEqualTo(getMetaId(accountId));
} }
@@ -2621,7 +2620,7 @@ public class AccountIT extends AbstractDaemonTest {
assertThat(doneBgUpdate.get()).isTrue(); assertThat(doneBgUpdate.get()).isTrue();
assertThat(updatedAccountState).isPresent(); assertThat(updatedAccountState).isPresent();
Account updatedAccount = updatedAccountState.get().getAccount(); Account updatedAccount = updatedAccountState.get().account();
assertThat(updatedAccount.status()).isEqualTo(status); assertThat(updatedAccount.status()).isEqualTo(status);
assertThat(updatedAccount.fullName()).isEqualTo(fullName); assertThat(updatedAccount.fullName()).isEqualTo(fullName);
@@ -2678,7 +2677,7 @@ public class AccountIT extends AbstractDaemonTest {
() -> update.update("Set Full Name", admin.id(), u -> u.setFullName(fullName))); () -> update.update("Set Full Name", admin.id(), u -> u.setFullName(fullName)));
assertThat(bgCounter.get()).isEqualTo(status.size()); assertThat(bgCounter.get()).isEqualTo(status.size());
Account updatedAccount = accounts.get(admin.id()).get().getAccount(); Account updatedAccount = accounts.get(admin.id()).get().account();
assertThat(updatedAccount.status()).isEqualTo(Iterables.getLast(status)); assertThat(updatedAccount.status()).isEqualTo(Iterables.getLast(status));
assertThat(updatedAccount.fullName()).isEqualTo(admin.fullName()); assertThat(updatedAccount.fullName()).isEqualTo(admin.fullName());
@@ -2730,12 +2729,12 @@ public class AccountIT extends AbstractDaemonTest {
"Set Status", "Set Status",
admin.id(), admin.id(),
(a, u) -> { (a, u) -> {
if ("A-1".equals(a.getAccount().status())) { if ("A-1".equals(a.account().status())) {
bgCounterA1.getAndIncrement(); bgCounterA1.getAndIncrement();
u.setStatus("B-1"); u.setStatus("B-1");
} }
if ("A-2".equals(a.getAccount().status())) { if ("A-2".equals(a.account().status())) {
bgCounterA2.getAndIncrement(); bgCounterA2.getAndIncrement();
u.setStatus("B-2"); u.setStatus("B-2");
} }
@@ -2745,8 +2744,8 @@ public class AccountIT extends AbstractDaemonTest {
assertThat(bgCounterA2.get()).isEqualTo(1); assertThat(bgCounterA2.get()).isEqualTo(1);
assertThat(updatedAccountState).isPresent(); assertThat(updatedAccountState).isPresent();
assertThat(updatedAccountState.get().getAccount().status()).isEqualTo("B-2"); assertThat(updatedAccountState.get().account().status()).isEqualTo("B-2");
assertThat(accounts.get(admin.id()).get().getAccount().status()).isEqualTo("B-2"); assertThat(accounts.get(admin.id()).get().account().status()).isEqualTo("B-2");
assertThat(gApi.accounts().id(admin.id().get()).get().status).isEqualTo("B-2"); assertThat(gApi.accounts().id(admin.id().get()).get().status).isEqualTo("B-2");
} }
@@ -2812,12 +2811,12 @@ public class AccountIT extends AbstractDaemonTest {
"Update External ID", "Update External ID",
accountId, accountId,
(a, u) -> { (a, u) -> {
if (a.getExternalIds().contains(extIdA1)) { if (a.externalIds().contains(extIdA1)) {
bgCounterA1.getAndIncrement(); bgCounterA1.getAndIncrement();
u.replaceExternalId(extIdA1, extIdB1); u.replaceExternalId(extIdA1, extIdB1);
} }
if (a.getExternalIds().contains(extIdA2)) { if (a.externalIds().contains(extIdA2)) {
bgCounterA2.getAndIncrement(); bgCounterA2.getAndIncrement();
u.replaceExternalId(extIdA2, extIdB2); u.replaceExternalId(extIdA2, extIdB2);
} }
@@ -2827,8 +2826,8 @@ public class AccountIT extends AbstractDaemonTest {
assertThat(bgCounterA2.get()).isEqualTo(1); assertThat(bgCounterA2.get()).isEqualTo(1);
assertThat(updatedAccount).isPresent(); assertThat(updatedAccount).isPresent();
assertThat(updatedAccount.get().getExternalIds()).containsExactly(extIdB2); assertThat(updatedAccount.get().externalIds()).containsExactly(extIdB2);
assertThat(accounts.get(accountId).get().getExternalIds()).containsExactly(extIdB2); assertThat(accounts.get(accountId).get().externalIds()).containsExactly(extIdB2);
assertThat( assertThat(
gApi.accounts().id(accountId.get()).getExternalIds().stream() gApi.accounts().id(accountId.get()).getExternalIds().stream()
.map(i -> i.identity) .map(i -> i.identity)

View File

@@ -66,7 +66,7 @@ public class AccountIndexerIT {
List<AccountState> matchedAccountStates = List<AccountState> matchedAccountStates =
accountQueryProvider.get().byPreferredEmail(preferredEmail); accountQueryProvider.get().byPreferredEmail(preferredEmail);
assertThat(matchedAccountStates).hasSize(1); assertThat(matchedAccountStates).hasSize(1);
assertThat(matchedAccountStates.get(0).getAccount().id()).isEqualTo(accountId); assertThat(matchedAccountStates.get(0).account().id()).isEqualTo(accountId);
} }
@Test @Test
@@ -82,7 +82,7 @@ public class AccountIndexerIT {
List<AccountState> matchedAccountStates = List<AccountState> matchedAccountStates =
accountQueryProvider.get().byPreferredEmail(preferredEmail); accountQueryProvider.get().byPreferredEmail(preferredEmail);
assertThat(matchedAccountStates).hasSize(1); assertThat(matchedAccountStates).hasSize(1);
assertThat(matchedAccountStates.get(0).getAccount().id()).isEqualTo(accountId); assertThat(matchedAccountStates.get(0).account().id()).isEqualTo(accountId);
} }
@Test @Test
@@ -91,10 +91,10 @@ public class AccountIndexerIT {
loadAccountToCache(accountId); loadAccountToCache(accountId);
String status = "ooo"; String status = "ooo";
updateAccountWithoutCacheOrIndex(accountId, newAccountUpdate().setStatus(status).build()); updateAccountWithoutCacheOrIndex(accountId, newAccountUpdate().setStatus(status).build());
assertThat(accountCache.get(accountId).get().getAccount().status()).isNull(); assertThat(accountCache.get(accountId).get().account().status()).isNull();
accountIndexer.index(accountId); accountIndexer.index(accountId);
assertThat(accountCache.get(accountId).get().getAccount().status()).isEqualTo(status); assertThat(accountCache.get(accountId).get().account().status()).isEqualTo(status);
} }
@Test @Test
@@ -109,7 +109,7 @@ public class AccountIndexerIT {
List<AccountState> matchedAccountStates = List<AccountState> matchedAccountStates =
accountQueryProvider.get().byPreferredEmail(preferredEmail); accountQueryProvider.get().byPreferredEmail(preferredEmail);
assertThat(matchedAccountStates).hasSize(1); assertThat(matchedAccountStates).hasSize(1);
assertThat(matchedAccountStates.get(0).getAccount().id()).isEqualTo(accountId); assertThat(matchedAccountStates.get(0).account().id()).isEqualTo(accountId);
} }
@Test @Test

View File

@@ -192,7 +192,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().preferredEmail()).isEqualTo(newEmail); assertThat(accountState.get().account().preferredEmail()).isEqualTo(newEmail);
} }
@Test @Test
@@ -217,7 +217,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().fullName()).isEqualTo(newName); assertThat(accountState.get().account().fullName()).isEqualTo(newName);
} }
@Test @Test
@@ -296,7 +296,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
assertAuthResultForExistingAccount(authResult, accountId, gerritExtIdKey); assertAuthResultForExistingAccount(authResult, accountId, gerritExtIdKey);
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().isActive()).isTrue(); assertThat(accountState.get().account().isActive()).isTrue();
} }
@Test @Test
@@ -317,7 +317,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
assertAuthResultForExistingAccount(authResult, accountId, gerritExtIdKey); assertAuthResultForExistingAccount(authResult, accountId, gerritExtIdKey);
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().isActive()).isTrue(); assertThat(accountState.get().account().isActive()).isTrue();
} }
@Test @Test
@@ -341,7 +341,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().isActive()).isFalse(); assertThat(accountState.get().account().isActive()).isFalse();
} }
@Test @Test
@@ -433,7 +433,7 @@ public class AccountManagerIT extends AbstractDaemonTest {
// Verify that the preferred email was not updated. // Verify that the preferred email was not updated.
Optional<AccountState> accountState = accounts.get(accountId); Optional<AccountState> accountState = accounts.get(accountId);
assertThat(accountState).isPresent(); assertThat(accountState).isPresent();
assertThat(accountState.get().getAccount().preferredEmail()).isEqualTo(email); assertThat(accountState.get().account().preferredEmail()).isEqualTo(email);
} }
@Test @Test

View File

@@ -112,7 +112,7 @@ public class ExternalIdIT extends AbstractDaemonTest {
@Test @Test
public void getExternalIds() throws Exception { public void getExternalIds() throws Exception {
Collection<ExternalId> expectedIds = getAccountState(user.id()).getExternalIds(); Collection<ExternalId> expectedIds = getAccountState(user.id()).externalIds();
List<AccountExternalIdInfo> expectedIdInfos = toExternalIdInfos(expectedIds); List<AccountExternalIdInfo> expectedIdInfos = toExternalIdInfos(expectedIds);
RestResponse response = userRestSession.get("/accounts/self/external.ids"); RestResponse response = userRestSession.get("/accounts/self/external.ids");
@@ -142,7 +142,7 @@ public class ExternalIdIT extends AbstractDaemonTest {
.add(allowCapability(GlobalCapability.ACCESS_DATABASE).group(REGISTERED_USERS)) .add(allowCapability(GlobalCapability.ACCESS_DATABASE).group(REGISTERED_USERS))
.update(); .update();
Collection<ExternalId> expectedIds = getAccountState(admin.id()).getExternalIds(); Collection<ExternalId> expectedIds = getAccountState(admin.id()).externalIds();
List<AccountExternalIdInfo> expectedIdInfos = toExternalIdInfos(expectedIds); List<AccountExternalIdInfo> expectedIdInfos = toExternalIdInfos(expectedIds);
RestResponse response = userRestSession.get("/accounts/" + admin.id() + "/external.ids"); RestResponse response = userRestSession.get("/accounts/" + admin.id() + "/external.ids");

View File

@@ -340,6 +340,6 @@ public class AccountResolverIT extends AbstractDaemonTest {
accountsUpdateProvider accountsUpdateProvider
.get() .get()
.update("Force set preferred email", id, (s, u) -> u.setPreferredEmail(email)); .update("Force set preferred email", id, (s, u) -> u.setPreferredEmail(email));
assertThat(result.map(a -> a.getAccount().preferredEmail())).hasValue(email); assertThat(result.map(a -> a.account().preferredEmail())).hasValue(email);
} }
} }

View File

@@ -198,7 +198,7 @@ public class GerritPublicKeyCheckerTest {
.update( .update(
"Delete External IDs", "Delete External IDs",
user.getAccountId(), user.getAccountId(),
(a, u) -> u.deleteExternalIds(a.getExternalIds())); (a, u) -> u.deleteExternalIds(a.externalIds()));
reloadUser(); reloadUser();
TestKey key = validKeyWithSecondUserId(); TestKey key = validKeyWithSecondUserId();

View File

@@ -84,7 +84,7 @@ public class AccountResolverTest {
@Override @Override
public String toString() { public String toString() {
return accounts.stream() return accounts.stream()
.map(a -> a.getAccount().id().toString()) .map(a -> a.account().id().toString())
.collect(joining(",", pattern + "(", ")")); .collect(joining(",", pattern + "(", ")"));
} }
} }
@@ -156,7 +156,7 @@ public class AccountResolverTest {
// Searchers always short-circuit when finding a non-empty result list, and this one didn't // Searchers always short-circuit when finding a non-empty result list, and this one didn't
// filter out inactive results, so the second searcher never ran. // filter out inactive results, so the second searcher never ran.
assertThat(result.asIdSet()).containsExactlyElementsIn(ids(1)); assertThat(result.asIdSet()).containsExactlyElementsIn(ids(1));
assertThat(getOnlyElement(result.asList()).getAccount().isActive()).isFalse(); assertThat(getOnlyElement(result.asList()).account().isActive()).isFalse();
assertThat(filteredInactiveIds(result)).isEmpty(); assertThat(filteredInactiveIds(result)).isEmpty();
} }
@@ -173,7 +173,7 @@ public class AccountResolverTest {
// and this one didn't filter out inactive results, // and this one didn't filter out inactive results,
// so the second searcher never ran. // so the second searcher never ran.
assertThat(result.asIdSet()).containsExactlyElementsIn(ids(1)); assertThat(result.asIdSet()).containsExactlyElementsIn(ids(1));
assertThat(getOnlyElement(result.asList()).getAccount().isActive()).isFalse(); assertThat(getOnlyElement(result.asList()).account().isActive()).isFalse();
assertThat(filteredInactiveIds(result)).isEmpty(); assertThat(filteredInactiveIds(result)).isEmpty();
} }
@@ -255,8 +255,8 @@ public class AccountResolverTest {
AccountState account = newAccount(1); AccountState account = newAccount(1);
ImmutableList<Searcher<?>> searchers = ImmutableList<Searcher<?>> searchers =
ImmutableList.of(new TestSearcher("foo", false, account)); ImmutableList.of(new TestSearcher("foo", false, account));
assertThat(search("foo", searchers, allVisible()).asUnique().getAccount().id()) assertThat(search("foo", searchers, allVisible()).asUnique().account().id())
.isEqualTo(account.getAccount().id()); .isEqualTo(account.account().id());
} }
@Test @Test
@@ -375,18 +375,16 @@ public class AccountResolverTest {
} }
private Predicate<AccountState> activityPrediate() { private Predicate<AccountState> activityPrediate() {
return (AccountState accountState) -> accountState.getAccount().isActive(); return (AccountState accountState) -> accountState.account().isActive();
} }
private static Supplier<Predicate<AccountState>> only(int... ids) { private static Supplier<Predicate<AccountState>> only(int... ids) {
ImmutableSet<Account.Id> idSet = ImmutableSet<Account.Id> idSet =
Arrays.stream(ids).mapToObj(Account::id).collect(toImmutableSet()); Arrays.stream(ids).mapToObj(Account::id).collect(toImmutableSet());
return () -> a -> idSet.contains(a.getAccount().id()); return () -> a -> idSet.contains(a.account().id());
} }
private static ImmutableSet<Account.Id> filteredInactiveIds(Result result) { private static ImmutableSet<Account.Id> filteredInactiveIds(Result result) {
return result.filteredInactive().stream() return result.filteredInactive().stream().map(a -> a.account().id()).collect(toImmutableSet());
.map(a -> a.getAccount().id())
.collect(toImmutableSet());
} }
} }

View File

@@ -347,8 +347,8 @@ public class FromAddressGeneratorProviderTest {
private Account.Id user(String name, String email) { private Account.Id user(String name, String email) {
final AccountState s = makeUser(name, email); final AccountState s = makeUser(name, email);
when(accountCache.get(eq(s.getAccount().id()))).thenReturn(Optional.of(s)); when(accountCache.get(eq(s.account().id()))).thenReturn(Optional.of(s));
return s.getAccount().id(); return s.account().id();
} }
private void verifyAccountCacheGet(Account.Id id) { private void verifyAccountCacheGet(Account.Id id) {
@@ -357,7 +357,7 @@ public class FromAddressGeneratorProviderTest {
private Account.Id userNoLookup(String name, String email) { private Account.Id userNoLookup(String name, String email) {
final AccountState s = makeUser(name, email); final AccountState s = makeUser(name, email);
return s.getAccount().id(); return s.account().id();
} }
private AccountState makeUser(String name, String email) { private AccountState makeUser(String name, String email) {

View File

@@ -816,7 +816,7 @@ public abstract class AbstractQueryAccountsTest extends GerritServerTests {
} }
protected void assertAccounts(List<AccountState> accounts, AccountInfo... expectedAccounts) { protected void assertAccounts(List<AccountState> accounts, AccountInfo... expectedAccounts) {
assertThat(accounts.stream().map(a -> a.getAccount().id().get()).collect(toList())) assertThat(accounts.stream().map(a -> a.account().id().get()).collect(toList()))
.containsExactlyElementsIn( .containsExactlyElementsIn(
Arrays.asList(expectedAccounts).stream().map(a -> a._accountId).collect(toList())); Arrays.asList(expectedAccounts).stream().map(a -> a._accountId).collect(toList()));
} }