Search in sources :

Example 11 with QueryParseException

use of com.google.gerrit.index.query.QueryParseException 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;
}
Also used : Account(com.google.gerrit.entities.Account) ProjectWatchKey(com.google.gerrit.server.account.ProjectWatches.ProjectWatchKey) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.index.query.QueryParseException) ImmutableSet(com.google.common.collect.ImmutableSet) NotifyConfig(com.google.gerrit.entities.NotifyConfig) ProjectState(com.google.gerrit.server.project.ProjectState) Map(java.util.Map) HashSet(java.util.HashSet)

Example 12 with QueryParseException

use of com.google.gerrit.index.query.QueryParseException in project gerrit by GerritCodeReview.

the class QueryProjects method apply.

public List<ProjectInfo> apply() throws BadRequestException, MethodNotAllowedException {
    if (Strings.isNullOrEmpty(query)) {
        throw new BadRequestException("missing query field");
    }
    ProjectIndex searchIndex = indexes.getSearchIndex();
    if (searchIndex == null) {
        throw new MethodNotAllowedException("no project index");
    }
    ProjectQueryProcessor queryProcessor = queryProcessorProvider.get();
    if (start != 0) {
        queryProcessor.setStart(start);
    }
    if (limit != 0) {
        queryProcessor.setUserProvidedLimit(limit);
    }
    try {
        QueryResult<ProjectData> result = queryProcessor.query(queryBuilder.parse(query));
        List<ProjectData> pds = result.entities();
        ArrayList<ProjectInfo> projectInfos = Lists.newArrayListWithCapacity(pds.size());
        for (ProjectData pd : pds) {
            projectInfos.add(json.format(pd.getProject()));
        }
        return projectInfos;
    } catch (QueryParseException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ProjectQueryProcessor(com.google.gerrit.server.query.project.ProjectQueryProcessor) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectData(com.google.gerrit.index.project.ProjectData) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 13 with QueryParseException

use of com.google.gerrit.index.query.QueryParseException in project gerrit by GerritCodeReview.

the class ApprovalQueryIT method hasChangedFilesPredicate_unsupportedOperator.

@Test
public void hasChangedFilesPredicate_unsupportedOperator() {
    QueryParseException thrown = assertThrows(QueryParseException.class, () -> queryBuilder.parse("has:invalid").asMatchable().match(contextForCodeReviewLabel(/* value= */
    2)));
    assertThat(thrown).hasMessageThat().contains("'invalid' is not a supported argument for has. only 'unchanged-files' is supported");
}
Also used : QueryParseException(com.google.gerrit.index.query.QueryParseException) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 14 with QueryParseException

use of com.google.gerrit.index.query.QueryParseException 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());
    }
}
Also used : Account(com.google.gerrit.entities.Account) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountQueryProcessor(com.google.gerrit.server.query.account.AccountQueryProcessor) AccountState(com.google.gerrit.server.account.AccountState) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 15 with QueryParseException

use of com.google.gerrit.index.query.QueryParseException in project gerrit by GerritCodeReview.

the class ReviewersUtil method suggestAccounts.

private List<Account.Id> suggestAccounts(SuggestReviewers suggestReviewers) throws BadRequestException {
    try (Timer0.Context ctx = metrics.queryAccountsLatency.start()) {
        // For performance reasons we don't use AccountQueryProvider as it would always load the
        // complete account from the cache (or worse, from NoteDb) even though we only need the ID
        // which we can directly get from the returned results.
        Predicate<AccountState> pred = Predicate.and(AccountPredicates.isActive(), accountQueryBuilder.defaultQuery(suggestReviewers.getQuery()));
        logger.atFine().log("accounts index query: %s", pred);
        accountIndexRewriter.validateMaxTermsInQuery(pred);
        boolean useLegacyNumericFields = accountIndexes.getSearchIndex().getSchema().useLegacyNumericFields();
        FieldDef<AccountState, ?> idField = useLegacyNumericFields ? AccountField.ID : AccountField.ID_STR;
        ResultSet<FieldBundle> result = accountIndexes.getSearchIndex().getSource(pred, QueryOptions.create(indexConfig, 0, suggestReviewers.getLimit(), ImmutableSet.of(idField.getName()))).readRaw();
        List<Account.Id> matches = result.toList().stream().map(f -> fromIdField(f, useLegacyNumericFields)).collect(toList());
        logger.atFine().log("Matches: %s", matches);
        return matches;
    } catch (TooManyTermsInQueryException e) {
        throw new BadRequestException(e.getMessage());
    } catch (QueryParseException e) {
        logger.atWarning().withCause(e).log("Suggesting accounts failed, return empty result.");
        return ImmutableList.of();
    } catch (StorageException e) {
        if (e.getCause() instanceof TooManyTermsInQueryException) {
            throw new BadRequestException(e.getMessage());
        }
        if (e.getCause() instanceof QueryParseException) {
            return ImmutableList.of();
        }
        throw e;
    }
}
Also used : GroupBackend(com.google.gerrit.server.account.GroupBackend) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) EnumSet(java.util.EnumSet) FieldDef(com.google.gerrit.index.FieldDef) ImmutableSet(com.google.common.collect.ImmutableSet) GroupBaseInfo(com.google.gerrit.extensions.common.GroupBaseInfo) Timer0(com.google.gerrit.metrics.Timer0) Account(com.google.gerrit.entities.Account) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountQueryBuilder(com.google.gerrit.server.query.account.AccountQueryBuilder) Set(java.util.Set) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) Sets(com.google.common.collect.Sets) GroupReference(com.google.gerrit.entities.GroupReference) Objects(java.util.Objects) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Url(com.google.gerrit.extensions.restapi.Url) MetricMaker(com.google.gerrit.metrics.MetricMaker) LazyArgs.lazy(com.google.common.flogger.LazyArgs.lazy) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) AccountLoader(com.google.gerrit.server.account.AccountLoader) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IndexConfig(com.google.gerrit.index.IndexConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) ResultSet(com.google.gerrit.index.query.ResultSet) AccountPredicates(com.google.gerrit.server.query.account.AccountPredicates) GroupMembers(com.google.gerrit.server.account.GroupMembers) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) QueryParseException(com.google.gerrit.index.query.QueryParseException) Description(com.google.gerrit.metrics.Description) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountIndexRewriter(com.google.gerrit.server.index.account.AccountIndexRewriter) Predicate(com.google.gerrit.index.query.Predicate) SuggestedReviewerInfo(com.google.gerrit.extensions.common.SuggestedReviewerInfo) AccountControl(com.google.gerrit.server.account.AccountControl) CurrentUser(com.google.gerrit.server.CurrentUser) AccountField(com.google.gerrit.server.index.account.AccountField) StorageException(com.google.gerrit.exceptions.StorageException) Units(com.google.gerrit.metrics.Description.Units) ProjectState(com.google.gerrit.server.project.ProjectState) QueryOptions(com.google.gerrit.index.QueryOptions) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) Project(com.google.gerrit.entities.Project) AccountState(com.google.gerrit.server.account.AccountState) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) Collections(java.util.Collections) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Timer0(com.google.gerrit.metrics.Timer0) StorageException(com.google.gerrit.exceptions.StorageException)

Aggregations

QueryParseException (com.google.gerrit.index.query.QueryParseException)30 Account (com.google.gerrit.entities.Account)7 StorageException (com.google.gerrit.exceptions.StorageException)6 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)6 ArrayList (java.util.ArrayList)6 Predicate (com.google.gerrit.index.query.Predicate)5 AccountState (com.google.gerrit.server.account.AccountState)5 ChangeData (com.google.gerrit.server.query.change.ChangeData)5 IOException (java.io.IOException)5 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)5 Repository (org.eclipse.jgit.lib.Repository)4 FluentLogger (com.google.common.flogger.FluentLogger)3 GroupReference (com.google.gerrit.entities.GroupReference)3 Project (com.google.gerrit.entities.Project)3 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)3 LimitPredicate (com.google.gerrit.index.query.LimitPredicate)3 Inject (com.google.inject.Inject)3 Provider (com.google.inject.Provider)3 Collections (java.util.Collections)3 List (java.util.List)3