use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.
the class ProjectWatch method getWatchers.
/**
* Returns all watchers that are relevant
*/
public final Watchers getWatchers(NotifyConfig.NotifyType type, boolean includeWatchersFromNotifyConfig) {
Watchers matching = new Watchers();
Set<Account.Id> projectWatchers = new HashSet<>();
for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) {
Account.Id accountId = a.account().id();
for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyConfig.NotifyType>> e : a.projectWatches().entrySet()) {
if (project.equals(e.getKey().project()) && add(matching, accountId, e.getKey(), e.getValue(), type)) {
// We only want to prevent matching All-Projects if this filter hits
projectWatchers.add(accountId);
}
}
}
for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) {
for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyConfig.NotifyType>> e : a.projectWatches().entrySet()) {
if (args.allProjectsName.equals(e.getKey().project())) {
Account.Id accountId = a.account().id();
if (!projectWatchers.contains(accountId)) {
add(matching, accountId, e.getKey(), e.getValue(), type);
}
}
}
}
if (!includeWatchersFromNotifyConfig) {
return matching;
}
for (ProjectState state : projectState.tree()) {
for (NotifyConfig nc : state.getConfig().getNotifySections().values()) {
if (nc.isNotify(type)) {
try {
add(matching, state.getNameKey(), nc);
} catch (QueryParseException e) {
logger.atInfo().log("Project %s has invalid notify %s filter \"%s\": %s", state.getName(), nc.getName(), nc.getFilter(), e.getMessage());
}
}
}
}
return matching;
}
use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.
the class SetMembersCommand method reportMembersAction.
private void reportMembersAction(String action, GroupResource group, List<Account.Id> accountIdList) throws UnsupportedEncodingException, IOException {
String names = accountIdList.stream().map(accountId -> {
Optional<AccountState> accountState = accountCache.get(accountId);
if (!accountState.isPresent()) {
return "n/a";
}
return MoreObjects.firstNonNull(accountState.get().account().preferredEmail(), "n/a");
}).collect(joining(", "));
out.write(String.format("Members %s group %s: %s\n", action, group.getName(), names).getBytes(ENC));
}
use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.
the class AbstractQueryAccountsTest method rawDocument.
@Test
public void rawDocument() throws Exception {
AccountInfo userInfo = gApi.accounts().id(admin.getAccountId().get()).get();
Schema<AccountState> schema = indexes.getSearchIndex().getSchema();
Optional<FieldBundle> rawFields = indexes.getSearchIndex().getRaw(Account.id(userInfo._accountId), QueryOptions.create(IndexConfig.createDefault(), 0, 1, schema.getStoredFields().keySet()));
assertThat(rawFields).isPresent();
if (schema.useLegacyNumericFields()) {
assertThat(rawFields.get().getValue(AccountField.ID)).isEqualTo(userInfo._accountId);
} else {
assertThat(Integer.valueOf(rawFields.get().getValue(AccountField.ID_STR))).isEqualTo(userInfo._accountId);
}
// The field EXTERNAL_ID_STATE is only supported from schema version 6.
if (getSchemaVersion() < 6) {
return;
}
List<AccountExternalIdInfo> externalIdInfos = gApi.accounts().self().getExternalIds();
List<ByteArrayWrapper> blobs = new ArrayList<>();
for (AccountExternalIdInfo info : externalIdInfos) {
Optional<ExternalId> extId = externalIds.get(externalIdKeyFactory.parse(info.identity));
assertThat(extId).isPresent();
blobs.add(new ByteArrayWrapper(extId.get().toByteArray()));
}
assertThat(rawFields.get().getValue(AccountField.EXTERNAL_ID_STATE)).hasSize(blobs.size());
assertThat(Streams.stream(rawFields.get().getValue(AccountField.EXTERNAL_ID_STATE)).map(ByteArrayWrapper::new).collect(toList())).containsExactlyElementsIn(blobs);
}
use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.
the class QueryAccounts method apply.
@Override
public Response<List<AccountInfo>> apply(TopLevelResource rsrc) throws RestApiException, PermissionBackendException {
if (Strings.isNullOrEmpty(query)) {
throw new BadRequestException("missing query field");
}
if (suggest && (!suggestConfig || query.length() < suggestFrom)) {
return Response.ok(Collections.emptyList());
}
Set<FillOptions> fillOptions = EnumSet.of(FillOptions.ID);
if (options.contains(ListAccountsOption.DETAILS)) {
fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
}
boolean modifyAccountCapabilityChecked = false;
if (options.contains(ListAccountsOption.ALL_EMAILS)) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
modifyAccountCapabilityChecked = true;
fillOptions.add(FillOptions.EMAIL);
fillOptions.add(FillOptions.SECONDARY_EMAILS);
}
if (suggest) {
fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
fillOptions.add(FillOptions.EMAIL);
if (modifyAccountCapabilityChecked) {
fillOptions.add(FillOptions.SECONDARY_EMAILS);
} else {
if (permissionBackend.currentUser().test(GlobalPermission.MODIFY_ACCOUNT)) {
fillOptions.add(FillOptions.SECONDARY_EMAILS);
}
}
}
accountLoader = accountLoaderFactory.create(fillOptions);
AccountQueryProcessor queryProcessor = queryProcessorProvider.get();
if (queryProcessor.isDisabled()) {
throw new MethodNotAllowedException("query disabled");
}
if (limit != null) {
queryProcessor.setUserProvidedLimit(limit);
}
if (start != null) {
queryProcessor.setStart(start);
}
Map<Account.Id, AccountInfo> matches = new LinkedHashMap<>();
try {
Predicate<AccountState> queryPred;
if (suggest) {
queryPred = queryBuilder.defaultQuery(query);
queryProcessor.setUserProvidedLimit(suggestLimit);
} else {
queryPred = queryBuilder.parse(query);
}
if (!AccountPredicates.hasActive(queryPred)) {
// if neither 'is:active' nor 'is:inactive' appears in the query only
// active accounts should be queried
queryPred = AccountPredicates.andActive(queryPred);
}
QueryResult<AccountState> result = queryProcessor.query(queryPred);
for (AccountState accountState : result.entities()) {
Account.Id id = accountState.account().id();
matches.put(id, accountLoader.get(id));
}
accountLoader.fill();
List<AccountInfo> sorted = AccountInfoComparator.ORDER_NULLS_LAST.sortedCopy(matches.values());
if (!sorted.isEmpty() && result.more()) {
sorted.get(sorted.size() - 1)._moreAccounts = true;
}
return Response.ok(sorted);
} catch (QueryParseException e) {
if (suggest) {
return Response.ok(ImmutableList.of());
}
throw new BadRequestException(e.getMessage());
}
}
use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.
the class PutPreferred method apply.
public Response<String> apply(IdentifiedUser user, String preferredEmail) throws RestApiException, IOException, ConfigInvalidException {
AtomicReference<Optional<RestApiException>> exception = new AtomicReference<>(Optional.empty());
AtomicBoolean alreadyPreferred = new AtomicBoolean(false);
Optional<AccountState> updatedAccount = accountsUpdateProvider.get().update("Set Preferred Email via API", user.getAccountId(), (a, u) -> {
if (preferredEmail.equals(a.account().preferredEmail())) {
alreadyPreferred.set(true);
} else {
// check if the user has a matching email
String matchingEmail = null;
for (String email : a.externalIds().stream().map(ExternalId::email).filter(Objects::nonNull).collect(toSet())) {
if (email.equals(preferredEmail)) {
// we have an email that matches exactly, prefer this one
matchingEmail = email;
break;
} else if (matchingEmail == null && email.equalsIgnoreCase(preferredEmail)) {
// we found an email that matches but has a different case
matchingEmail = email;
}
}
if (matchingEmail == null) {
// user doesn't have an external ID for this email
if (user.hasEmailAddress(preferredEmail)) {
// but Realm says the user is allowed to use this email
Set<ExternalId> existingExtIdsWithThisEmail = externalIds.byEmail(preferredEmail);
if (!existingExtIdsWithThisEmail.isEmpty()) {
// but the email is already assigned to another account
logger.atWarning().log("Cannot set preferred email %s for account %s because it is owned" + " by the following account(s): %s", preferredEmail, user.getAccountId(), existingExtIdsWithThisEmail.stream().map(ExternalId::accountId).collect(toList()));
exception.set(Optional.of(new ResourceConflictException("email in use by another account")));
return;
}
// claim the email now
u.addExternalId(externalIdFactory.createEmail(a.account().id(), preferredEmail));
matchingEmail = preferredEmail;
} else {
// Realm says that the email doesn't belong to the user. This can only
// happen as
// a race condition because EmailsCollection would have thrown
// ResourceNotFoundException already before invoking this REST endpoint.
exception.set(Optional.of(new ResourceNotFoundException(preferredEmail)));
return;
}
}
u.setPreferredEmail(matchingEmail);
}
});
if (!updatedAccount.isPresent()) {
throw new ResourceNotFoundException("account not found");
}
if (exception.get().isPresent()) {
throw exception.get().get();
}
return alreadyPreferred.get() ? Response.ok() : Response.created();
}
Aggregations