Make ProjectCache#get return an Optional<ProjectState>

This refactoring forces callers to think about how to handle projects
that do not exist explicitly. As a general guidance, API handlers will
want to throw a BadRequestException and components in the inner works of
Gerrit where content should have been pre-validated should throw an
IllegalStateException.

But overall, it's a case-by-case decision.

In a follow-up commit, we will remove #checkedGet and move callers to
get instead.

Change-Id: I95bbc22ad5f3279e6f40f1d05c8d7235d601e32d
This commit is contained in:
Patrick Hiesel
2020-03-04 13:22:25 +01:00
parent 8d6c9ade61
commit a3b587c0ce
54 changed files with 251 additions and 165 deletions

View File

@@ -32,12 +32,14 @@ import com.google.gerrit.index.query.QueryParseException;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.IndexUtils;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.util.Optional;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.elasticsearch.client.Response;
@@ -119,6 +121,10 @@ public class ElasticProjectIndex extends AbstractElasticIndex<Project.NameKey, P
Project.NameKey nameKey =
Project.nameKey(source.getAsJsonObject().get(ProjectField.NAME.getName()).getAsString());
return projectCache.get().get(nameKey).toProjectData();
Optional<ProjectState> state = projectCache.get().get(nameKey);
if (!state.isPresent()) {
return null;
}
return state.get().toProjectData();
}
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.gpg;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.base.Strings;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.BooleanProjectConfig;
@@ -87,7 +89,7 @@ class SignedPushModule extends AbstractModule {
@Override
public void init(Project.NameKey project, ReceivePack rp) {
ProjectState ps = projectCache.get(project);
ProjectState ps = projectCache.get(project).orElseThrow(illegalState(project));
if (!ps.is(BooleanProjectConfig.ENABLE_SIGNED_PUSH)) {
rp.setSignedPushConfig(null);
return;

View File

@@ -142,7 +142,6 @@ public class LuceneProjectIndex extends AbstractLuceneIndex<Project.NameKey, Pro
@Override
protected ProjectData fromDocument(Document doc) {
Project.NameKey nameKey = Project.nameKey(doc.getField(NAME.getName()).stringValue());
ProjectState projectState = projectCache.get().get(nameKey);
return projectState == null ? null : projectState.toProjectData();
return projectCache.get().get(nameKey).map(ProjectState::toProjectData).orElse(null);
}
}

View File

@@ -27,6 +27,7 @@ import static com.google.gerrit.extensions.client.ListChangesOption.DOWNLOAD_COM
import static com.google.gerrit.extensions.client.ListChangesOption.PUSH_CERTIFICATES;
import static com.google.gerrit.extensions.client.ListChangesOption.WEB_LINKS;
import static com.google.gerrit.server.CommonConverters.toGitPerson;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -306,7 +307,7 @@ public class RevisionJson {
}
out.commitWithFooters =
mergeUtilFactory
.create(projectCache.get(project))
.create(projectCache.get(project).orElseThrow(illegalState(project)))
.createCommitMessageOnSubmit(commit, mergeTip, cd.notes(), in.id());
}
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.config;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.Project;
import com.google.gerrit.server.plugins.Plugin;
@@ -129,10 +131,8 @@ public class PluginConfigFactory implements ReloadPluginListener {
*/
public PluginConfig getFromProjectConfig(Project.NameKey projectName, String pluginName)
throws NoSuchProjectException {
ProjectState projectState = projectCache.get(projectName);
if (projectState == null) {
throw new NoSuchProjectException(projectName);
}
ProjectState projectState =
projectCache.get(projectName).orElseThrow(noSuchProject(projectName));
return getFromProjectConfig(projectState, pluginName);
}
@@ -363,10 +363,8 @@ public class PluginConfigFactory implements ReloadPluginListener {
private ProjectLevelConfig getPluginConfig(Project.NameKey projectName, String pluginName)
throws NoSuchProjectException {
ProjectState projectState = projectCache.get(projectName);
if (projectState == null) {
throw new NoSuchProjectException(projectName);
}
ProjectState projectState =
projectCache.get(projectName).orElseThrow(noSuchProject(projectName));
return projectState.getConfig(pluginName + EXTENSION);
}

View File

@@ -37,6 +37,7 @@ import com.google.gerrit.server.project.ProjectState;
import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Optional;
/** Distributes Events to listeners if they are allowed to see them */
@Singleton
@@ -146,8 +147,8 @@ public class EventBroker implements EventDispatcher {
protected boolean isVisibleTo(Project.NameKey project, CurrentUser user) {
try {
ProjectState state = projectCache.get(project);
if (state == null || !state.statePermitsRead()) {
Optional<ProjectState> state = projectCache.get(project);
if (!state.isPresent() || !state.get().statePermitsRead()) {
return false;
}
@@ -162,8 +163,8 @@ public class EventBroker implements EventDispatcher {
if (change == null) {
return false;
}
ProjectState pe = projectCache.get(change.getProject());
if (pe == null || !pe.statePermitsRead()) {
Optional<ProjectState> pe = projectCache.get(change.getProject());
if (!pe.isPresent() || !pe.get().statePermitsRead()) {
return false;
}
try {
@@ -179,8 +180,8 @@ public class EventBroker implements EventDispatcher {
protected boolean isVisibleTo(BranchNameKey branchName, CurrentUser user)
throws PermissionBackendException {
ProjectState pe = projectCache.get(branchName.project());
if (pe == null || !pe.statePermitsRead()) {
Optional<ProjectState> pe = projectCache.get(branchName.project());
if (!pe.isPresent() || !pe.get().statePermitsRead()) {
return false;
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.events;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Sets;
@@ -24,6 +26,7 @@ import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.BranchNameKey;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.entities.Project;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.common.ApprovalInfo;
@@ -215,7 +218,9 @@ public class StreamEventsApiListener
final Map<String, Short> approvals = convertApprovalsMap(newApprovals);
return Suppliers.memoize(
() -> {
LabelTypes labelTypes = projectCache.get(change.getProject()).getLabelTypes();
Project.NameKey nameKey = change.getProject();
LabelTypes labelTypes =
projectCache.get(nameKey).orElseThrow(illegalState(nameKey)).getLabelTypes();
if (approvals.size() > 0) {
ApprovalAttribute[] r = new ApprovalAttribute[approvals.size()];
int i = 0;

View File

@@ -30,6 +30,7 @@ import static com.google.gerrit.server.git.receive.ReceiveConstants.PUSH_OPTION_
import static com.google.gerrit.server.git.receive.ReceiveConstants.SAME_CHANGE_ID_IN_MULTIPLE_CHANGES;
import static com.google.gerrit.server.git.validators.CommitValidators.NEW_PATCHSET_PATTERN;
import static com.google.gerrit.server.mail.MailUtil.getRecipientsFromFooters;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
@@ -1204,7 +1205,7 @@ class ReceiveCommits {
}
}
if (projectCache.get(newParent) == null) {
if (!projectCache.get(newParent).isPresent()) {
reject(cmd, "invalid project configuration: parent does not exist");
return;
}
@@ -1810,7 +1811,10 @@ class ReceiveCommits {
}
boolean privateByDefault =
projectCache.get(project.getNameKey()).is(BooleanProjectConfig.PRIVATE_BY_DEFAULT);
projectCache
.get(project.getNameKey())
.orElseThrow(illegalState(project.getNameKey()))
.is(BooleanProjectConfig.PRIVATE_BY_DEFAULT);
setChangeAsPrivate =
magicBranch.isPrivate || (privateByDefault && !magicBranch.removePrivate);
@@ -2088,6 +2092,7 @@ class ReceiveCommits {
start.getParentCount() == 1
&& projectCache
.get(project.getNameKey())
.orElseThrow(illegalState(project.getNameKey()))
.is(BooleanProjectConfig.REJECT_IMPLICIT_MERGES)
// Don't worry about implicit merges when creating changes for
// already-merged commits; they're already in history, so it's too
@@ -3091,7 +3096,8 @@ class ReceiveCommits {
logger.atWarning().withCause(e).log(
"Cannot evict from project cache, name key: %s", project.getName());
}
ProjectState ps = projectCache.get(project.getNameKey());
ProjectState ps =
projectCache.get(project.getNameKey()).orElseThrow(illegalState(project.getNameKey()));
try {
logger.atFine().log("Updating project description");
repo.setGitwebDescription(ps.getProject().getDescription());

View File

@@ -216,7 +216,7 @@ public class MergeValidators {
String.format(
" %s must inherit from %s", allUsersName.get(), allProjectsName.get()));
}
if (projectCache.get(newParent) == null) {
if (!projectCache.get(newParent).isPresent()) {
throw new MergeValidationException(PARENT_NOT_FOUND);
}
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.group.db;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.entities.AccountGroup;
@@ -85,7 +87,8 @@ class RenameGroupOp extends DefaultQueueOp {
public void run() {
Iterable<Project.NameKey> names = tryingAgain ? retryOn : projectCache.all();
for (Project.NameKey projectName : names) {
ProjectConfig config = projectCache.get(projectName).getConfig();
ProjectConfig config =
projectCache.get(projectName).orElseThrow(illegalState(projectName)).getConfig();
GroupReference ref = config.getGroup(uuid);
if (ref == null || newName.equals(ref.getName())) {
continue;

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.server.index.project;
import static com.google.gerrit.server.git.QueueProvider.QueueType.BATCH;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.base.Stopwatch;
import com.google.common.flogger.FluentLogger;
@@ -78,7 +79,8 @@ public class AllProjectsIndexer extends SiteIndexer<Project.NameKey, ProjectData
() -> {
try {
projectCache.evict(name);
index.replace(projectCache.get(name).toProjectData());
index.replace(
projectCache.get(name).orElseThrow(illegalState(name)).toProjectData());
verboseWriter.println("Reindexed " + desc);
done.incrementAndGet();
} catch (Exception e) {

View File

@@ -34,6 +34,7 @@ import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
/**
* Implementation for indexing a Gerrit-managed repository (project). The project will be loaded
@@ -77,10 +78,10 @@ public class ProjectIndexerImpl implements ProjectIndexer {
@Override
public void index(Project.NameKey nameKey) {
ProjectState projectState = projectCache.get(nameKey);
if (projectState != null) {
Optional<ProjectState> projectState = projectCache.get(nameKey);
if (projectState.isPresent()) {
logger.atFine().log("Replace project %s in index", nameKey.get());
ProjectData projectData = projectState.toProjectData();
ProjectData projectData = projectState.get().toProjectData();
for (ProjectIndex i : getWriteIndexes()) {
try (TraceTimer traceTimer =
TraceContext.newTimer(

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.index.project;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.SetMultimap;
@@ -57,7 +59,8 @@ public class StalenessChecker {
* provided {@link com.google.gerrit.entities.Project.NameKey}.
*/
public StalenessCheckResult check(Project.NameKey project) {
ProjectData projectData = projectCache.get(project).toProjectData();
ProjectData projectData =
projectCache.get(project).orElseThrow(illegalState(project)).toProjectData();
ProjectIndex i = indexes.getSearchIndex();
if (i == null) {
return StalenessCheckResult

View File

@@ -142,7 +142,7 @@ public abstract class ChangeEmail extends NotificationEmail {
@Override
protected void init() throws EmailException {
if (args.projectCache != null) {
projectState = args.projectCache.get(change.getProject());
projectState = args.projectCache.get(change.getProject()).orElse(null);
} else {
projectState = null;
}

View File

@@ -41,6 +41,7 @@ import static com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TAG;
import static com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TOPIC;
import static com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_WORK_IN_PROGRESS;
import static com.google.gerrit.server.notedb.NoteDbUtil.sanitizeFooter;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Comparator.naturalOrder;
import static java.util.Objects.requireNonNull;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
@@ -169,7 +170,11 @@ public class ChangeUpdate extends AbstractChangeUpdate {
notes,
user,
when,
projectCache.get(notes.getProjectName()).getLabelTypes().nameComparator(),
projectCache
.get(notes.getProjectName())
.orElseThrow(illegalState(notes.getProjectName()))
.getLabelTypes()
.nameComparator(),
noteUtil);
}

View File

@@ -65,7 +65,16 @@ public class ChildProjects {
private Map<Project.NameKey, Project> readAllReadableProjects() {
Map<Project.NameKey, Project> projects = new HashMap<>();
for (Project.NameKey name : projectCache.all()) {
ProjectState c = projectCache.get(name);
ProjectState c =
projectCache
.get(name)
.orElseThrow(
() ->
new IllegalStateException(
"race while traversing projects. got "
+ name
+ " when loading all projects, but can't load it now"));
if (c != null && c.statePermitsRead()) {
projects.put(c.getNameKey(), c.getProject());
}

View File

@@ -20,10 +20,28 @@ import com.google.gerrit.entities.AccountGroup;
import com.google.gerrit.entities.Project;
import com.google.gerrit.exceptions.StorageException;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
/** Cache of project information, including access rights. */
public interface ProjectCache {
/**
* Returns a supplier to be used as a short-hand when unwrapping an {@link Optional} returned from
* this cache.
*/
static Supplier<IllegalStateException> illegalState(Project.NameKey nameKey) {
return () -> new IllegalStateException("unable to find project " + nameKey);
}
/**
* Returns a supplier to be used as a short-hand when unwrapping an {@link Optional} returned from
* this cache.
*/
static Supplier<NoSuchProjectException> noSuchProject(Project.NameKey nameKey) {
return () -> new NoSuchProjectException(nameKey);
}
/** @return the parent state for all projects on this server. */
ProjectState getAllProjects();
@@ -34,11 +52,12 @@ public interface ProjectCache {
* Get the cached data for a project by its unique name.
*
* @param projectName name of the project.
* @return the cached data; null if no such project exists or the projectName is null
* @return an {@link Optional} wrapping the the cached data; {@code absent} if no such project
* exists or the projectName is null
* @throws StorageException when there was an error.
* @see #checkedGet(com.google.gerrit.entities.Project.NameKey)
*/
ProjectState get(@Nullable Project.NameKey projectName) throws StorageException;
Optional<ProjectState> get(@Nullable Project.NameKey projectName) throws StorageException;
/**
* Get the cached data for a project by its unique name.

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.project;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.stream.Collectors.toSet;
import com.google.common.annotations.VisibleForTesting;
@@ -48,6 +49,7 @@ import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
@@ -125,29 +127,18 @@ public class ProjectCacheImpl implements ProjectCache {
@Override
public ProjectState getAllProjects() {
ProjectState state = get(allProjectsName);
if (state == null) {
// This should never occur, the server must have this
// project to process anything.
throw new IllegalStateException("Missing project " + allProjectsName);
}
return state;
return get(allProjectsName).orElseThrow(illegalState(allProjectsName));
}
@Override
public ProjectState getAllUsers() {
ProjectState state = get(allUsersName);
if (state == null) {
// This should never occur.
throw new IllegalStateException("Missing project " + allUsersName);
}
return state;
return get(allUsersName).orElseThrow(illegalState(allUsersName));
}
@Override
public ProjectState get(Project.NameKey projectName) {
public Optional<ProjectState> get(Project.NameKey projectName) {
try {
return checkedGet(projectName);
return Optional.ofNullable(checkedGet(projectName));
} catch (IOException e) {
throw new StorageException("project state not available", e);
}

View File

@@ -53,7 +53,16 @@ public class ProjectCacheWarmer implements LifecycleListener {
new Thread(
() -> {
for (Project.NameKey name : cache.all()) {
pool.execute(() -> cache.get(name));
pool.execute(
() ->
cache
.get(name)
.orElseThrow(
() ->
new IllegalStateException(
"race while traversing projects. got "
+ name
+ " when loading all projects, but can't load it now")));
}
pool.shutdown();
try {

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.project;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.base.MoreObjects;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.AccessSection;
@@ -124,7 +126,7 @@ public class ProjectCreator {
fire(nameKey, head);
return projectCache.get(nameKey);
return projectCache.get(nameKey).orElseThrow(illegalState(nameKey));
}
} catch (RepositoryCaseMismatchException e) {
throw new ResourceConflictException(

View File

@@ -23,6 +23,7 @@ import com.google.gerrit.server.config.AllProjectsName;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
/**
@@ -65,16 +66,16 @@ class ProjectHierarchyIterator implements Iterator<ProjectState> {
private ProjectState computeNext(ProjectState n) {
Project.NameKey parentName = n.getProject().getParent();
if (parentName != null && visit(parentName)) {
ProjectState p = cache.get(parentName);
if (p != null) {
return p;
Optional<ProjectState> p = cache.get(parentName);
if (p.isPresent()) {
return p.get();
}
}
// Parent does not exist or was already visited.
// Fall back to visit All-Projects exactly once.
if (seen.add(allProjectsName)) {
return cache.get(allProjectsName);
return cache.getAllProjects();
}
return null;
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.project;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import com.google.common.collect.Streams;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.SubmitRecord;
@@ -108,17 +110,13 @@ public class SubmitRuleEvaluator {
public List<SubmitRecord> evaluate(ChangeData cd) {
try (Timer0.Context ignored = submitRuleEvaluationLatency.start()) {
Change change;
ProjectState projectState;
try {
change = cd.change();
if (change == null) {
throw new StorageException("Change not found");
}
projectState = projectCache.get(cd.project());
if (projectState == null) {
throw new NoSuchProjectException(cd.project());
}
projectCache.get(cd.project()).orElseThrow(noSuchProject(cd.project()));
} catch (StorageException | NoSuchProjectException e) {
return Collections.singletonList(ruleError("Error looking up change " + cd.getId(), e));
}
@@ -154,10 +152,7 @@ public class SubmitRuleEvaluator {
try (Timer0.Context ignored = submitTypeEvaluationLatency.start()) {
ProjectState projectState;
try {
projectState = projectCache.get(cd.project());
if (projectState == null) {
throw new NoSuchProjectException(cd.project());
}
projectState = projectCache.get(cd.project()).orElseThrow(noSuchProject(cd.project()));
} catch (NoSuchProjectException e) {
return typeError("Error looking up change " + cd.getId(), e);
}

View File

@@ -25,6 +25,7 @@ import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Singleton
@@ -51,9 +52,9 @@ public class SuggestParentCandidates {
private Set<Project.NameKey> readableParents() {
Set<Project.NameKey> parents = new HashSet<>();
for (Project.NameKey p : projectCache.all()) {
ProjectState ps = projectCache.get(p);
if (ps != null && ps.statePermitsRead()) {
Project.NameKey parent = ps.getProject().getParent();
Optional<ProjectState> ps = projectCache.get(p);
if (ps.isPresent() && ps.get().statePermitsRead()) {
Project.NameKey parent = ps.get().getProject().getParent();
if (parent != null) {
parents.add(parent);
}

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.query.change;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
@@ -915,7 +916,9 @@ public class ChangeData {
return false;
}
String mergeStrategy =
mergeUtilFactory.create(projectCache.get(project())).mergeStrategyName();
mergeUtilFactory
.create(projectCache.get(project()).orElseThrow(illegalState(project())))
.mergeStrategyName();
mergeable =
mergeabilityCache.get(ps.commitId(), ref, str.type, mergeStrategy, c.getDest(), repo);
} catch (IOException e) {

View File

@@ -16,6 +16,7 @@ package com.google.gerrit.server.query.change;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.flogger.LazyArgs.lazy;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import static java.util.concurrent.TimeUnit.MINUTES;
import com.google.common.flogger.FluentLogger;
@@ -218,10 +219,7 @@ public class ConflictsPredicate {
ProjectState getProjectState() throws NoSuchProjectException {
if (projectState == null) {
projectState = projectCache.get(cd.project());
if (projectState == null) {
throw new NoSuchProjectException(cd.project());
}
projectState = projectCache.get(cd.project()).orElseThrow(noSuchProject(cd.project()));
}
return projectState;
}

View File

@@ -29,6 +29,7 @@ import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import java.io.IOException;
import java.util.Optional;
public class EqualsLabelPredicate extends ChangeIndexPredicate {
protected final ProjectCache projectCache;
@@ -60,14 +61,14 @@ public class EqualsLabelPredicate extends ChangeIndexPredicate {
return false;
}
ProjectState project = projectCache.get(c.getDest().project());
if (project == null) {
Optional<ProjectState> project = projectCache.get(c.getDest().project());
if (!project.isPresent()) {
// The project has disappeared.
//
return false;
}
LabelType labelType = type(project.getLabelTypes(), label);
LabelType labelType = type(project.get().getLabelTypes(), label);
if (labelType == null) {
return false; // Label is not defined by this project.
}

View File

@@ -26,6 +26,7 @@ import com.google.gerrit.server.project.ProjectState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class ParentProjectPredicate extends OrPredicate<ChangeData> {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@@ -40,15 +41,15 @@ public class ParentProjectPredicate extends OrPredicate<ChangeData> {
protected static List<Predicate<ChangeData>> predicates(
ProjectCache projectCache, ChildProjects childProjects, String value) {
ProjectState projectState = projectCache.get(Project.nameKey(value));
if (projectState == null) {
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(value));
if (!projectState.isPresent()) {
return Collections.emptyList();
}
List<Predicate<ChangeData>> r = new ArrayList<>();
r.add(new ProjectPredicate(projectState.getName()));
r.add(new ProjectPredicate(projectState.get().getName()));
try {
for (ProjectInfo p : childProjects.list(projectState.getNameKey())) {
for (ProjectInfo p : childProjects.list(projectState.get().getNameKey())) {
r.add(new ProjectPredicate(p.name));
}
} catch (PermissionBackendException e) {

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.restapi.change;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static com.google.gerrit.util.cli.Localizable.localizable;
import com.google.common.base.MoreObjects;
@@ -146,7 +147,7 @@ public class GetDiff implements RestReadView<FileResource> {
psf.setLoadComments(context != DiffPreferencesInfo.WHOLE_FILE_CONTEXT);
PatchScript ps = psf.call();
Project.NameKey projectName = resource.getRevision().getChange().getProject();
ProjectState state = projectCache.get(projectName);
ProjectState state = projectCache.get(projectName).orElseThrow(illegalState(projectName));
DiffSide sideA =
DiffSide.create(
ps.getFileInfoA(),

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.restapi.change;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.stream.Collectors.groupingBy;
import com.google.common.base.MoreObjects;
@@ -78,7 +79,8 @@ public class GetFixPreview implements RestReadView<FixResource> {
PatchSet patchSet = resource.getRevisionResource().getPatchSet();
ChangeNotes notes = resource.getRevisionResource().getNotes();
Change change = notes.getChange();
ProjectState state = projectCache.get(change.getProject());
ProjectState state =
projectCache.get(change.getProject()).orElseThrow(illegalState(change.getProject()));
Map<String, List<FixReplacement>> fixReplacementsPerFilePath =
resource.getFixReplacements().stream()
.collect(groupingBy(fixReplacement -> fixReplacement.path));

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.restapi.change;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.gerrit.common.data.SubmitTypeRecord;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.PatchSet;
@@ -105,7 +107,8 @@ public class Mergeable implements RestReadView<RevisionResource> {
try (Repository git = gitManager.openRepository(change.getProject())) {
ObjectId commit = ps.commitId();
Ref ref = git.getRefDatabase().exactRef(change.getDest().branch());
ProjectState projectState = projectCache.get(change.getProject());
ProjectState projectState =
projectCache.get(change.getProject()).orElseThrow(illegalState(change.getProject()));
String strategy = mergeUtilFactory.create(projectState).mergeStrategyName();
result.strategy = strategy;
result.mergeable = isMergable(git, change, commit, ref, result.submitType, strategy);

View File

@@ -75,10 +75,10 @@ public class TestSubmitRule implements RestModifyView<RevisionResource, TestSubm
}
input.filters = MoreObjects.firstNonNull(input.filters, filters);
ProjectState projectState = projectCache.get(rsrc.getProject());
if (projectState == null) {
throw new BadRequestException("project not found");
}
ProjectState projectState =
projectCache
.get(rsrc.getProject())
.orElseThrow(() -> new BadRequestException("project not found " + rsrc.getProject()));
ChangeData cd = changeDataFactory.create(rsrc.getNotes());
SubmitRecord record =
prologRule.evaluate(

View File

@@ -41,6 +41,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Singleton
@@ -85,8 +86,8 @@ public class ListTasks implements RestReadView<ConfigResource> {
Boolean visible = visibilityCache.get(task.projectName);
if (visible == null) {
Project.NameKey nameKey = Project.nameKey(task.projectName);
ProjectState state = projectCache.get(nameKey);
if (state == null || !state.statePermitsRead()) {
Optional<ProjectState> state = projectCache.get(nameKey);
if (!state.isPresent() || !state.get().statePermitsRead()) {
visible = false;
} else {
try {

View File

@@ -37,6 +37,7 @@ import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.util.Optional;
@Singleton
public class TasksCollection implements ChildCollection<ConfigResource, TaskResource> {
@@ -87,12 +88,12 @@ public class TasksCollection implements ChildCollection<ConfigResource, TaskReso
Task<?> task = workQueue.getTask(taskId);
if (task instanceof ProjectTask) {
Project.NameKey nameKey = ((ProjectTask<?>) task).getProjectNameKey();
ProjectState state = projectCache.get(nameKey);
if (state == null) {
Optional<ProjectState> state = projectCache.get(nameKey);
if (!state.isPresent()) {
throw new ResourceNotFoundException(String.format("project %s not found", nameKey));
}
state.checkStatePermitsRead();
state.get().checkStatePermitsRead();
try {
permissionBackend.user(user).project(nameKey).check(ProjectPermission.ACCESS);

View File

@@ -75,7 +75,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedMap;
import java.util.SortedSet;
@@ -610,7 +609,8 @@ public class ListProjects implements RestReadView<TopLevelResource> {
private Stream<ProjectState> filter(PermissionBackend.WithUser perm) throws BadRequestException {
return StreamSupport.stream(scan().spliterator(), false)
.map(projectCache::get)
.filter(Objects::nonNull)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(p -> permissionCheck(p, perm));
}

View File

@@ -156,10 +156,14 @@ public class SetParent
newParent = Strings.emptyToNull(newParent);
if (newParent != null) {
ProjectState parent = cache.get(Project.nameKey(newParent));
if (parent == null) {
throw new UnprocessableEntityException("parent project " + newParent + " not found");
}
Project.NameKey newParentNameKey = Project.nameKey(newParent);
ProjectState parent =
cache
.get(newParentNameKey)
.orElseThrow(
() ->
new UnprocessableEntityException(
"parent project " + newParentNameKey + " not found"));
if (parent.getName().equals(project.get())) {
throw new ResourceConflictException("cannot set parent to self");

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.server.rules;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.common.data.LabelFunction;
@@ -63,11 +64,12 @@ public final class DefaultSubmitRule implements SubmitRule {
@Override
public Optional<SubmitRecord> evaluate(ChangeData cd) {
ProjectState projectState = projectCache.get(cd.project());
ProjectState projectState =
projectCache.get(cd.project()).orElseThrow(illegalState(cd.project()));
// In case at least one project has a rules.pl file, we let Prolog handle it.
// The Prolog rules engine will also handle the labels for us.
if (projectState == null || projectState.hasPrologRules()) {
if (projectState.hasPrologRules()) {
return Optional.empty();
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.rules;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.common.data.SubmitTypeRecord;
import com.google.gerrit.server.project.ProjectCache;
@@ -36,9 +38,10 @@ public class PrologRule implements SubmitRule {
@Override
public Optional<SubmitRecord> evaluate(ChangeData cd) {
ProjectState projectState = projectCache.get(cd.project());
ProjectState projectState =
projectCache.get(cd.project()).orElseThrow(illegalState(cd.project()));
// We only want to run the Prolog engine if we have at least one rules.pl file to use.
if ((projectState == null || !projectState.hasPrologRules())) {
if (!projectState.hasPrologRules()) {
return Optional.empty();
}

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.server.rules;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static com.google.gerrit.server.project.SubmitRuleEvaluator.createRuleError;
import static com.google.gerrit.server.project.SubmitRuleEvaluator.defaultRuleError;
import static com.google.gerrit.server.project.SubmitRuleEvaluator.defaultTypeError;
@@ -115,7 +116,7 @@ public class PrologRuleEvaluator {
this.cd = cd;
this.opts = options;
this.projectState = projectCache.get(cd.project());
this.projectState = projectCache.get(cd.project()).orElseThrow(illegalState(cd.project()));
}
private static Term toListTerm(List<Term> terms) {

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.server.submit;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.Maps;
@@ -185,10 +186,7 @@ public class MergeOpRepoManager implements AutoCloseable {
return openRepos.get(project);
}
ProjectState projectState = projectCache.get(project);
if (projectState == null) {
throw new NoSuchProjectException(project);
}
ProjectState projectState = projectCache.get(project).orElseThrow(noSuchProject(project));
try {
OpenRepo or = new OpenRepo(repoManager.openRepository(project), projectState);
openRepos.put(project, or);

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.submit;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import static java.util.stream.Collectors.toSet;
import com.google.common.collect.ImmutableSet;
@@ -156,10 +157,6 @@ public class SubmitDryRun {
}
private ProjectState getProject(BranchNameKey branch) throws NoSuchProjectException {
ProjectState p = projectCache.get(branch.project());
if (p == null) {
throw new NoSuchProjectException(branch.project());
}
return p;
return projectCache.get(branch.project()).orElseThrow(noSuchProject(branch.project()));
}
}

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.server.submit;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableMap;
@@ -200,9 +201,7 @@ public abstract class SubmitStrategy {
this.dryrun = dryrun;
this.project =
requireNonNull(
projectCache.get(destBranch.project()),
() -> String.format("project not found: %s", destBranch.project()));
projectCache.get(destBranch.project()).orElseThrow(illegalState(destBranch.project()));
this.mergeSorter =
new MergeSorter(caller, rw, alreadyAccepted, canMergeFlag, queryProvider, incoming);
this.rebaseSorter =

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.server.submit;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;
@@ -486,7 +487,8 @@ abstract class SubmitStrategyOp implements BatchUpdateOp {
// per project even if multiple changes to refs/meta/config are submitted.
if (RefNames.REFS_CONFIG.equals(getDest().branch())) {
args.projectCache.evict(getProject());
ProjectState p = args.projectCache.get(getProject());
ProjectState p =
args.projectCache.get(getProject()).orElseThrow(illegalState(getProject()));
try (Repository git = args.repoManager.openRepository(getProject())) {
git.setGitwebDescription(p.getProject().getDescription());
} catch (IOException e) {

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.server.submit;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
@@ -362,7 +363,11 @@ public class SubmoduleOp {
logger.atFine().log("Calculating possible superprojects for %s", srcBranch);
Collection<SubmoduleSubscription> ret = new ArrayList<>();
Project.NameKey srcProject = srcBranch.project();
for (SubscribeSection s : projectCache.get(srcProject).getSubscribeSections(srcBranch)) {
for (SubscribeSection s :
projectCache
.get(srcProject)
.orElseThrow(illegalState(srcProject))
.getSubscribeSections(srcBranch)) {
logger.atFine().log("Checking subscribe section %s", s);
Collection<BranchNameKey> branches = getDestinationBranches(srcBranch, s);
for (BranchNameKey targetBranch : branches) {

View File

@@ -14,6 +14,7 @@
package com.google.gerrit.sshd.commands;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.entities.Project;
@@ -37,6 +38,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
@@ -117,7 +119,7 @@ final class SetParentCommand extends SshCommand {
for (Project.NameKey nameKey : childProjects) {
final String name = nameKey.get();
ProjectState project = projectCache.get(nameKey);
ProjectState project = projectCache.get(nameKey).orElseThrow(illegalState(nameKey));
try {
setParent.apply(new ProjectResource(project, user), parentInput(newParentKey.get()));
} catch (AuthException e) {
@@ -177,10 +179,10 @@ final class SetParentCommand extends SshCommand {
}
private Set<Project.NameKey> getAllParents(Project.NameKey projectName) {
ProjectState ps = projectCache.get(projectName);
if (ps == null) {
Optional<ProjectState> ps = projectCache.get(projectName);
if (!ps.isPresent()) {
return Collections.emptySet();
}
return ps.parents().transform(ProjectState::getNameKey).toSet();
return ps.get().parents().transform(ProjectState::getNameKey).toSet();
}
}

View File

@@ -14,8 +14,8 @@
package com.google.gerrit.sshd.commands;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
@@ -245,8 +245,8 @@ public class UploadArchive extends AbstractGitCommand {
}
private boolean canRead(ObjectId revId) throws IOException, PermissionBackendException {
ProjectState projectState = projectCache.get(projectName);
requireNonNull(projectState, () -> String.format("Failed to load project %s", projectName));
ProjectState projectState =
projectCache.get(projectName).orElseThrow(illegalState(projectName));
if (!projectState.statePermitsRead()) {
return false;

View File

@@ -91,9 +91,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
// for more extensive coverage of the LabelTypeInfo.
assertThat(p.labels).hasSize(1);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertProjectInfo(projectState.getProject(), p);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertProjectInfo(projectState.get().getProject(), p);
assertHead(newProjectName, "refs/heads/master");
}
@@ -167,9 +167,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
String newProjectName = name("newProject");
ProjectInfo p = gApi.projects().create(newProjectName).get();
assertThat(p.name).isEqualTo(newProjectName);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertProjectInfo(projectState.getProject(), p);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertProjectInfo(projectState.get().getProject(), p);
assertHead(newProjectName, "refs/heads/master");
assertThat(readProjectConfig(newProjectName))
.hasValue("[access]\n\tinheritFrom = All-Projects\n[submit]\n\taction = inherit\n");
@@ -180,9 +180,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
String newProjectName = name("newProject");
ProjectInfo p = gApi.projects().create(newProjectName + ".git").get();
assertThat(p.name).isEqualTo(newProjectName);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertProjectInfo(projectState.getProject(), p);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertProjectInfo(projectState.get().getProject(), p);
assertHead(newProjectName, "refs/heads/master");
}
@@ -191,9 +191,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
String newProjectName = name("newProject");
ProjectInfo p = gApi.projects().create(newProjectName + "/").get();
assertThat(p.name).isEqualTo(newProjectName);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertProjectInfo(projectState.getProject(), p);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertProjectInfo(projectState.get().getProject(), p);
assertHead(newProjectName, "refs/heads/master");
}
@@ -202,9 +202,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
String newProjectName = name("newProject/newProject");
ProjectInfo p = gApi.projects().create(newProjectName).get();
assertThat(p.name).isEqualTo(newProjectName);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertProjectInfo(projectState.getProject(), p);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertProjectInfo(projectState.get().getProject(), p);
assertHead(newProjectName, "refs/heads/master");
}
@@ -221,7 +221,7 @@ public class CreateProjectIT extends AbstractDaemonTest {
in.requireChangeId = InheritableBoolean.TRUE;
ProjectInfo p = gApi.projects().create(in).get();
assertThat(p.name).isEqualTo(newProjectName);
Project project = projectCache.get(Project.nameKey(newProjectName)).getProject();
Project project = projectCache.get(Project.nameKey(newProjectName)).get().getProject();
assertProjectInfo(project, p);
assertThat(project.getDescription()).isEqualTo(in.description);
assertThat(project.getConfiguredSubmitType()).isEqualTo(in.submitType);
@@ -247,7 +247,7 @@ public class CreateProjectIT extends AbstractDaemonTest {
in.name = childName;
in.parent = parentName;
gApi.projects().create(in);
Project project = projectCache.get(Project.nameKey(childName)).getProject();
Project project = projectCache.get(Project.nameKey(childName)).get().getProject();
assertThat(project.getParentName()).isEqualTo(in.parent);
}
@@ -275,12 +275,13 @@ public class CreateProjectIT extends AbstractDaemonTest {
.getId()
.get())); // by ID
gApi.projects().create(in);
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
Set<AccountGroup.UUID> expectedOwnerIds = Sets.newHashSetWithExpectedSize(3);
expectedOwnerIds.add(SystemGroupBackend.ANONYMOUS_USERS);
expectedOwnerIds.add(SystemGroupBackend.REGISTERED_USERS);
expectedOwnerIds.add(groupUuid("Administrators"));
assertProjectOwners(expectedOwnerIds, projectState);
assertThat(projectState).isPresent();
assertProjectOwners(expectedOwnerIds, projectState.get());
}
@Test
@@ -367,7 +368,7 @@ public class CreateProjectIT extends AbstractDaemonTest {
@Test
public void createProjectWithCreateProjectCapabilityAndParentNotVisible() throws Exception {
Project parent = projectCache.get(allProjects).getProject();
Project parent = projectCache.get(allProjects).get().getProject();
parent.setState(com.google.gerrit.extensions.client.ProjectState.HIDDEN);
projectOperations
.allProjectsForUpdate()

View File

@@ -49,7 +49,7 @@ public class GetChildProjectIT extends AbstractDaemonTest {
Project.NameKey child = projectOperations.newProject().create();
ProjectInfo childInfo = gApi.projects().name(allProjects.get()).child(child.get()).get();
assertProjectInfo(projectCache.get(child).getProject(), childInfo);
assertProjectInfo(projectCache.get(child).get().getProject(), childInfo);
}
@Test
@@ -67,7 +67,7 @@ public class GetChildProjectIT extends AbstractDaemonTest {
ProjectInfo grandChildInfo =
gApi.projects().name(allProjects.get()).child(grandChild.get()).get(true);
assertProjectInfo(projectCache.get(grandChild).getProject(), grandChildInfo);
assertProjectInfo(projectCache.get(grandChild).get().getProject(), grandChildInfo);
}
private void assertChildNotFound(Project.NameKey parent, String child) throws Exception {

View File

@@ -50,13 +50,13 @@ public class ProjectLevelConfigIT extends AbstractDaemonTest {
admin.newIdent(), testRepo, "Create Project Level Config", configName, cfg.toText());
push.to(RefNames.REFS_CONFIG);
ProjectState state = projectCache.get(project);
ProjectState state = projectCache.get(project).get();
assertThat(state.getConfig(configName).get().toText()).isEqualTo(cfg.toText());
}
@Test
public void nonExistingConfig() {
ProjectState state = projectCache.get(project);
ProjectState state = projectCache.get(project).get();
assertThat(state.getConfig("test.config").get().toText()).isEqualTo("");
}
@@ -99,7 +99,7 @@ public class ProjectLevelConfigIT extends AbstractDaemonTest {
.to(RefNames.REFS_CONFIG)
.assertOkStatus();
ProjectState state = projectCache.get(childProject);
ProjectState state = projectCache.get(childProject).get();
Config expectedCfg = new Config();
expectedCfg.setString("s1", null, "k1", "childValue1");
@@ -158,7 +158,7 @@ public class ProjectLevelConfigIT extends AbstractDaemonTest {
.to(RefNames.REFS_CONFIG)
.assertOkStatus();
ProjectState state = projectCache.get(childProject);
ProjectState state = projectCache.get(childProject).get();
Config expectedCfg = new Config();
expectedCfg.setStringList("s1", null, "k1", Arrays.asList("childValue1", "parentValue1"));

View File

@@ -15,11 +15,13 @@
package com.google.gerrit.acceptance.ssh;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.UseSsh;
import com.google.gerrit.entities.Project;
import com.google.gerrit.server.project.ProjectState;
import java.util.Optional;
import org.junit.Test;
@UseSsh
@@ -33,8 +35,8 @@ public class CreateProjectIT extends AbstractDaemonTest {
adminSshSession.exec(
"gerrit create-project --branch master --owner " + newGroupName + " " + newProjectName);
adminSshSession.assertSuccess();
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
}
@Test
@@ -46,8 +48,8 @@ public class CreateProjectIT extends AbstractDaemonTest {
adminSshSession.exec(
"gerrit create-project --branch master --owner " + wrongGroupName + " " + newProjectName);
adminSshSession.assertFailure();
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNull();
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isEmpty();
}
@Test
@@ -62,9 +64,9 @@ public class CreateProjectIT extends AbstractDaemonTest {
+ newProjectName
+ ".git");
adminSshSession.assertSuccess();
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertThat(projectState.getName()).isEqualTo(newProjectName);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertThat(projectState.get().getName()).isEqualTo(newProjectName);
}
@Test
@@ -79,8 +81,8 @@ public class CreateProjectIT extends AbstractDaemonTest {
+ newProjectName
+ "/");
adminSshSession.assertSuccess();
ProjectState projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isNotNull();
assertThat(projectState.getName()).isEqualTo(newProjectName);
Optional<ProjectState> projectState = projectCache.get(Project.nameKey(newProjectName));
assertThat(projectState).isPresent();
assertThat(projectState.get().getName()).isEqualTo(newProjectName);
}
}

View File

@@ -207,7 +207,7 @@ public class CommitsCollectionTest {
}
private ProjectState readProjectState() throws Exception {
return projectCache.get(project);
return projectCache.get(project).get();
}
private void setUpPermissions() throws Exception {