Search in sources :

Example 26 with QueryParseException

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

the class ChangeQueryBuilder method cherryPickOf.

@Operator
public Predicate<ChangeData> cherryPickOf(String value) throws QueryParseException {
    checkFieldAvailable(ChangeField.CHERRY_PICK_OF_CHANGE, "cherryPickOf");
    checkFieldAvailable(ChangeField.CHERRY_PICK_OF_PATCHSET, "cherryPickOf");
    if (Ints.tryParse(value) != null) {
        return ChangePredicates.cherryPickOf(Change.id(Ints.tryParse(value)));
    }
    try {
        PatchSet.Id patchSetId = PatchSet.Id.parse(value);
        return ChangePredicates.cherryPickOf(patchSetId);
    } catch (IllegalArgumentException e) {
        throw new QueryParseException("'" + value + "' is not a valid input. It must be in the 'ChangeNumber[,PatchsetNumber]' format.", e);
    }
}
Also used : PatchSet(com.google.gerrit.entities.PatchSet) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 27 with QueryParseException

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

the class ChangeQueryBuilder method query.

@Operator
public Predicate<ChangeData> query(String value) throws QueryParseException {
    // [name=]<name>[,user=<user>] || [user=<user>,][name=]<name>
    PredicateArgs inputArgs = new PredicateArgs(value);
    String name = null;
    Account.Id account = null;
    try (Repository git = args.repoManager.openRepository(args.allUsersName)) {
        // [name=]<name>
        if (inputArgs.keyValue.containsKey(ARG_ID_NAME)) {
            name = inputArgs.keyValue.get(ARG_ID_NAME).value();
        } else if (inputArgs.positional.size() == 1) {
            name = Iterables.getOnlyElement(inputArgs.positional);
        } else if (inputArgs.positional.size() > 1) {
            throw new QueryParseException("Error parsing named query: " + value);
        }
        // [,user=<user>]
        if (inputArgs.keyValue.containsKey(ARG_ID_USER)) {
            Set<Account.Id> accounts = parseAccount(inputArgs.keyValue.get(ARG_ID_USER).value());
            if (accounts != null && accounts.size() > 1) {
                throw error(String.format("\"%s\" resolves to multiple accounts", inputArgs.keyValue.get(ARG_ID_USER)));
            }
            account = (accounts == null ? self() : Iterables.getOnlyElement(accounts));
        } else {
            account = self();
        }
        VersionedAccountQueries q = VersionedAccountQueries.forUser(account);
        q.load(args.allUsersName, git);
        String query = q.getQueryList().getQuery(name);
        if (query != null) {
            return parse(query);
        }
    } catch (RepositoryNotFoundException e) {
        throw new QueryParseException("Unknown named query (no " + args.allUsersName + " repo): " + name, e);
    } catch (IOException | ConfigInvalidException e) {
        throw new QueryParseException("Error parsing named query: " + value, e);
    }
    throw new QueryParseException("Unknown named query: " + name);
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) VersionedAccountQueries(com.google.gerrit.server.account.VersionedAccountQueries) QueryParseException(com.google.gerrit.index.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository)

Example 28 with QueryParseException

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

the class OutputStreamQuery method query.

public void query(String queryString) throws IOException {
    out = new // 
    PrintWriter(new // 
    BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)));
    try {
        if (queryProcessor.isDisabled()) {
            ErrorMessage m = new ErrorMessage();
            m.message = "query disabled";
            show(m);
            return;
        }
        try {
            final QueryStatsAttribute stats = new QueryStatsAttribute();
            stats.runTimeMilliseconds = TimeUtil.nowMs();
            Map<Project.NameKey, Repository> repos = new HashMap<>();
            Map<Project.NameKey, RevWalk> revWalks = new HashMap<>();
            QueryResult<ChangeData> results = queryProcessor.query(queryBuilder.parse(queryString));
            pluginInfosByChange = queryProcessor.createPluginDefinedInfos(results.entities());
            try {
                for (ChangeData d : results.entities()) {
                    show(buildChangeAttribute(d, repos, revWalks));
                }
            } finally {
                closeAll(revWalks.values(), repos.values());
            }
            stats.rowCount = results.entities().size();
            stats.moreChanges = results.more();
            stats.runTimeMilliseconds = TimeUtil.nowMs() - stats.runTimeMilliseconds;
            show(stats);
        } catch (StorageException err) {
            logger.atSevere().withCause(err).log("Cannot execute query: %s", queryString);
            ErrorMessage m = new ErrorMessage();
            m.message = "cannot query database";
            show(m);
        } catch (QueryParseException e) {
            ErrorMessage m = new ErrorMessage();
            m.message = e.getMessage();
            show(m);
        }
    } finally {
        try {
            out.flush();
        } finally {
            out = null;
        }
    }
}
Also used : HashMap(java.util.HashMap) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BufferedWriter(java.io.BufferedWriter) QueryParseException(com.google.gerrit.index.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository) QueryStatsAttribute(com.google.gerrit.server.data.QueryStatsAttribute) OutputStreamWriter(java.io.OutputStreamWriter) StorageException(com.google.gerrit.exceptions.StorageException)

Example 29 with QueryParseException

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

the class ReviewerRecommender method baseRanking.

/**
 * @param baseWeight The weight applied to the ordering of the reviewers.
 * @param query Query to match. For example, it can try to match all users that start with "Ab".
 * @param candidateList The list of candidates based on the query. If query is empty, this list is
 *     also empty.
 * @return Map of account ids that match the query and their appropriate ranking (the better the
 *     ranking, the better it is to suggest them as reviewers).
 * @throws IOException Can't find owner="self" account.
 * @throws ConfigInvalidException Can't find owner="self" account.
 */
private Map<Account.Id, MutableDouble> baseRanking(double baseWeight, String query, List<Account.Id> candidateList) throws IOException, ConfigInvalidException {
    int numberOfRelevantChanges = config.getInt("suggest", "relevantChanges", 50);
    // Get the user's last numberOfRelevantChanges changes, check reviewers
    try {
        List<ChangeData> result = queryProvider.get().setLimit(numberOfRelevantChanges).setRequestedFields(ChangeField.REVIEWER).query(changeQueryBuilder.owner("self"));
        Map<Account.Id, MutableDouble> suggestions = new LinkedHashMap<>();
        // Put those candidates at the bottom of the list
        candidateList.stream().forEach(id -> suggestions.put(id, new MutableDouble(0)));
        for (ChangeData cd : result) {
            for (Account.Id reviewer : cd.reviewers().all()) {
                if (accountMatchesQuery(reviewer, query)) {
                    suggestions.computeIfAbsent(reviewer, (ignored) -> new MutableDouble(0)).add(baseWeight);
                }
            }
        }
        return suggestions;
    } catch (QueryParseException e) {
        // Unhandled, because owner:self will never provoke a QueryParseException
        logger.atSevere().withCause(e).log("Exception while suggesting reviewers");
        return new HashMap<>();
    }
}
Also used : AccountCache(com.google.gerrit.server.account.AccountCache) FanOutExecutor(com.google.gerrit.server.FanOutExecutor) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) MutableDouble(org.apache.commons.lang3.mutable.MutableDouble) Config(org.eclipse.jgit.lib.Config) Future(java.util.concurrent.Future) ImmutableList(com.google.common.collect.ImmutableList) QueryParseException(com.google.gerrit.index.query.QueryParseException) Map(java.util.Map) ExecutorService(java.util.concurrent.ExecutorService) SuggestedReviewer(com.google.gerrit.server.change.SuggestedReviewer) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Iterator(java.util.Iterator) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) ProjectState(com.google.gerrit.server.project.ProjectState) Account(com.google.gerrit.entities.Account) Set(java.util.Set) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) PluginMapContext(com.google.gerrit.server.plugincontext.PluginMapContext) ChangeField(com.google.gerrit.server.index.change.ChangeField) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) ChangeData(com.google.gerrit.server.query.change.ChangeData) Provider(com.google.inject.Provider) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Stream(java.util.stream.Stream) ChangeQueryBuilder(com.google.gerrit.server.query.change.ChangeQueryBuilder) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Optional(java.util.Optional) AccountState(com.google.gerrit.server.account.AccountState) Collections(java.util.Collections) FluentLogger(com.google.common.flogger.FluentLogger) ReviewerSuggestion(com.google.gerrit.server.change.ReviewerSuggestion) Account(com.google.gerrit.entities.Account) MutableDouble(org.apache.commons.lang3.mutable.MutableDouble) ChangeData(com.google.gerrit.server.query.change.ChangeData) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 30 with QueryParseException

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

the class ApprovalQueryIT method userInPredicate_groupNotFound.

@Test
public void userInPredicate_groupNotFound() {
    QueryParseException thrown = assertThrows(QueryParseException.class, () -> queryBuilder.parse("uploaderin:foobar").asMatchable().match(contextForCodeReviewLabel(/* value= */
    2)));
    assertThat(thrown).hasMessageThat().contains("Group foobar not found");
}
Also used : QueryParseException(com.google.gerrit.index.query.QueryParseException) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

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