src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CentralDogmaConfig { @JsonProperty public long maxRemovedRepositoryAgeMillis() { return maxRemovedRepositoryAgeMillis; } CentralDogmaConfig(
@JsonProperty(value = "dataDir", required = true) File dataDir,
@JsonProperty(value = "ports", required = true)
@JsonDeserialize(contentUsing = ServerPortDeserializer.class)
List<ServerPort> ports,
@JsonProperty("tls") @Nullable TlsConfig tls,
@JsonProperty("trustedProxyAddresses") @Nullable List<String> trustedProxyAddresses,
@JsonProperty("clientAddressSources") @Nullable List<String> clientAddressSources,
@JsonProperty("numWorkers") @Nullable Integer numWorkers,
@JsonProperty("maxNumConnections") @Nullable Integer maxNumConnections,
@JsonProperty("requestTimeoutMillis") @Nullable Long requestTimeoutMillis,
@JsonProperty("idleTimeoutMillis") @Nullable Long idleTimeoutMillis,
@JsonProperty("maxFrameLength") @Nullable Integer maxFrameLength,
@JsonProperty("numRepositoryWorkers") @Nullable Integer numRepositoryWorkers,
@JsonProperty("repositoryCacheSpec") @Nullable String repositoryCacheSpec,
@JsonProperty("maxRemovedRepositoryAgeMillis") @Nullable Long maxRemovedRepositoryAgeMillis,
@JsonProperty("gracefulShutdownTimeout") @Nullable GracefulShutdownTimeout gracefulShutdownTimeout,
@JsonProperty("webAppEnabled") @Nullable Boolean webAppEnabled,
@JsonProperty("webAppTitle") @Nullable String webAppTitle,
@JsonProperty("mirroringEnabled") @Nullable Boolean mirroringEnabled,
@JsonProperty("numMirroringThreads") @Nullable Integer numMirroringThreads,
@JsonProperty("maxNumFilesPerMirror") @Nullable Integer maxNumFilesPerMirror,
@JsonProperty("maxNumBytesPerMirror") @Nullable Long maxNumBytesPerMirror,
@JsonProperty("replication") @Nullable ReplicationConfig replicationConfig,
@JsonProperty("csrfTokenRequiredForThrift") @Nullable Boolean csrfTokenRequiredForThrift,
@JsonProperty("accessLogFormat") @Nullable String accessLogFormat,
@JsonProperty("authentication") @Nullable AuthConfig authConfig); @JsonProperty File dataDir(); @JsonProperty @JsonSerialize(contentUsing = ServerPortSerializer.class) List<ServerPort> ports(); @Nullable @JsonProperty TlsConfig tls(); @Nullable @JsonProperty List<String> trustedProxyAddresses(); @Nullable @JsonProperty List<String> clientAddressSources(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<Integer> numWorkers(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<Integer> maxNumConnections(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<Long> requestTimeoutMillis(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<Long> idleTimeoutMillis(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<Integer> maxFrameLength(); @JsonProperty long maxRemovedRepositoryAgeMillis(); @JsonProperty @Deprecated String cacheSpec(); @JsonProperty String repositoryCacheSpec(); @JsonProperty @JsonSerialize(converter = OptionalConverter.class) Optional<GracefulShutdownTimeout> gracefulShutdownTimeout(); @JsonProperty boolean isWebAppEnabled(); @Nullable @JsonProperty("webAppTitle") String webAppTitle(); @JsonProperty boolean isMirroringEnabled(); @JsonProperty int numMirroringThreads(); @JsonProperty int maxNumFilesPerMirror(); @JsonProperty long maxNumBytesPerMirror(); @JsonProperty("replication") ReplicationConfig replicationConfig(); @JsonProperty boolean isCsrfTokenRequiredForThrift(); @JsonProperty @Nullable String accessLogFormat(); @Nullable @JsonProperty("authentication") AuthConfig authConfig(); @Override String toString(); } | @Test void maxRemovedRepositoryAgeMillis() throws Exception { final CentralDogmaConfig cfg = Jackson.readValue("{\n" + " \"dataDir\": \"./data\",\n" + " \"ports\": [\n" + " {\n" + " \"localAddress\": {\n" + " \"host\": \"*\",\n" + " \"port\": 36462\n" + " },\n" + " \"protocols\": [\n" + " \"https\",\n" + " \"http\",\n" + " \"proxy\"\n" + " ]\n" + " }\n" + " ],\n" + " \"maxRemovedRepositoryAgeMillis\": 50000 \n" + '}', CentralDogmaConfig.class); assertThat(cfg.maxRemovedRepositoryAgeMillis()).isEqualTo(50000); }
@Test void maxRemovedRepositoryAgeMillis_withDefault() throws Exception { final CentralDogmaConfig cfg = Jackson.readValue("{\n" + " \"dataDir\": \"./data\",\n" + " \"ports\": [\n" + " {\n" + " \"localAddress\": {\n" + " \"host\": \"*\",\n" + " \"port\": 36462\n" + " },\n" + " \"protocols\": [\n" + " \"https\",\n" + " \"http\",\n" + " \"proxy\"\n" + " ]\n" + " }\n" + " ]\n" + '}', CentralDogmaConfig.class); assertThat(cfg.maxRemovedRepositoryAgeMillis()).isEqualTo(DEFAULT_MAX_REMOVED_REPOSITORY_AGE_MILLIS); } |
Util { public static String validateFilePath(String path, String paramName) { requireNonNull(path, paramName); checkArgument(isValidFilePath(path), "%s: %s (expected: %s)", paramName, path, FILE_PATH_PATTERN); return path; } private Util(); static String validateFileName(String name, String paramName); static boolean isValidFileName(String name); static String validateFilePath(String path, String paramName); static boolean isValidFilePath(String path); static String validateJsonFilePath(String path, String paramName); static boolean isValidJsonFilePath(String path); static String validateJsonPath(String jsonPath, String paramName); static boolean isValidJsonPath(String jsonPath); static String validateDirPath(String path, String paramName); static boolean isValidDirPath(String path); static boolean isValidDirPath(String path, boolean mustEndWithSlash); static String validatePathPattern(String pathPattern, String paramName); static boolean isValidPathPattern(String pathPattern); static String validateProjectName(String projectName, String paramName); static boolean isValidProjectName(String projectName); static String validateRepositoryName(String repoName, String paramName); static boolean isValidRepositoryName(String repoName); static String validateEmailAddress(String emailAddr, String paramName); static boolean isValidEmailAddress(String emailAddr); static String toEmailAddress(String emailAddr, String paramName); static String emailToUsername(String emailAddr, String paramName); static List<String> stringToLines(String str); static String simpleTypeName(Object obj); static String simpleTypeName(Class<?> clazz); static String simpleTypeName(Class<?> clazz, boolean decapitalize); @SuppressWarnings("unchecked") static T unsafeCast(Object o); static Iterable<T> requireNonNullElements(Iterable<T> values, String name); static void deleteFileTree(File directory); } | @Test void testValidateFilePath() { assertFilePathValidationSuccess("/foo.txt"); assertFilePathValidationSuccess("/foo/bar.txt"); assertFilePathValidationSuccess("/foo.bar/baz.json"); assertFilePathValidationSuccess("/foo-bar/baz-json"); assertFilePathValidationFailure("foo"); assertFilePathValidationFailure("/"); assertFilePathValidationFailure("/foo/"); assertFilePathValidationFailure(" assertFilePathValidationFailure("/foo assertFilePathValidationFailure("/."); assertFilePathValidationFailure("/.."); assertFilePathValidationFailure("/.foo"); assertFilePathValidationFailure("/foo."); assertFilePathValidationFailure("/.foo."); assertFilePathValidationFailure("/\t"); assertFilePathValidationFailure("/80:20"); assertFilePathValidationFailure("/foo*.txt"); assertFilePathValidationFailure("/bar?.txt"); assertFilePathValidationFailure("/baz|.txt"); assertFilePathValidationFailure("/\uAC00\uB098\uB2E4.json"); } |
Util { public static String validateJsonFilePath(String path, String paramName) { requireNonNull(path, paramName); checkArgument(isValidJsonFilePath(path), "%s: %s (expected: %s)", paramName, path, JSON_FILE_PATH_PATTERN); return path; } private Util(); static String validateFileName(String name, String paramName); static boolean isValidFileName(String name); static String validateFilePath(String path, String paramName); static boolean isValidFilePath(String path); static String validateJsonFilePath(String path, String paramName); static boolean isValidJsonFilePath(String path); static String validateJsonPath(String jsonPath, String paramName); static boolean isValidJsonPath(String jsonPath); static String validateDirPath(String path, String paramName); static boolean isValidDirPath(String path); static boolean isValidDirPath(String path, boolean mustEndWithSlash); static String validatePathPattern(String pathPattern, String paramName); static boolean isValidPathPattern(String pathPattern); static String validateProjectName(String projectName, String paramName); static boolean isValidProjectName(String projectName); static String validateRepositoryName(String repoName, String paramName); static boolean isValidRepositoryName(String repoName); static String validateEmailAddress(String emailAddr, String paramName); static boolean isValidEmailAddress(String emailAddr); static String toEmailAddress(String emailAddr, String paramName); static String emailToUsername(String emailAddr, String paramName); static List<String> stringToLines(String str); static String simpleTypeName(Object obj); static String simpleTypeName(Class<?> clazz); static String simpleTypeName(Class<?> clazz, boolean decapitalize); @SuppressWarnings("unchecked") static T unsafeCast(Object o); static Iterable<T> requireNonNullElements(Iterable<T> values, String name); static void deleteFileTree(File directory); } | @Test void testValidateJsonFilePath() { assertJsonFilePathValidationSuccess("/foo.json"); assertJsonFilePathValidationSuccess("/foo/bar.json"); assertJsonFilePathValidationSuccess("/foo.bar/baz.json"); assertJsonFilePathValidationSuccess("/foo.JSON"); assertJsonFilePathValidationSuccess("/foo.Json"); assertJsonFilePathValidationSuccess("/foo.jsoN"); assertJsonFilePathValidationFailure("/foo.txt"); assertJsonFilePathValidationFailure("/foo/bar.txt"); assertJsonFilePathValidationFailure("/foo.bar/baz.json.txt"); assertJsonFilePathValidationFailure("/foo-bar/baz-json"); assertJsonFilePathValidationFailure("/"); assertJsonFilePathValidationFailure("/foo/"); assertJsonFilePathValidationFailure("/."); assertJsonFilePathValidationFailure("/.."); assertJsonFilePathValidationFailure("/.json"); assertJsonFilePathValidationFailure("/json."); assertJsonFilePathValidationFailure("/.json."); assertJsonFilePathValidationFailure("/\t"); assertJsonFilePathValidationFailure("/80:20"); assertJsonFilePathValidationFailure("/foo*.json"); assertJsonFilePathValidationFailure("/bar?.json"); assertJsonFilePathValidationFailure("/baz|.json"); assertJsonFilePathValidationFailure("/\uAC00\uB098\uB2E4.json"); } |
Util { public static String validateDirPath(String path, String paramName) { requireNonNull(path, paramName); checkArgument(isValidDirPath(path), "%s: %s (expected: %s)", paramName, path, DIR_PATH_PATTERN); return path; } private Util(); static String validateFileName(String name, String paramName); static boolean isValidFileName(String name); static String validateFilePath(String path, String paramName); static boolean isValidFilePath(String path); static String validateJsonFilePath(String path, String paramName); static boolean isValidJsonFilePath(String path); static String validateJsonPath(String jsonPath, String paramName); static boolean isValidJsonPath(String jsonPath); static String validateDirPath(String path, String paramName); static boolean isValidDirPath(String path); static boolean isValidDirPath(String path, boolean mustEndWithSlash); static String validatePathPattern(String pathPattern, String paramName); static boolean isValidPathPattern(String pathPattern); static String validateProjectName(String projectName, String paramName); static boolean isValidProjectName(String projectName); static String validateRepositoryName(String repoName, String paramName); static boolean isValidRepositoryName(String repoName); static String validateEmailAddress(String emailAddr, String paramName); static boolean isValidEmailAddress(String emailAddr); static String toEmailAddress(String emailAddr, String paramName); static String emailToUsername(String emailAddr, String paramName); static List<String> stringToLines(String str); static String simpleTypeName(Object obj); static String simpleTypeName(Class<?> clazz); static String simpleTypeName(Class<?> clazz, boolean decapitalize); @SuppressWarnings("unchecked") static T unsafeCast(Object o); static Iterable<T> requireNonNullElements(Iterable<T> values, String name); static void deleteFileTree(File directory); } | @Test void testValidateDirPath() { assertDirPathValidationSuccess("/"); assertDirPathValidationSuccess("/foo"); assertDirPathValidationSuccess("/foo/"); assertDirPathValidationSuccess("/foo/bar"); assertDirPathValidationSuccess("/foo/bar/"); assertDirPathValidationSuccess("/foo.bar/"); assertDirPathValidationSuccess("/foo-bar/"); assertDirPathValidationFailure("foo"); assertDirPathValidationFailure(" assertDirPathValidationFailure("/foo assertDirPathValidationFailure("/./"); assertDirPathValidationFailure("/../"); assertDirPathValidationFailure("/.foo/"); assertDirPathValidationFailure("/foo./"); assertDirPathValidationFailure("/.foo./"); assertDirPathValidationFailure("/\t/"); assertDirPathValidationFailure("/80:20/"); assertDirPathValidationFailure("/foo*/"); assertDirPathValidationFailure("/bar?/"); assertDirPathValidationFailure("/baz|/"); assertDirPathValidationFailure("/\uAC00\uB098\uB2E4/"); } |
WatchTimeout { public static long availableTimeout(long expectedTimeoutMillis) { return availableTimeout(expectedTimeoutMillis, 0); } private WatchTimeout(); static long availableTimeout(long expectedTimeoutMillis); static long availableTimeout(long expectedTimeoutMillis, long currentTimeoutMillis); static final long MAX_MILLIS; } | @Test void testMakeReasonable() { assertThat(availableTimeout(1_000, 0)).isEqualTo(1_000); assertThat(availableTimeout(1_000, 1_000)).isEqualTo(1_000); assertThat(availableTimeout(MAX_MILLIS, 1_000)).isEqualTo(MAX_MILLIS - 1_000); assertThat(availableTimeout(MAX_MILLIS + 1_000, 0)).isEqualTo(MAX_MILLIS); assertThat(availableTimeout(MAX_MILLIS - 1_000, 500)).isEqualTo(MAX_MILLIS - 1000); assertThatThrownBy(() -> availableTimeout(0, 1_000)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> availableTimeout(-1, 1_000)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> availableTimeout(1_000, -1)) .isInstanceOf(IllegalArgumentException.class); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> normalizeRevision( String projectName, String repositoryName, Revision revision) { return executeWithRetries( new Supplier<CompletableFuture<Revision>>() { @Override public CompletableFuture<Revision> get() { return delegate.normalizeRevision(projectName, repositoryName, revision); } @Override public String toString() { return "normalizeRevision(" + projectName + ", " + repositoryName + ", " + revision + ')'; } }, (res, cause) -> { if (cause != null) { return handleRevisionNotFound(projectName, repositoryName, revision, cause); } if (revision.isRelative()) { final Revision headRevision = res.forward(-(revision.major() + 1)); return !updateLatestKnownRevision(projectName, repositoryName, headRevision); } updateLatestKnownRevision(projectName, repositoryName, revision); return false; }); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void normalizeRevision() { final Revision latestRevision = new Revision(2); for (int i = 1; i <= latestRevision.major(); i++) { final Revision revision = new Revision(i); when(delegate.normalizeRevision(any(), any(), any())).thenReturn(completedFuture(revision)); assertThat(dogma.normalizeRevision("foo", "bar", Revision.HEAD).join()).isEqualTo(revision); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.HEAD); verifyNoMoreInteractions(delegate); reset(delegate); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(revision); } when(delegate.normalizeRevision(any(), any(), any())).thenReturn( exceptionallyCompletedFuture(new RevisionNotFoundException()), completedFuture(latestRevision.backward(1)), completedFuture(latestRevision)); assertThat(dogma.normalizeRevision("foo", "bar", Revision.HEAD).join()).isEqualTo(latestRevision); verify(delegate, times(3)).normalizeRevision("foo", "bar", Revision.HEAD); verifyNoMoreInteractions(delegate); reset(delegate); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(latestRevision); final Revision newLatestRevision = latestRevision.forward(1); when(delegate.normalizeRevision(any(), any(), any())).thenReturn(completedFuture(newLatestRevision)); assertThat(dogma.normalizeRevision("foo", "bar", newLatestRevision).join()) .isEqualTo(newLatestRevision); verify(delegate, times(1)).normalizeRevision("foo", "bar", newLatestRevision); verifyNoMoreInteractions(delegate); reset(delegate); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(newLatestRevision); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(completedFuture(Revision.INIT)); assertThat(dogma.normalizeRevision("foo", "bar", Revision.HEAD).join()).isEqualTo(Revision.INIT); verify(delegate, times(4)).normalizeRevision("foo", "bar", Revision.HEAD); verifyNoMoreInteractions(delegate); reset(delegate); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(exceptionallyCompletedFuture(new RevisionNotFoundException())); assertThatThrownBy(() -> dogma.normalizeRevision("foo", "bar", Revision.HEAD).join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(RevisionNotFoundException.class); verify(delegate, times(4)).normalizeRevision("foo", "bar", Revision.HEAD); verifyNoMoreInteractions(delegate); }
@Test void retryOnlyOnRevisionNotFoundException() { when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(exceptionallyCompletedFuture(new ProjectNotFoundException())); assertThatThrownBy(() -> dogma.normalizeRevision("foo", "bar", Revision.HEAD).join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(ProjectNotFoundException.class); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.HEAD); verifyNoMoreInteractions(delegate); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { private <T> CompletableFuture<T> normalizeRevisionAndExecuteWithRetries( String projectName, String repositoryName, Revision revision, Function<Revision, CompletableFuture<T>> taskRunner) { return normalizeRevision(projectName, repositoryName, revision) .thenCompose(normRev -> executeWithRetries( new Supplier<CompletableFuture<T>>() { @Override public CompletableFuture<T> get() { return taskRunner.apply(normRev); } @Override public String toString() { return taskRunner + " with " + normRev; } }, (res, cause) -> cause != null && handleRevisionNotFound(projectName, repositoryName, normRev, cause))); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void normalizeRevisionAndExecuteWithRetries() throws Exception { final Revision latestRevision = new Revision(3); when(delegate.normalizeRevision(any(), any(), any())).thenReturn(completedFuture(latestRevision)); when(delegate.getFile(any(), any(), any(), any(Query.class))).thenReturn( exceptionallyCompletedFuture(new RevisionNotFoundException()), exceptionallyCompletedFuture(new RevisionNotFoundException()), completedFuture(Entry.ofJson(latestRevision, "/foo.json", "{ \"a\": \"b\" }"))); assertThat(dogma.getFile("foo", "bar", Revision.HEAD, Query.ofJson("/foo.json")).join()) .isEqualTo(Entry.ofJson(latestRevision, "/foo.json", "{ \"a\": \"b\" }")); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.HEAD); verify(delegate, times(3)).getFile("foo", "bar", latestRevision, Query.ofJson("/foo.json")); verifyNoMoreInteractions(delegate); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName) { return executeWithRetries( new Supplier<CompletableFuture<Map<String, RepositoryInfo>>>() { @Override public CompletableFuture<Map<String, RepositoryInfo>> get() { return delegate.listRepositories(projectName); } @Override public String toString() { return "listRepositories(" + projectName + ')'; } }, (res, cause) -> { if (res != null) { for (RepositoryInfo info : res.values()) { if (!updateLatestKnownRevision(projectName, info.name(), info.headRevision())) { return true; } } } return false; }); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void listRepositories() { final Revision latestRevision = new Revision(2); for (int i = 1; i <= latestRevision.major(); i++) { final Revision revision = new Revision(i); when(delegate.listRepositories(any())).thenReturn(completedFuture( ImmutableMap.of("bar", new RepositoryInfo("bar", revision)))); assertThat(dogma.listRepositories("foo").join()).isEqualTo( ImmutableMap.of("bar", new RepositoryInfo("bar", revision))); verify(delegate, times(1)).listRepositories("foo"); verifyNoMoreInteractions(delegate); reset(delegate); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(revision); } when(delegate.listRepositories(any())).thenReturn( completedFuture(ImmutableMap.of( "bar", new RepositoryInfo("bar", latestRevision.backward(1)))), completedFuture(ImmutableMap.of( "bar", new RepositoryInfo("bar", latestRevision)))); assertThat(dogma.listRepositories("foo").join()) .isEqualTo(ImmutableMap.of("bar", new RepositoryInfo("bar", latestRevision))); verify(delegate, times(2)).listRepositories("foo"); verifyNoMoreInteractions(delegate); reset(delegate); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(latestRevision); when(delegate.listRepositories(any())).thenReturn(completedFuture( ImmutableMap.of("bar", new RepositoryInfo("bar", Revision.INIT)))); assertThat(dogma.listRepositories("foo").join()).isEqualTo( ImmutableMap.of("bar", new RepositoryInfo("bar", Revision.INIT))); verify(delegate, times(4)).listRepositories("foo"); verifyNoMoreInteractions(delegate); } |
Entry implements ContentHolder<T> { public static Entry<String> ofText(Revision revision, String path, String content) { return new Entry<>(revision, path, EntryType.TEXT, content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void ofText() throws Exception { final Entry<String> e = Entry.ofText(new Revision(1), "/a.txt", "foo"); assertThat(e.revision()).isEqualTo(new Revision(1)); assertThat(e.hasContent()).isTrue(); e.ifHasContent(content -> assertThat(content).isEqualTo("foo")); assertThat(e.content()).isEqualTo("foo"); assertThat(e.contentAsText()).isEqualTo("foo"); assertThat(e.contentAsPrettyText()).isEqualTo("foo"); assertThatThrownBy(e::contentAsJson).isInstanceOf(JsonParseException.class); assertThatThrownBy(() -> e.contentAsJson(JsonNode.class)).isInstanceOf(JsonParseException.class); assertThat(Entry.ofText(new Revision(1), "/a.txt", "null").contentAsJson()) .isEqualTo(Jackson.nullNode); assertThat(Entry.ofText(new Revision(1), "/a.txt", "null").contentAsJson(JsonNode.class)) .isEqualTo(Jackson.nullNode); final Entry<String> e2 = Entry.ofText(new Revision(1), "/a.txt", "foo"); assertThat(e).isEqualTo(e2); assertThat(e.hashCode()).isEqualTo(e2.hashCode()); assertThat(e).isNotEqualTo(Entry.ofText(new Revision(2), "/a.txt", "foo")); assertThat(e).isNotEqualTo(Entry.ofText(new Revision(1), "/b.txt", "foo")); assertThat(e).isNotEqualTo(Entry.ofText(new Revision(1), "/a.txt", "bar")); final Entry<JsonNode> e3 = Entry.ofJson(new Revision(1), "/a.json", "{ \"foo\": \"bar\" }"); assertThat(e).isNotEqualTo(e3); assertThat(e.hashCode()).isNotEqualTo(e3.hashCode()); final Entry<Void> e4 = Entry.ofDirectory(new Revision(1), "/foo"); assertThat(e).isNotEqualTo(e4); assertThat(e.hashCode()).isNotEqualTo(e4.hashCode()); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<PushResult> push( String projectName, String repositoryName, Revision baseRevision, String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes) { return executeWithRetries( new Supplier<CompletableFuture<PushResult>>() { @Override public CompletableFuture<PushResult> get() { return delegate.push(projectName, repositoryName, baseRevision, summary, detail, markup, changes); } @Override public String toString() { return "push(" + projectName + ", " + repositoryName + ", " + baseRevision + ", " + summary + ", ...)"; } }, pushRetryPredicate(projectName, repositoryName, baseRevision)); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void push() { final PushResult pushResult = new PushResult(new Revision(3), 42L); when(delegate.push(any(), any(), any(), any(), any(), any(), any(Iterable.class))) .thenReturn(completedFuture(pushResult)); assertThat(dogma.push("foo", "bar", Revision.HEAD, "summary", "detail", Markup.MARKDOWN, ImmutableList.of(Change.ofTextUpsert("/a.txt", "a"))).join()) .isEqualTo(pushResult); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(pushResult.revision()); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> watchRepository( String projectName, String repositoryName, Revision lastKnownRevision, String pathPattern, long timeoutMillis) { return normalizeRevisionAndExecuteWithRetries( projectName, repositoryName, lastKnownRevision, new Function<Revision, CompletableFuture<Revision>>() { @Override public CompletableFuture<Revision> apply(Revision normLastKnownRevision) { return delegate.watchRepository(projectName, repositoryName, normLastKnownRevision, pathPattern, timeoutMillis) .thenApply(newLastKnownRevision -> { if (newLastKnownRevision != null) { updateLatestKnownRevision(projectName, repositoryName, newLastKnownRevision); } return newLastKnownRevision; }); } @Override public String toString() { return "watchRepository(" + projectName + ", " + repositoryName + ", " + lastKnownRevision + ", " + pathPattern + ", " + timeoutMillis + ')'; } }); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void watchRepository() { final Revision latestRevision = new Revision(3); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(completedFuture(Revision.INIT)); when(delegate.watchRepository(any(), any(), any(), any(), anyLong())) .thenReturn(completedFuture(latestRevision)); assertThat(dogma.watchRepository("foo", "bar", Revision.INIT, "/**", 10000L).join()) .isEqualTo(latestRevision); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(latestRevision); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.INIT); verify(delegate, times(1)).watchRepository("foo", "bar", Revision.INIT, "/**", 10000L); verifyNoMoreInteractions(delegate); reset(delegate); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(completedFuture(latestRevision)); when(delegate.getFile(any(), any(), any(), any(Query.class))) .thenReturn(exceptionallyCompletedFuture(new RevisionNotFoundException()), completedFuture(Entry.ofText(latestRevision, "/a.txt", "a"))); assertThat(dogma.getFile("foo", "bar", Revision.HEAD, Query.ofText("/a.txt")).join()) .isEqualTo(Entry.ofText(latestRevision, "/a.txt", "a")); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.HEAD); verify(delegate, times(2)).getFile("foo", "bar", latestRevision, Query.ofText("/a.txt")); verifyNoMoreInteractions(delegate); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<Entry<T>> watchFile( String projectName, String repositoryName, Revision lastKnownRevision, Query<T> query, long timeoutMillis) { return normalizeRevisionAndExecuteWithRetries( projectName, repositoryName, lastKnownRevision, new Function<Revision, CompletableFuture<Entry<T>>>() { @Override public CompletableFuture<Entry<T>> apply(Revision normLastKnownRevision) { return delegate.watchFile(projectName, repositoryName, normLastKnownRevision, query, timeoutMillis) .thenApply(entry -> { if (entry != null) { updateLatestKnownRevision(projectName, repositoryName, entry.revision()); } return entry; }); } @Override public String toString() { return "watchFile(" + projectName + ", " + repositoryName + ", " + lastKnownRevision + ", " + query + ", " + timeoutMillis + ')'; } }); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void watchFile() { final Revision latestRevision = new Revision(3); final Entry<String> latestEntry = Entry.ofText(latestRevision, "/a.txt", "a"); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(completedFuture(Revision.INIT)); when(delegate.watchFile(any(), any(), any(), (Query<String>) any(), anyLong())) .thenReturn(completedFuture(latestEntry)); assertThat(dogma.watchFile("foo", "bar", Revision.INIT, Query.ofText("/a.txt"), 10000L).join()) .isEqualTo(latestEntry); assertThat(dogma.latestKnownRevision("foo", "bar")).isEqualTo(latestRevision); verify(delegate, times(1)).normalizeRevision("foo", "bar", Revision.INIT); verify(delegate, times(1)).watchFile("foo", "bar", Revision.INIT, Query.ofText("/a.txt"), 10000L); verifyNoMoreInteractions(delegate); } |
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<Entry<T>> getFile( String projectName, String repositoryName, Revision revision, Query<T> query) { return normalizeRevisionAndExecuteWithRetries( projectName, repositoryName, revision, new Function<Revision, CompletableFuture<Entry<T>>>() { @Override public CompletableFuture<Entry<T>> apply(Revision normRev) { return delegate.getFile(projectName, repositoryName, normRev, query); } @Override public String toString() { return "getFile(" + projectName + ", " + repositoryName + ", " + revision + ", " + query + ')'; } }); } ReplicationLagTolerantCentralDogma(ScheduledExecutorService executor, CentralDogma delegate,
int maxRetries, long retryIntervalMillis,
Supplier<?> currentReplicaHintSupplier); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(
String projectName, String repositoryName, Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(
String projectName, String repositoryName, Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(
String projectName, String repositoryName, Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(
String projectName, String repositoryName, Revision revision,
MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(
String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<Change<T>> getDiff(
String projectName, String repositoryName, Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(
String projectName, String repositoryName, Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(
String projectName, String repositoryName, Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(
String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(
String projectName, String repositoryName, Revision lastKnownRevision,
String pathPattern, long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(
String projectName, String repositoryName, Revision lastKnownRevision,
Query<T> query, long timeoutMillis); } | @Test void getFile() { final Revision latestRevision = new Revision(3); final Entry<String> latestEntry = Entry.ofText(latestRevision, "/a.txt", "a"); when(delegate.normalizeRevision(any(), any(), any())) .thenReturn(completedFuture(latestRevision)); when(delegate.getFile(any(), any(), any(), any(Query.class))) .thenAnswer(invocation -> CompletableFuture.supplyAsync(() -> { throw new RevisionNotFoundException(); })) .thenReturn(completedFuture(latestEntry)); assertThat(dogma.getFile("foo", "bar", Revision.HEAD, "/a.txt").join()) .isEqualTo(latestEntry); verify(delegate).normalizeRevision("foo", "bar", Revision.HEAD); verify(delegate, times(2)).getFile("foo", "bar", latestRevision, Query.ofText("/a.txt")); verifyNoMoreInteractions(delegate); } |
ArmeriaCentralDogma extends AbstractCentralDogma { @VisibleForTesting static String encodePathPattern(String pathPattern) { int spacePos = pathPattern.indexOf(' '); if (spacePos < 0) { return pathPattern; } final StringBuilder buf = new StringBuilder(IntMath.saturatedMultiply(pathPattern.length(), 2)); for (int pos = 0;;) { buf.append(pathPattern, pos, spacePos); buf.append("%20"); pos = spacePos + 1; spacePos = pathPattern.indexOf(' ', pos); if (spacePos < 0) { buf.append(pathPattern, pos, pathPattern.length()); break; } } return buf.toString(); } ArmeriaCentralDogma(ScheduledExecutorService executor, WebClient client, String accessToken); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName, Revision revision,
Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName, String repositoryName,
Revision from, Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName, Revision from,
Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName, Revision from,
Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision, String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void testEncodePathPattern() { assertThat(encodePathPattern("/")).isEqualTo("/"); assertThat(encodePathPattern(" ")).isEqualTo("%20"); assertThat(encodePathPattern(" ")).isEqualTo("%20%20"); assertThat(encodePathPattern("a b")).isEqualTo("a%20b"); assertThat(encodePathPattern(" a ")).isEqualTo("%20a%20"); final String pathPatternThatDoesNotNeedEscaping = "*.jar"; assertThat(encodePathPattern(pathPatternThatDoesNotNeedEscaping)) .isSameAs(pathPatternThatDoesNotNeedEscaping); } |
JsonEndpointListDecoder implements EndpointListDecoder<JsonNode> { @Override public List<Endpoint> decode(JsonNode node) { final List<String> endpoints; try { endpoints = objectMapper.readValue(node.traverse(), new TypeReference<List<String>>() {}); } catch (IOException e) { throw new IllegalArgumentException("invalid format: " + node); } return convertToEndpointList(endpoints); } @Override List<Endpoint> decode(JsonNode node); } | @Test void decode() throws Exception { final EndpointListDecoder<JsonNode> decoder = EndpointListDecoder.JSON; final List<Endpoint> decoded = decoder.decode( objectMapper.readTree(objectMapper.writeValueAsString(HOST_AND_PORT_LIST))); assertThat(decoded).hasSize(4); assertThat(decoded).isEqualTo(ENDPOINT_LIST); } |
TextEndpointListDecoder implements EndpointListDecoder<String> { @Override public List<Endpoint> decode(String object) { return convertToEndpointList(NEWLINE_SPLITTER.splitToList(object)); } @Override List<Endpoint> decode(String object); } | @Test void decode() { final EndpointListDecoder<String> decoder = EndpointListDecoder.TEXT; final List<Endpoint> decoded = decoder.decode(String.join("\n", HOST_AND_PORT_LIST)); assertThat(decoded).hasSize(4); assertThat(decoded).isEqualTo(ENDPOINT_LIST); } |
ArmeriaCentralDogmaBuilder extends AbstractArmeriaCentralDogmaBuilder<ArmeriaCentralDogmaBuilder> { public CentralDogma build() throws UnknownHostException { final EndpointGroup endpointGroup = endpointGroup(); final String scheme = "none+" + (isUseTls() ? "https" : "http"); final ClientBuilder builder = newClientBuilder(scheme, endpointGroup, cb -> cb.decorator(DecodingClient.newDecorator()), "/"); final EventLoopGroup executor = clientFactory().eventLoopGroup(); final int maxRetriesOnReplicationLag = maxNumRetriesOnReplicationLag(); final CentralDogma dogma = new ArmeriaCentralDogma(executor, builder.build(WebClient.class), accessToken()); if (maxRetriesOnReplicationLag <= 0) { return dogma; } else { return new ReplicationLagTolerantCentralDogma( executor, dogma, maxRetriesOnReplicationLag, retryIntervalOnReplicationLagMillis(), () -> { final ClientRequestContext ctx = ClientRequestContext.currentOrNull(); return ctx != null ? ctx.remoteAddress() : null; }); } } CentralDogma build(); } | @Test void newClientBuilderCustomizationOrder() { final ClientFactory cf1 = mock(ClientFactory.class); final ClientFactory cf2 = mock(ClientFactory.class); final ClientFactory cf3 = mock(ClientFactory.class); final ArmeriaCentralDogmaBuilder b = new ArmeriaCentralDogmaBuilder(); final StringBuilder buf = new StringBuilder(); b.clientFactory(cf1); b.clientConfigurator(cb -> { buf.append('2'); cb.factory(cf2); }); final ClientBuilder cb = b.newClientBuilder("none+http", Endpoint.of("127.0.0.1"), cb2 -> { cb2.factory(cf3); buf.append('1'); }, "/"); assertThat(buf.toString()).isEqualTo("12"); cb.build(HttpClient.class); verify(cf1, times(1)).newClient(any()); verify(cf2, never()).newClient(any()); verify(cf3, never()).newClient(any()); } |
LegacyCentralDogmaTimeoutScheduler extends SimpleDecoratingRpcClient { @Override public RpcResponse execute(ClientRequestContext ctx, RpcRequest req) throws Exception { final long responseTimeoutMillis = ctx.responseTimeoutMillis(); if (responseTimeoutMillis > 0) { final String method = req.method(); if ("watchFile".equals(method) || "watchRepository".equals(method)) { final List<Object> params = req.params(); final long timeout = (Long) params.get(params.size() - 1); if (timeout > 0) { ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, WatchTimeout.availableTimeout(timeout, responseTimeoutMillis)); } } } return unwrap().execute(ctx, req); } LegacyCentralDogmaTimeoutScheduler(RpcClient delegate); @Override RpcResponse execute(ClientRequestContext ctx, RpcRequest req); } | @Test void execute() throws Exception { check("listProjects", 1000L, 1L, 1L); } |
Entry implements ContentHolder<T> { public static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content) { return new Entry<>(revision, path, EntryType.JSON, content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void ofJson() throws Exception { final Entry<JsonNode> e = Entry.ofJson(new Revision(1), "/a.json", "{ \"foo\": \"bar\" }"); assertThat(e.revision()).isEqualTo(new Revision(1)); assertThat(e.hasContent()).isTrue(); e.ifHasContent(content -> assertThatJson(content).isEqualTo("{ \"foo\": \"bar\" }")); assertThatJson(e.content()).isEqualTo("{ \"foo\": \"bar\" }"); assertThat(e.contentAsText()).isEqualTo("{\"foo\":\"bar\"}"); assertThat(e.contentAsPrettyText()).isEqualTo("{\n \"foo\": \"bar\"\n}"); assertThat(e.content()).isSameAs(e.contentAsJson()); assertThat(e.content()).isEqualTo(e.contentAsJson(JsonNode.class)); final Entry<JsonNode> e2 = Entry.ofJson(new Revision(1), "/a.json", "{ \"foo\": \"bar\" }"); assertThat(e).isEqualTo(e2); assertThat(e.hashCode()).isEqualTo(e2.hashCode()); assertThat(e).isNotEqualTo(Entry.ofJson(new Revision(2), "/a.json", "{ \"foo\": \"bar\" }")); assertThat(e).isNotEqualTo(Entry.ofJson(new Revision(1), "/b.json", "{ \"foo\": \"bar\" }")); assertThat(e).isNotEqualTo(Entry.ofJson(new Revision(1), "/a.json", "null")); final Entry<String> e3 = Entry.ofText(new Revision(1), "/a.json", "{\"foo\":\"bar\"}"); assertThat(e).isNotEqualTo(e3); assertThat(e.hashCode()).isNotEqualTo(e3.hashCode()); final Entry<Void> e4 = Entry.ofDirectory(new Revision(1), "/foo"); assertThat(e).isNotEqualTo(e4); assertThat(e.hashCode()).isNotEqualTo(e4.hashCode()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> createProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.createProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void createProject() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(1); callback.onComplete(null); return null; }).when(iface).createProject(any(), any()); assertThat(client.createProject("project").get()).isNull(); verify(iface).createProject(eq("project"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> removeProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.removeProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void removeProject() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(1); callback.onComplete(null); return null; }).when(iface).removeProject(any(), any()); assertThat(client.removeProject("project").get()).isNull(); verify(iface).removeProject(eq("project"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> purgeProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.purgeProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void purgeProject() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(1); callback.onComplete(null); return null; }).when(iface).purgeProject(any(), any()); assertThat(client.purgeProject("project").get()).isNull(); verify(iface).purgeProject(eq("project"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> unremoveProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.unremoveProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void unremoveProject() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(1); callback.onComplete(null); return null; }).when(iface).unremoveProject(any(), any()); assertThat(client.unremoveProject("project").get()).isNull(); verify(iface).unremoveProject(eq("project"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Set<String>> listProjects() { final CompletableFuture<List<Project>> future = run(client::listProjects); return future.thenApply(list -> convertToSet(list, Project::getName)); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void listProjects() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<Project>> callback = invocation.getArgument(0); callback.onComplete(ImmutableList.of(new Project("project"))); return null; }).when(iface).listProjects(any()); assertThat(client.listProjects().get()).isEqualTo(ImmutableSet.of("project")); verify(iface).listProjects(any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Set<String>> listRemovedProjects() { return run(client::listRemovedProjects); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void listRemovedProjects() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Set<String>> callback = invocation.getArgument(0); callback.onComplete(ImmutableSet.of("project")); return null; }).when(iface).listRemovedProjects(any()); assertThat(client.listRemovedProjects().get()).isEqualTo(ImmutableSet.of("project")); verify(iface).listRemovedProjects(any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> createRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.createRepository(projectName, repositoryName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void createRepository() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(2); callback.onComplete(null); return null; }).when(iface).createRepository(anyString(), anyString(), any()); assertThat(client.createRepository("project", "repo").get()).isNull(); verify(iface).createRepository(eq("project"), eq("repo"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> removeRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.removeRepository(projectName, repositoryName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void removeRepository() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(2); callback.onComplete(null); return null; }).when(iface).removeRepository(anyString(), anyString(), any()); assertThat(client.removeRepository("project", "repo").get()).isNull(); verify(iface).removeRepository(eq("project"), eq("repo"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> purgeRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.purgeRepository(projectName, repositoryName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void purgeRepository() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(2); callback.onComplete(null); return null; }).when(iface).purgeRepository(anyString(), anyString(), any()); assertThat(client.purgeRepository("project", "repo").get()).isNull(); verify(iface).purgeRepository(eq("project"), eq("repo"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.unremoveRepository(projectName, repositoryName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void unremoveRepository() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Void> callback = invocation.getArgument(2); callback.onComplete(null); return null; }).when(iface).unremoveRepository(anyString(), anyString(), any()); assertThat(client.unremoveRepository("project", "repo").get()).isNull(); verify(iface).unremoveRepository(eq("project"), eq("repo"), any()); } |
Entry implements ContentHolder<T> { public static <T> Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content) { return new Entry<>(revision, path, type, content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void of() { assertThatThrownBy(() -> Entry.of(null, "/1.txt", EntryType.TEXT, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), null, EntryType.TEXT, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", null, "1")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", EntryType.TEXT, null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> Entry.of(new Revision(1), "/1.txt", EntryType.TEXT, new Object())) .isInstanceOf(ClassCastException.class); Entry.of(new Revision(1), "/a", EntryType.DIRECTORY, null); assertThatThrownBy(() -> Entry.of(new Revision(1), "/a", EntryType.DIRECTORY, "foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expected: null"); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName) { final CompletableFuture<List<Repository>> future = run(callback -> { validateProjectName(projectName); client.listRepositories(projectName, callback); }); return future.thenApply(list -> convertToMap( list, Function.identity(), Repository::getName, r -> new RepositoryInfo( r.getName(), RevisionConverter.TO_MODEL.convert(r.getHead().getRevision())))); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void listRepositories() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<Repository>> callback = invocation.getArgument(1); final Repository repository = new Repository("repo").setHead( new TCommit(new TRevision(42), new TAuthor("hitchhiker", "[email protected]"), "1978-03-08T00:00:00Z", "The primary phrase", new Comment(""), null)); callback.onComplete(ImmutableList.of(repository)); return null; }).when(iface).listRepositories(any(), any()); assertThat(client.listRepositories("project").get()).isEqualTo(ImmutableMap.of( "repo", new RepositoryInfo("repo", new Revision(42)))); verify(iface).listRepositories(eq("project"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Set<String>> listRemovedRepositories(String projectName) { return run(callback -> { validateProjectName(projectName); client.listRemovedRepositories(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void listRemovedRepositories() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<Set<String>> callback = invocation.getArgument(1); callback.onComplete(ImmutableSet.of("repo")); return null; }).when(iface).listRemovedRepositories(any(), any()); assertThat(client.listRemovedRepositories("project").get()).isEqualTo(ImmutableSet.of("repo")); verify(iface).listRemovedRepositories(anyString(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName, Revision revision) { final CompletableFuture<com.linecorp.centraldogma.internal.thrift.Revision> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(revision, "revision"); client.normalizeRevision(projectName, repositoryName, RevisionConverter.TO_DATA.convert(revision), callback); }); return future.thenApply(RevisionConverter.TO_MODEL::convert); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void normalizeRevision() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<TRevision> callback = invocation.getArgument(3); callback.onComplete(new TRevision(3)); return null; }).when(iface).normalizeRevision(anyString(), anyString(), any(), any()); assertThat(client.normalizeRevision("project", "repo", new Revision(1)).get()) .isEqualTo(new Revision(3)); verify(iface).normalizeRevision(eq("project"), eq("repo"), any(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName, Revision revision, String pathPattern) { final CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Entry>> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(revision, "revision"); validatePathPattern(pathPattern, "pathPattern"); client.listFiles(projectName, repositoryName, RevisionConverter.TO_DATA.convert(revision), pathPattern, callback); }); return future.thenApply(list -> list.stream().collect(toImmutableMap( com.linecorp.centraldogma.internal.thrift.Entry::getPath, e -> EntryConverter.convertEntryType(e.getType())))); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void listFiles() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<TEntry>> callback = invocation.getArgument(4); final TEntry entry = new TEntry("/a.txt", TEntryType.TEXT); entry.setContent("hello"); callback.onComplete(ImmutableList.of(entry)); return null; }).when(iface).listFiles(anyString(), anyString(), any(), anyString(), any()); assertThat(client.listFiles("project", "repo", new Revision(1), "/a.txt").get()) .isEqualTo(ImmutableMap.of("/a.txt", EntryType.TEXT)); verify(iface).listFiles(anyString(), anyString(), any(), anyString(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName, Revision revision, String pathPattern) { return maybeNormalizeRevision(projectName, repositoryName, revision).thenCompose(normRev -> { final CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Entry>> future = run(callback -> { validatePathPattern(pathPattern, "pathPattern"); client.getFiles(projectName, repositoryName, RevisionConverter.TO_DATA.convert(normRev), pathPattern, callback); }); return future.thenApply(list -> convertToMap(list, e -> EntryConverter.convert(normRev, e), Entry::path, Function.identity())); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void getFiles() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<TEntry>> callback = invocation.getArgument(4); final TEntry entry = new TEntry("/b.txt", TEntryType.TEXT); entry.setContent("world"); callback.onComplete(ImmutableList.of(entry)); return null; }).when(iface).getFiles(anyString(), anyString(), any(), anyString(), any()); assertThat(client.getFiles("project", "repo", new Revision(1), "path").get()) .isEqualTo(ImmutableMap.of("/b.txt", Entry.ofText(new Revision(1), "/b.txt", "world"))); verify(iface).getFiles(anyString(), anyString(), any(), anyString(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<List<Commit>> getHistory(String projectName, String repositoryName, Revision from, Revision to, String pathPattern) { final CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Commit>> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(from, "from"); requireNonNull(to, "to"); validatePathPattern(pathPattern, "pathPattern"); client.getHistory(projectName, repositoryName, RevisionConverter.TO_DATA.convert(from), RevisionConverter.TO_DATA.convert(to), pathPattern, callback); }); return future.thenApply(list -> convertToList(list, CommitConverter.TO_MODEL::convert)); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void getHistory() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<TCommit>> callback = invocation.getArgument(5); callback.onComplete(ImmutableList.of(new TCommit( new TRevision(1), new TAuthor("name", "[email protected]"), TIMESTAMP, "summary", new Comment("detail").setMarkup(TMarkup.PLAINTEXT), ImmutableList.of(new TChange("/a.txt", ChangeType.UPSERT_TEXT).setContent("content"))))); return null; }).when(iface).getHistory(any(), any(), any(), any(), any(), any()); assertThat(client.getHistory("project", "repo", new Revision(1), new Revision(3), "path").get()) .isEqualTo(ImmutableList.of(new Commit(new Revision(1), new Author("name", "[email protected]"), Instant.parse(TIMESTAMP).toEpochMilli(), "summary", "detail", Markup.PLAINTEXT))); verify(iface).getHistory(eq("project"), eq("repo"), any(), any(), eq("path"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName, Revision from, Revision to, String pathPattern) { final CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Change>> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(from, "from"); requireNonNull(to, "to"); validatePathPattern(pathPattern, "pathPattern"); client.getDiffs(projectName, repositoryName, RevisionConverter.TO_DATA.convert(from), RevisionConverter.TO_DATA.convert(to), pathPattern, callback); }); return future.thenApply(list -> convertToList(list, ChangeConverter.TO_MODEL::convert)); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void getDiffs() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<TChange>> callback = invocation.getArgument(5); final TChange change = new TChange("/a.txt", ChangeType.UPSERT_TEXT); change.setContent("content"); callback.onComplete(ImmutableList.of(change)); return null; }).when(iface).getDiffs(any(), any(), any(), any(), any(), any()); assertThat(client.getDiffs("project", "repo", new Revision(1), new Revision(3), "path").get()) .isEqualTo(ImmutableList.of(Change.ofTextUpsert("/a.txt", "content"))); verify(iface).getDiffs(eq("project"), eq("repo"), any(), any(), eq("path"), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName, Revision baseRevision, Iterable<? extends Change<?>> changes) { final CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Change>> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(baseRevision, "baseRevision"); requireNonNull(changes, "changes"); client.getPreviewDiffs( projectName, repositoryName, RevisionConverter.TO_DATA.convert(baseRevision), convertToList(changes, ChangeConverter.TO_DATA::convert), callback); }); return future.thenApply(LegacyCentralDogma::convertToChangesModel); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void getPreviewDiffs() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<List<TChange>> callback = invocation.getArgument(4); final TChange change = new TChange("/a.txt", ChangeType.UPSERT_TEXT); change.setContent("content"); callback.onComplete(ImmutableList.of(change)); return null; }).when(iface).getPreviewDiffs(any(), any(), any(), any(), any()); assertThat(client.getPreviewDiffs("project", "repo", new Revision(1), ImmutableList.of(Change.ofTextUpsert("/a.txt", "content"))).get()) .isEqualTo(ImmutableList.of(Change.ofTextUpsert("/a.txt", "content"))); verify(iface).getPreviewDiffs(eq("project"), eq("repo"), any(), any(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision, String summary, String detail, Markup markup, Iterable<? extends Change<?>> changes) { return push(projectName, repositoryName, baseRevision, Author.UNKNOWN, summary, detail, markup, changes); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void push() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<TCommit> callback = invocation.getArgument(7); callback.onComplete(new TCommit( new TRevision(1), new TAuthor("name", "[email protected]"), TIMESTAMP, "summary", new Comment("detail"), ImmutableList.of())); return null; }).when(iface).push(anyString(), anyString(), any(), any(), any(), any(), any(), any()); assertThat(client.push("project", "repo", new Revision(1), new Author("name", "[email protected]"), "summary", "detail", Markup.PLAINTEXT, ImmutableList.of(Change.ofTextUpsert("/a.txt", "hello")) ).get()).isEqualTo(new PushResult(new Revision(1), Instant.parse(TIMESTAMP).toEpochMilli())); verify(iface).push(eq("project"), eq("repo"), any(), any(), eq("summary"), any(), any(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName, Revision revision, Query<T> query) { return maybeNormalizeRevision(projectName, repositoryName, revision).thenCompose(normRev -> { final CompletableFuture<GetFileResult> future = run(callback -> { requireNonNull(query, "query"); client.getFile(projectName, repositoryName, RevisionConverter.TO_DATA.convert(normRev), QueryConverter.TO_DATA.convert(query), callback); }); return future.thenApply(r -> { if (r == null) { return null; } return toEntry(query, normRev, query.type(), r.getContent(), r.getType()); }); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void getFile() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<GetFileResult> callback = invocation.getArgument(4); callback.onComplete(new GetFileResult(TEntryType.TEXT, "content")); return null; }).when(iface).getFile(any(), any(), any(), any(), any()); assertThat(client.getFile("project", "repo", new Revision(1), Query.ofText("/a.txt")).get()) .isEqualTo(Entry.ofText(new Revision(1), "/a.txt", "content")); verify(iface).getFile(eq("project"), eq("repo"), any(), any(), any()); }
@Test void getFile_path() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<GetFileResult> callback = invocation.getArgument(4); callback.onComplete(new GetFileResult(TEntryType.TEXT, "content")); return null; }).when(iface).getFile(any(), any(), any(), any(), any()); assertThat(client.getFile("project", "repo", new Revision(1), Query.ofText("/a.txt")).get()) .isEqualTo(Entry.ofText(new Revision(1), "/a.txt", "content")); verify(iface).getFile(eq("project"), eq("repo"), any(), any(), any()); } |
Entry implements ContentHolder<T> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Entry)) { return false; } @SuppressWarnings("unchecked") final Entry<T> that = (Entry<T>) o; return type == that.type && revision.equals(that.revision) && path.equals(that.path) && Objects.equals(content, that.content); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void testEquals() { final Entry<Void> e = Entry.ofDirectory(new Revision(1), "/foo"); assertThat(e).isNotEqualTo(null); assertThat(e).isNotEqualTo(new Object()); assertThat(e).isEqualTo(e); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName, Revision revision, MergeQuery<T> mergeQuery) { final CompletableFuture<com.linecorp.centraldogma.internal.thrift.MergedEntry> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(revision, "revision"); requireNonNull(mergeQuery, "mergeQuery"); client.mergeFiles(projectName, repositoryName, RevisionConverter.TO_DATA.convert(revision), MergeQueryConverter.TO_DATA.convert(mergeQuery), callback); }); return future.thenApply(entry -> { final EntryType entryType = EntryConverter.convertEntryType(entry.getType()); assert entryType != null; switch (entryType) { case JSON: try { @SuppressWarnings("unchecked") final MergedEntry<T> converted = (MergedEntry<T>) MergedEntry.of( RevisionConverter.TO_MODEL.convert(entry.revision), entryType, Jackson.readTree(entry.content), entry.paths); return converted; } catch (IOException e) { throw new CentralDogmaException( "failed to parse the content: " + entry.content, e); } default: throw new Error("unsupported entry type: " + entryType); } }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void mergeFiles() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<MergedEntry> callback = invocation.getArgument(4); callback.onComplete(new MergedEntry(new TRevision(1), TEntryType.JSON, "{\"foo\": \"bar\"}", ImmutableList.of("/a.json", "/b.json"))); return null; }).when(iface).mergeFiles(any(), any(), any(), any(), any()); assertThat(client.mergeFiles("project", "repo", new Revision(1), MergeQuery.ofJson(ImmutableList.of(MergeSource.ofOptional("/a.json"), MergeSource.ofRequired("/b.json")))) .get()) .isEqualTo(com.linecorp.centraldogma.common.MergedEntry.of( new Revision(1), EntryType.JSON, Jackson.readTree("{\"foo\": \"bar\"}"), ImmutableList.of("/a.json", "/b.json"))); verify(iface).mergeFiles(eq("project"), eq("repo"), any(), any(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName, Revision from, Revision to, Query<T> query) { final CompletableFuture<DiffFileResult> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(from, "from"); requireNonNull(to, "to"); requireNonNull(query, "query"); client.diffFile(projectName, repositoryName, RevisionConverter.TO_DATA.convert(from), RevisionConverter.TO_DATA.convert(to), QueryConverter.TO_DATA.convert(query), callback); }); return future.thenApply(r -> { if (r == null) { return null; } final Change<T> converted; switch (r.getType()) { case UPSERT_JSON: converted = unsafeCast(Change.ofJsonUpsert(query.path(), r.getContent())); break; case UPSERT_TEXT: converted = unsafeCast(Change.ofTextUpsert(query.path(), r.getContent())); break; case REMOVE: converted = unsafeCast(Change.ofRemoval(query.path())); break; case RENAME: converted = unsafeCast(Change.ofRename(query.path(), r.getContent())); break; case APPLY_JSON_PATCH: converted = unsafeCast(Change.ofJsonPatch(query.path(), r.getContent())); break; case APPLY_TEXT_PATCH: converted = unsafeCast(Change.ofTextPatch(query.path(), r.getContent())); break; default: throw new Error("unknown change type: " + r.getType()); } return converted; }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void diffFile() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<DiffFileResult> callback = invocation.getArgument(5); callback.onComplete(new DiffFileResult(ChangeType.UPSERT_TEXT, "some_text")); return null; }).when(iface).diffFile(any(), any(), any(), any(), any(), any()); assertThat(client.getDiff("project", "repo", new Revision(1), new Revision(3), Query.ofText("/a.txt")).get()) .isEqualTo(Change.ofTextUpsert("/a.txt", "some_text")); verify(iface).diffFile(eq("project"), eq("repo"), any(), any(), any(), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> watchRepository(String projectName, String repositoryName, Revision lastKnownRevision, String pathPattern, long timeoutMillis) { final CompletableFuture<WatchRepositoryResult> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(lastKnownRevision, "lastKnownRevision"); validatePathPattern(pathPattern, "pathPattern"); client.watchRepository(projectName, repositoryName, RevisionConverter.TO_DATA.convert(lastKnownRevision), pathPattern, timeoutMillis, callback); }); return future.thenApply(r -> { if (r == null) { return null; } return RevisionConverter.TO_MODEL.convert(r.getRevision()); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void watchRepository() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<WatchRepositoryResult> callback = invocation.getArgument(5); callback.onComplete(new WatchRepositoryResult().setRevision(new TRevision(42))); return null; }).when(iface).watchRepository(any(), any(), any(), anyString(), anyLong(), any()); assertThat(client.watchRepository("project", "repo", new Revision(1), "/a.txt", 100).get()) .isEqualTo(new Revision(42)); verify(iface).watchRepository(eq("project"), eq("repo"), any(), eq("/a.txt"), eq(100L), any()); }
@Test void watchRepositoryTimedOut() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<WatchRepositoryResult> callback = invocation.getArgument(5); callback.onComplete(new WatchRepositoryResult()); return null; }).when(iface).watchRepository(any(), any(), any(), anyString(), anyLong(), any()); assertThat(client.watchRepository("project", "repo", new Revision(1), "/a.txt", 100).get()) .isNull(); verify(iface).watchRepository(eq("project"), eq("repo"), any(), eq("/a.txt"), eq(100L), any()); } |
LegacyCentralDogma extends AbstractCentralDogma { @Override public <T> CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName, Revision lastKnownRevision, Query<T> query, long timeoutMillis) { final CompletableFuture<WatchFileResult> future = run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); requireNonNull(lastKnownRevision, "lastKnownRevision"); requireNonNull(query, "query"); client.watchFile(projectName, repositoryName, RevisionConverter.TO_DATA.convert(lastKnownRevision), QueryConverter.TO_DATA.convert(query), timeoutMillis, callback); }); return future.thenApply(r -> { if (r == null) { return null; } final Revision revision = RevisionConverter.TO_MODEL.convert(r.getRevision()); if (revision == null) { return null; } return toEntry(query, revision, query.type(), r.getContent(), r.getType()); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projectName); @Override CompletableFuture<Void> removeProject(String projectName); @Override CompletableFuture<Void> purgeProject(String projectName); @Override CompletableFuture<Void> unremoveProject(String projectName); @Override CompletableFuture<Set<String>> listProjects(); @Override CompletableFuture<Set<String>> listRemovedProjects(); @Override CompletableFuture<Void> createRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> removeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> purgeRepository(String projectName, String repositoryName); @Override CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName); @Override CompletableFuture<Map<String, RepositoryInfo>> listRepositories(String projectName); @Override CompletableFuture<Set<String>> listRemovedRepositories(String projectName); @Override CompletableFuture<Revision> normalizeRevision(String projectName, String repositoryName,
Revision revision); @Override CompletableFuture<Map<String, EntryType>> listFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName,
Revision revision, Query<T> query); @Override CompletableFuture<Map<String, Entry<?>>> getFiles(String projectName, String repositoryName,
Revision revision, String pathPattern); @Override CompletableFuture<MergedEntry<T>> mergeFiles(String projectName, String repositoryName,
Revision revision, MergeQuery<T> mergeQuery); @Override CompletableFuture<List<Commit>> getHistory(String projectName,
String repositoryName,
Revision from,
Revision to,
String pathPattern); @Override CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
Revision from, Revision to, Query<T> query); @Override CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
Revision from, Revision to, String pathPattern); @Override CompletableFuture<List<Change<?>>> getPreviewDiffs(String projectName, String repositoryName,
Revision baseRevision,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
Author author, String summary, String detail, Markup markup,
Iterable<? extends Change<?>> changes); @Override CompletableFuture<Revision> watchRepository(String projectName, String repositoryName,
Revision lastKnownRevision,
String pathPattern,
long timeoutMillis); @Override CompletableFuture<Entry<T>> watchFile(String projectName, String repositoryName,
Revision lastKnownRevision, Query<T> query,
long timeoutMillis); } | @Test void watchFile() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<WatchFileResult> callback = invocation.getArgument(5); callback.onComplete(new WatchFileResult().setRevision(new TRevision(42)) .setType(TEntryType.TEXT) .setContent("foo")); return null; }).when(iface).watchFile(any(), any(), any(), any(), anyLong(), any()); assertThat(client.watchFile("project", "repo", new Revision(1), Query.ofText("/a.txt"), 100).get()) .isEqualTo(Entry.ofText(new Revision(42), "/a.txt", "foo")); verify(iface).watchFile(eq("project"), eq("repo"), any(), any(), eq(100L), any()); }
@Test void watchFileTimedOut() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<WatchFileResult> callback = invocation.getArgument(5); callback.onComplete(new WatchFileResult()); return null; }).when(iface).watchFile(any(), any(), any(), any(), anyLong(), any()); assertThat(client.watchFile("project", "repo", new Revision(1), Query.ofText("/a.txt"), 100).get()).isNull(); verify(iface).watchFile(eq("project"), eq("repo"), any(), any(), eq(100L), any()); } |
ZooKeeperReplicationConfig implements ReplicationConfig { @JsonProperty public int serverId() { return serverId; } ZooKeeperReplicationConfig(int serverId, Map<Integer, ZooKeeperAddress> servers); @VisibleForTesting ZooKeeperReplicationConfig(
int serverId, Map<Integer, ZooKeeperAddress> servers, String secret,
Map<String, String> additionalProperties,
int timeoutMillis, int numWorkers, int maxLogCount, long minLogAgeMillis); @JsonCreator ZooKeeperReplicationConfig(@JsonProperty("serverId") @Nullable Integer serverId,
@JsonProperty(value = "servers", required = true)
@JsonDeserialize(keyAs = Integer.class, contentAs = ZooKeeperAddress.class)
Map<Integer, ZooKeeperAddress> servers,
@JsonProperty("secret") @Nullable String secret,
@JsonProperty("additionalProperties")
@JsonDeserialize(keyAs = String.class, contentAs = String.class)
@Nullable Map<String, String> additionalProperties,
@JsonProperty("timeoutMillis") @Nullable Integer timeoutMillis,
@JsonProperty("numWorkers") @Nullable Integer numWorkers,
@JsonProperty("maxLogCount") @Nullable Integer maxLogCount,
@JsonProperty("minLogAgeMillis") @Nullable Long minLogAgeMillis); @Override ReplicationMethod method(); @JsonProperty int serverId(); ZooKeeperAddress serverAddress(); @JsonProperty Map<Integer, ZooKeeperAddress> servers(); String secret(); @JsonProperty Map<String, String> additionalProperties(); @JsonProperty int timeoutMillis(); @JsonProperty int numWorkers(); @JsonProperty int maxLogCount(); @JsonProperty long minLogAgeMillis(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } | @Test void autoDetection() throws Exception { final ZooKeeperReplicationConfig cfg = Jackson.readValue( '{' + " \"method\": \"ZOOKEEPER\"," + " \"servers\": {" + " \"1\": {" + " \"host\": \"127.0.0.1\"," + " \"quorumPort\": 100," + " \"electionPort\": 101" + " }," + " \"2\": {" + " \"host\": \"255.255.255.255\"," + " \"quorumPort\": 200," + " \"electionPort\": 201" + " }" + " }" + '}', ZooKeeperReplicationConfig.class); assertThat(cfg.serverId()).isEqualTo(1); } |
MetadataService { public CompletableFuture<Revision> removeMember(Author author, String projectName, User member) { requireNonNull(author, "author"); requireNonNull(projectName, "projectName"); requireNonNull(member, "member"); final String commitSummary = "Remove the member '" + member.id() + "' from the project '" + projectName + '\''; return metadataRepo.push( projectName, Project.REPO_DOGMA, author, commitSummary, () -> fetchMetadata(projectName).thenApply( metadataWithRevision -> { final ImmutableList.Builder<JsonPatchOperation> patches = ImmutableList.builder(); metadataWithRevision .object().repos().values() .stream().filter(r -> r.perUserPermissions().containsKey(member.id())) .forEach(r -> patches.add(new RemoveOperation( perUserPermissionPointer(r.name(), member.id())))); patches.add(new RemoveOperation(JsonPointer.compile("/members" + encodeSegment(member.id())))); final Change<JsonNode> change = Change.ofJsonPatch(METADATA_JSON, Jackson.valueToTree(patches.build())); return HolderWithRevision.of(change, metadataWithRevision.revision()); }) ); } MetadataService(ProjectManager projectManager, CommandExecutor executor); CompletableFuture<ProjectMetadata> getProject(String projectName); CompletableFuture<Revision> removeProject(Author author, String projectName); CompletableFuture<Revision> restoreProject(Author author, String projectName); CompletableFuture<Member> getMember(String projectName, User user); CompletableFuture<Revision> addMember(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<Revision> removeMember(Author author, String projectName, User member); CompletableFuture<Revision> updateMemberRole(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<RepositoryMetadata> getRepo(String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName,
PerRolePermissions permission); CompletableFuture<Revision> removeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> purgeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> restoreRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> updatePerRolePermissions(Author author,
String projectName, String repoName,
PerRolePermissions perRolePermissions); CompletableFuture<Revision> addToken(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addToken(Author author, String projectName,
String appId, ProjectRole role); CompletableFuture<Revision> removeToken(Author author, String projectName, Token token); CompletableFuture<Revision> removeToken(Author author, String projectName, String appId); CompletableFuture<Revision> updateTokenRole(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addPerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> removePerUserPermission(Author author, String projectName,
String repoName, User member); CompletableFuture<Revision> updatePerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> addPerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Revision> removePerTokenPermission(Author author, String projectName,
String repoName, String appId); CompletableFuture<Revision> updatePerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
User user); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
String appId); CompletableFuture<ProjectRole> findRole(String projectName, User user); CompletableFuture<Tokens> getTokens(); CompletableFuture<Revision> createToken(Author author, String appId); CompletableFuture<Revision> createToken(Author author, String appId, boolean isAdmin); CompletableFuture<Revision> createToken(Author author, String appId, String secret); CompletableFuture<Revision> createToken(Author author, String appId, String secret,
boolean isAdmin); CompletableFuture<Revision> destroyToken(Author author, String appId); CompletableFuture<Revision> activateToken(Author author, String appId); CompletableFuture<Revision> deactivateToken(Author author, String appId); CompletableFuture<Token> findTokenByAppId(String appId); CompletableFuture<Token> findTokenBySecret(String secret); static final String METADATA_JSON; } | @Test void removeMember() { final MetadataService mds = newMetadataService(manager); mds.addRepo(author, project1, repo1, ownerOnly).join(); mds.addMember(author, project1, user1, ProjectRole.MEMBER).join(); mds.addMember(author, project1, user2, ProjectRole.MEMBER).join(); mds.addPerUserPermission(author, project1, repo1, user1, READ_ONLY).join(); mds.addPerUserPermission(author, project1, repo1, user2, READ_ONLY).join(); assertThat(mds.getMember(project1, user1).join().id()).isNotNull(); assertThat(mds.getMember(project1, user2).join().id()).isNotNull(); assertThat(mds.findPermissions(project1, repo1, user1).join()) .containsExactly(Permission.READ); mds.removeMember(author, project1, user1).join(); assertThat(mds.findPermissions(project1, repo1, user1).join()) .containsExactlyElementsOf(NO_PERMISSION); assertThat(mds.findPermissions(project1, repo1, user2).join()) .containsExactly(Permission.READ); } |
MetadataService { public CompletableFuture<Revision> removeToken(Author author, String projectName, Token token) { return removeToken(author, projectName, requireNonNull(token, "token").appId()); } MetadataService(ProjectManager projectManager, CommandExecutor executor); CompletableFuture<ProjectMetadata> getProject(String projectName); CompletableFuture<Revision> removeProject(Author author, String projectName); CompletableFuture<Revision> restoreProject(Author author, String projectName); CompletableFuture<Member> getMember(String projectName, User user); CompletableFuture<Revision> addMember(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<Revision> removeMember(Author author, String projectName, User member); CompletableFuture<Revision> updateMemberRole(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<RepositoryMetadata> getRepo(String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName,
PerRolePermissions permission); CompletableFuture<Revision> removeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> purgeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> restoreRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> updatePerRolePermissions(Author author,
String projectName, String repoName,
PerRolePermissions perRolePermissions); CompletableFuture<Revision> addToken(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addToken(Author author, String projectName,
String appId, ProjectRole role); CompletableFuture<Revision> removeToken(Author author, String projectName, Token token); CompletableFuture<Revision> removeToken(Author author, String projectName, String appId); CompletableFuture<Revision> updateTokenRole(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addPerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> removePerUserPermission(Author author, String projectName,
String repoName, User member); CompletableFuture<Revision> updatePerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> addPerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Revision> removePerTokenPermission(Author author, String projectName,
String repoName, String appId); CompletableFuture<Revision> updatePerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
User user); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
String appId); CompletableFuture<ProjectRole> findRole(String projectName, User user); CompletableFuture<Tokens> getTokens(); CompletableFuture<Revision> createToken(Author author, String appId); CompletableFuture<Revision> createToken(Author author, String appId, boolean isAdmin); CompletableFuture<Revision> createToken(Author author, String appId, String secret); CompletableFuture<Revision> createToken(Author author, String appId, String secret,
boolean isAdmin); CompletableFuture<Revision> destroyToken(Author author, String appId); CompletableFuture<Revision> activateToken(Author author, String appId); CompletableFuture<Revision> deactivateToken(Author author, String appId); CompletableFuture<Token> findTokenByAppId(String appId); CompletableFuture<Token> findTokenBySecret(String secret); static final String METADATA_JSON; } | @Test void removeToken() { final MetadataService mds = newMetadataService(manager); mds.addRepo(author, project1, repo1, ownerOnly).join(); mds.createToken(author, app1).join(); mds.createToken(author, app2).join(); mds.addToken(author, project1, app1, ProjectRole.MEMBER).join(); mds.addToken(author, project1, app2, ProjectRole.MEMBER).join(); mds.addPerTokenPermission(author, project1, repo1, app1, READ_ONLY).join(); mds.addPerTokenPermission(author, project1, repo1, app2, READ_ONLY).join(); assertThat(mds.findPermissions(project1, repo1, app1).join()) .containsExactly(Permission.READ); mds.removeToken(author, project1, app1).join(); assertThat(mds.findPermissions(project1, repo1, app1).join()) .containsExactlyElementsOf(NO_PERMISSION); assertThat(mds.findPermissions(project1, repo1, app2).join()) .containsExactly(Permission.READ); } |
Entry implements ContentHolder<T> { @Override public String toString() { return MoreObjects.toStringHelper(this).omitNullValues() .add("revision", revision.text()) .add("path", path) .add("type", type) .add("content", hasContent() ? contentAsText() : null) .toString(); } private Entry(Revision revision, String path, EntryType type, @Nullable T content); static Entry<Void> ofDirectory(Revision revision, String path); static Entry<JsonNode> ofJson(Revision revision, String path, JsonNode content); static Entry<JsonNode> ofJson(Revision revision, String path, String content); static Entry<String> ofText(Revision revision, String path, String content); static Entry<T> of(Revision revision, String path, EntryType type, @Nullable T content); Revision revision(); String path(); boolean hasContent(); void ifHasContent(Consumer<? super T> consumer); @Override EntryType type(); @Override T content(); @Override String contentAsText(); @Override String contentAsPrettyText(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void testToString() { assertThat(Entry.ofText(new Revision(1), "/a.txt", "a").toString()).isNotEmpty(); } |
MetadataService { public CompletableFuture<Revision> destroyToken(Author author, String appId) { requireNonNull(author, "author"); requireNonNull(appId, "appId"); final Collection<Project> projects = new SafeProjectManager(projectManager).list().values(); final CompletableFuture<?>[] futures = new CompletableFuture<?>[projects.size()]; int i = 0; for (final Project p : projects) { futures[i++] = removeToken(p.name(), author, appId, true).toCompletableFuture(); } return CompletableFuture.allOf(futures).thenCompose(unused -> tokenRepo.push( INTERNAL_PROJ, Project.REPO_DOGMA, author, "Remove the token: " + appId, () -> tokenRepo.fetch(INTERNAL_PROJ, Project.REPO_DOGMA, TOKEN_JSON) .thenApply(tokens -> { final Token token = tokens.object().get(appId); final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(appId)); final String secret = token.secret(); assert secret != null; final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(secret)); final Change<?> change = Change.ofJsonPatch( TOKEN_JSON, asJsonArray(new RemoveOperation(appIdPath), new RemoveIfExistsOperation(secretPath))); return HolderWithRevision.of(change, tokens.revision()); })) ); } MetadataService(ProjectManager projectManager, CommandExecutor executor); CompletableFuture<ProjectMetadata> getProject(String projectName); CompletableFuture<Revision> removeProject(Author author, String projectName); CompletableFuture<Revision> restoreProject(Author author, String projectName); CompletableFuture<Member> getMember(String projectName, User user); CompletableFuture<Revision> addMember(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<Revision> removeMember(Author author, String projectName, User member); CompletableFuture<Revision> updateMemberRole(Author author, String projectName,
User member, ProjectRole projectRole); CompletableFuture<RepositoryMetadata> getRepo(String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> addRepo(Author author, String projectName, String repoName,
PerRolePermissions permission); CompletableFuture<Revision> removeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> purgeRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> restoreRepo(Author author, String projectName, String repoName); CompletableFuture<Revision> updatePerRolePermissions(Author author,
String projectName, String repoName,
PerRolePermissions perRolePermissions); CompletableFuture<Revision> addToken(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addToken(Author author, String projectName,
String appId, ProjectRole role); CompletableFuture<Revision> removeToken(Author author, String projectName, Token token); CompletableFuture<Revision> removeToken(Author author, String projectName, String appId); CompletableFuture<Revision> updateTokenRole(Author author, String projectName,
Token token, ProjectRole role); CompletableFuture<Revision> addPerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> removePerUserPermission(Author author, String projectName,
String repoName, User member); CompletableFuture<Revision> updatePerUserPermission(Author author, String projectName,
String repoName, User member,
Collection<Permission> permission); CompletableFuture<Revision> addPerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Revision> removePerTokenPermission(Author author, String projectName,
String repoName, String appId); CompletableFuture<Revision> updatePerTokenPermission(Author author, String projectName,
String repoName, String appId,
Collection<Permission> permission); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
User user); CompletableFuture<Collection<Permission>> findPermissions(String projectName, String repoName,
String appId); CompletableFuture<ProjectRole> findRole(String projectName, User user); CompletableFuture<Tokens> getTokens(); CompletableFuture<Revision> createToken(Author author, String appId); CompletableFuture<Revision> createToken(Author author, String appId, boolean isAdmin); CompletableFuture<Revision> createToken(Author author, String appId, String secret); CompletableFuture<Revision> createToken(Author author, String appId, String secret,
boolean isAdmin); CompletableFuture<Revision> destroyToken(Author author, String appId); CompletableFuture<Revision> activateToken(Author author, String appId); CompletableFuture<Revision> deactivateToken(Author author, String appId); CompletableFuture<Token> findTokenByAppId(String appId); CompletableFuture<Token> findTokenBySecret(String secret); static final String METADATA_JSON; } | @Test void destroyToken() { final MetadataService mds = newMetadataService(manager); mds.addRepo(author, project1, repo1, ownerOnly).join(); mds.createToken(author, app1).join(); mds.createToken(author, app2).join(); mds.addToken(author, project1, app1, ProjectRole.MEMBER).join(); mds.addToken(author, project1, app2, ProjectRole.MEMBER).join(); mds.addPerTokenPermission(author, project1, repo1, app1, READ_ONLY).join(); mds.addPerTokenPermission(author, project1, repo1, app2, READ_ONLY).join(); assertThat(mds.findPermissions(project1, repo1, app1).join()) .containsExactly(Permission.READ); mds.destroyToken(author, app1).join(); assertThat(mds.findPermissions(project1, repo1, app1).join()) .containsExactlyElementsOf(NO_PERMISSION); assertThat(mds.findPermissions(project1, repo1, app2).join()) .containsExactly(Permission.READ); } |
MigrationUtil { public static synchronized void migrate(ProjectManager projectManager, CommandExecutor executor) { requireNonNull(projectManager, "projectManager"); requireNonNull(executor, "executor"); final RepositorySupport<ProjectMetadata> metadataRepo = new RepositorySupport<>(projectManager, executor, entry -> convertWithJackson(entry, ProjectMetadata.class)); final UserAndTimestamp userAndTimestamp = UserAndTimestamp.of(author); final Entry<?> tokenEntry = projectManager.get(INTERNAL_PROJ).repos() .get(Project.REPO_DOGMA) .getOrNull(Revision.HEAD, TOKEN_JSON).join(); final Collection<Token> migratedTokens = tokenEntry == null ? migrateTokens(projectManager, executor) : ImmutableSet.of(); migratedTokens.forEach(token -> logger.info("Token '{}' has been migrated", token.id())); final SafeProjectManager safeProjectManager = new SafeProjectManager(projectManager); safeProjectManager.list().values().forEach(p -> { if (alreadyMigrated(p)) { return; } if (!p.repos().exists(Project.REPO_META)) { return; } try { final ProjectMetadata metadata = metadataRepo.fetch(p.name(), Project.REPO_META, METADATA_JSON).join().object(); metadata.repos().put(Project.REPO_META, new RepositoryMetadata(Project.REPO_META, userAndTimestamp, PerRolePermissions.ofPublic())); commitProjectMetadata(metadataRepo, executor, p.name(), metadata); metadataRepo.push(p.name(), Project.REPO_META, author, "Remove the old metadata file", Change.ofRemoval(METADATA_JSON)).join(); } catch (Throwable cause) { cause = Exceptions.peel(cause); if (!(cause instanceof EntryNotFoundException)) { Exceptions.throwUnsafely(cause); } } }); final UserAndTimestamp creationTime = UserAndTimestamp.of(author); final Map<String, TokenRegistration> registrations = migratedTokens.stream() .map(t -> new TokenRegistration(t.id(), ProjectRole.MEMBER, creationTime)) .collect(toMap(TokenRegistration::id, Function.identity())); safeProjectManager.list().values().forEach(p -> { if (alreadyMigrated(p)) { return; } final Map<String, RepositoryMetadata> repos = p.repos().list().values().stream() .filter(r -> !r.name().equals(Project.REPO_DOGMA)) .map(r -> new RepositoryMetadata(r.name(), userAndTimestamp, PerRolePermissions.ofPublic())) .collect(toMap(RepositoryMetadata::name, Function.identity())); final ProjectMetadata metadata = new ProjectMetadata(p.name(), repos, ImmutableMap.of(), registrations, userAndTimestamp, null); commitProjectMetadata(metadataRepo, executor, p.name(), metadata); }); } private MigrationUtil(); static synchronized void migrate(ProjectManager projectManager, CommandExecutor executor); } | @Test void migrationWithoutLegacyTokens() { final ProjectManager pm = manager.projectManager(); final CommandExecutor executor = manager.executor(); final MetadataService mds = new MetadataService(pm, executor); MigrationUtil.migrate(pm, executor); final Tokens tokens1 = mds.getTokens().join(); assertThat(tokens1.appIds().isEmpty()).isTrue(); assertThat(tokens1.secrets().isEmpty()).isTrue(); }
@Test void migration() { final ProjectManager pm = manager.projectManager(); final CommandExecutor executor = manager.executor(); final MetadataService mds = new MetadataService(pm, executor); pm.get(INTERNAL_PROJ).repos().create(LEGACY_TOKEN_REPO, Author.SYSTEM); createProjectWithoutMetadata("legacyProject1"); createProjectWithoutMetadata("legacyProject2"); createProjectWithoutMetadata("legacyProject3"); final LegacyToken legacyToken1 = new LegacyToken("app1", SECRET_PREFIX + "app1", User.DEFAULT, Instant.now()); final LegacyToken legacyToken2 = new LegacyToken("app2", SECRET_PREFIX + "app2", User.DEFAULT, Instant.now()); final Map<String, LegacyToken> legacyTokens = ImmutableMap.of(SECRET_PREFIX + "app1", legacyToken1, SECRET_PREFIX + "app2", legacyToken2); final Change<?> change = Change.ofJsonUpsert(LEGACY_TOKEN_JSON, Jackson.valueToTree(legacyTokens)); executor.execute(Command.push(author, INTERNAL_PROJ, LEGACY_TOKEN_REPO, Revision.HEAD, "", "", Markup.PLAINTEXT, change)).join(); for (int i = 0; i < 2; i++) { MigrationUtil.migrate(pm, executor); final Tokens tokens2 = mds.getTokens().join(); assertThat(tokens2.appIds()).hasSize(2); assertThat(tokens2.appIds().get("app1").secret()).isEqualTo(legacyToken1.secret()); assertThat(tokens2.appIds().get("app2").secret()).isEqualTo(legacyToken2.secret()); final List<ProjectMetadata> metadataList = ImmutableList.of( mds.getProject("legacyProject1").join(), mds.getProject("legacyProject2").join(), mds.getProject("legacyProject3").join()); for (final ProjectMetadata m : metadataList) { assertThat(m.tokens()).hasSize(2); assertThat(m.tokens().get("app1").role()).isEqualTo(ProjectRole.MEMBER); assertThat(m.tokens().get("app2").role()).isEqualTo(ProjectRole.MEMBER); assertThat(m.repo(REPO_FOO).perRolePermissions().owner()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo("oneMoreThing").perRolePermissions().owner()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo(REPO_FOO).perRolePermissions().member()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo("oneMoreThing").perRolePermissions().member()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo(REPO_FOO).perRolePermissions().guest()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo("oneMoreThing").perRolePermissions().guest()) .containsExactly(Permission.READ, Permission.WRITE); assertThat(m.repo(REPO_META)).isNotNull(); } } }
@Test void migrationFrom0_23_0() { final ProjectManager pm = manager.projectManager(); final CommandExecutor executor = manager.executor(); pm.get(INTERNAL_PROJ).repos().create("main", Author.SYSTEM); final UserAndTimestamp userAndTimestamp = UserAndTimestamp.of(author); final Tokens tokens = new Tokens( ImmutableMap.of("app1", new Token("app1", "secret1", false, userAndTimestamp, null)), ImmutableMap.of("secret1", "app1")); executor.execute( Command.push(author, INTERNAL_PROJ, "main", Revision.HEAD, "", "", Markup.PLAINTEXT, Change.ofJsonUpsert(TOKEN_JSON, Jackson.valueToTree(tokens)))).join(); final Project project = createProjectWithoutMetadata("project1"); final ProjectMetadata metadata = new ProjectMetadata(project.name(), ImmutableMap.of(REPO_FOO, new RepositoryMetadata(REPO_FOO, userAndTimestamp, PerRolePermissions.ofPublic())), ImmutableMap.of(), ImmutableMap.of(), userAndTimestamp, null); executor.execute( Command.push(author, project.name(), REPO_META, Revision.HEAD, "", "", Markup.PLAINTEXT, Change.ofJsonUpsert(METADATA_JSON, Jackson.valueToTree(metadata)))).join(); MigrationUtil.migrate(pm, executor); final MetadataService mds = new MetadataService(pm, executor); final ProjectMetadata meta = mds.getProject("project1").join(); assertThat(meta).isNotNull(); assertThat(meta.repo(REPO_FOO)).isNotNull(); assertThat(meta.repo(REPO_META)).isNotNull(); assertThat(meta.creation()).isEqualToComparingFieldByField(userAndTimestamp); assertThat(project.repos().get(REPO_DOGMA) .getOrNull(Revision.HEAD, METADATA_JSON).join()).isNotNull(); assertThat(project.repos().get(REPO_META) .getOrNull(Revision.HEAD, METADATA_JSON).join()).isNull(); final Token token = mds.findTokenByAppId("app1").join(); assertThat(token).isNotNull(); assertThat(token.secret()).isEqualTo("secret1"); assertThat(token.isAdmin()).isFalse(); assertThat(token.isActive()).isTrue(); assertThat(token.creation()).isEqualToComparingFieldByField(userAndTimestamp); assertThat(pm.get(INTERNAL_PROJ).repos() .get(REPO_DOGMA) .getOrNull(Revision.HEAD, TOKEN_JSON).join()).isNotNull(); assertThat(pm.get(INTERNAL_PROJ).repos() .get("main") .getOrNull(Revision.HEAD, TOKEN_JSON).join()).isNull(); } |
CreateProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator CreateProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final CreateProjectCommand c = (CreateProjectCommand) Jackson.readValue( '{' + " \"type\": \"CREATE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
PurgeProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator PurgeProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final PurgeProjectCommand c = (PurgeProjectCommand) Jackson.readValue( '{' + " \"type\": \"PURGE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
RemoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator RemoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final RemoveProjectCommand c = (RemoveProjectCommand) Jackson.readValue( '{' + " \"type\": \"REMOVE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
PurgeRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator PurgeRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final PurgeRepositoryCommand c = (PurgeRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"PURGE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
RemoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator RemoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final RemoveRepositoryCommand c = (RemoveRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"REMOVE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
CreateRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator CreateRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final CreateRepositoryCommand c = (CreateRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"CREATE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
RevisionRange { public RevisionRange(int from, int to) { this(new Revision(from), new Revision(to)); } RevisionRange(int from, int to); RevisionRange(Revision from, Revision to); Revision from(); Revision to(); RevisionRange toAscending(); RevisionRange toDescending(); boolean isAscending(); boolean isRelative(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); } | @Test void revisionRange() { RevisionRange range = new RevisionRange(2, 4); assertThat(range.isAscending()).isTrue(); assertThat(range.isRelative()).isFalse(); assertThat(range.toAscending()).isSameAs(range); assertThat(range.toDescending()).isEqualTo(new RevisionRange(4, 2)); final Revision revisionTen = new Revision(10); range = new RevisionRange(revisionTen, INIT); assertThat(range.isAscending()).isFalse(); assertThat(range.isRelative()).isFalse(); assertThat(range.toAscending()).isEqualTo(new RevisionRange(INIT, revisionTen)); assertThat(range.toDescending()).isSameAs(range); range = new RevisionRange(revisionTen, revisionTen); assertThat(range.isAscending()).isFalse(); assertThat(range.isRelative()).isFalse(); assertThat(range.toAscending()).isSameAs(range); assertThat(range.toDescending()).isSameAs(range); final Revision revisionNegativeThree = new Revision(-3); final Revision revisionNegativeTen = new Revision(-10); range = new RevisionRange(revisionNegativeTen, revisionNegativeThree); assertThat(range.isAscending()).isTrue(); assertThat(range.isRelative()).isTrue(); assertThat(range.toAscending()).isSameAs(range); assertThat(range.toDescending()).isEqualTo( new RevisionRange(revisionNegativeThree, revisionNegativeTen)); final RevisionRange relativeRange = new RevisionRange(INIT, HEAD); assertThat(relativeRange.isRelative()).isTrue(); assertThat(relativeRange.from()).isSameAs(INIT); assertThat(relativeRange.to()).isSameAs(HEAD); assertThatThrownBy(relativeRange::isAscending) .isExactlyInstanceOf(IllegalStateException.class); assertThatThrownBy(relativeRange::toAscending) .isExactlyInstanceOf(IllegalStateException.class); assertThatThrownBy(relativeRange::toDescending) .isExactlyInstanceOf(IllegalStateException.class); } |
UnremoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator UnremoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName,
@JsonProperty("repositoryName") String repositoryName); @JsonProperty String repositoryName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final UnremoveRepositoryCommand c = (UnremoveRepositoryCommand) Jackson.readValue( '{' + " \"type\": \"UNREMOVE_REPOSITORY\"," + " \"projectName\": \"foo\"," + " \"repositoryName\": \"bar\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); assertThat(c.repositoryName()).isEqualTo("bar"); } |
UnremoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator UnremoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp,
@JsonProperty("author") @Nullable Author author,
@JsonProperty("projectName") String projectName); @JsonProperty String projectName(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test void backwardCompatibility() throws Exception { final UnremoveProjectCommand c = (UnremoveProjectCommand) Jackson.readValue( '{' + " \"type\": \"UNREMOVE_PROJECT\"," + " \"projectName\": \"foo\"" + '}', Command.class); assertThat(c.author()).isEqualTo(Author.SYSTEM); assertThat(c.timestamp()).isNotZero(); assertThat(c.projectName()).isEqualTo("foo"); } |
ProjectServiceV1 extends AbstractService { @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) public CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author) { return execute(Command.createProject(author, request.name())) .handle(returnOrThrow(() -> DtoConverter.convert(projectManager().get(request.name())))); } ProjectServiceV1(ProjectManager projectManager, CommandExecutor executor, MetadataService mds); @Get("/projects") CompletableFuture<List<ProjectDto>> listProjects(@Param @Nullable String status); @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author); @Get("/projects/{projectName}") @RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER }) CompletableFuture<ProjectMetadata> getProjectMetadata(
@Param String projectName,
@Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly); @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeProject(Project project, Author author); @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeProject(@Param String projectName, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}") @RequiresAdministrator CompletableFuture<ProjectDto> patchProject(@Param String projectName, JsonNode node, Author author); } | @Test void createProject() throws IOException { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse aRes = createProject(client, "myPro"); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(headers.status()).isEqualTo(HttpStatus.CREATED); final String location = headers.get(HttpHeaderNames.LOCATION); assertThat(location).isEqualTo("/api/v1/projects/myPro"); final JsonNode jsonNode = Jackson.readTree(aRes.contentUtf8()); assertThat(jsonNode.get("name").asText()).isEqualTo("myPro"); assertThat(jsonNode.get("createdAt").asText()).isNotNull(); }
@Test void createProjectWithSameName() { final WebClient client = dogma.httpClient(); createProject(client, "myNewPro"); final AggregatedHttpResponse res = createProject(client, "myNewPro"); assertThat(ResponseHeaders.of(res.headers()).status()).isEqualTo(HttpStatus.CONFLICT); final String expectedJson = '{' + " \"exception\": \"" + ProjectExistsException.class.getName() + "\"," + " \"message\": \"Project 'myNewPro' exists already.\"" + '}'; assertThatJson(res.contentUtf8()).isEqualTo(expectedJson); }
@Test void unremoveProject() { final WebClient client = dogma.httpClient(); createProject(client, "bar"); final String projectPath = PROJECTS_PREFIX + "/bar"; client.delete(projectPath).aggregate().join(); final RequestHeaders headers = RequestHeaders.of(HttpMethod.PATCH, projectPath, HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH); final String unremovePatch = "[{\"op\":\"replace\",\"path\":\"/status\",\"value\":\"active\"}]"; final AggregatedHttpResponse aRes = client.execute(headers, unremovePatch).aggregate().join(); assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.OK); final String expectedJson = '{' + " \"name\": \"bar\"," + " \"creator\": {" + " \"name\": \"System\"," + " \"email\": \"[email protected]\"" + " }," + " \"url\": \"/api/v1/projects/bar\"," + " \"createdAt\": \"${json-unit.ignore}\"" + '}'; assertThatJson(aRes.contentUtf8()).isEqualTo(expectedJson); } |
ProjectServiceV1 extends AbstractService { @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<Void> removeProject(Project project, Author author) { return mds.removeProject(author, project.name()) .thenCompose(unused -> execute(Command.removeProject(author, project.name()))) .handle(HttpApiUtil::throwUnsafelyIfNonNull); } ProjectServiceV1(ProjectManager projectManager, CommandExecutor executor, MetadataService mds); @Get("/projects") CompletableFuture<List<ProjectDto>> listProjects(@Param @Nullable String status); @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author); @Get("/projects/{projectName}") @RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER }) CompletableFuture<ProjectMetadata> getProjectMetadata(
@Param String projectName,
@Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly); @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeProject(Project project, Author author); @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeProject(@Param String projectName, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}") @RequiresAdministrator CompletableFuture<ProjectDto> patchProject(@Param String projectName, JsonNode node, Author author); } | @Test void removeProject() { final WebClient client = dogma.httpClient(); createProject(client, "foo"); final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo") .aggregate().join(); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT); } |
ProjectServiceV1 extends AbstractService { @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<Void> purgeProject(@Param String projectName, Author author) { return execute(Command.purgeProject(author, projectName)) .handle(HttpApiUtil::throwUnsafelyIfNonNull); } ProjectServiceV1(ProjectManager projectManager, CommandExecutor executor, MetadataService mds); @Get("/projects") CompletableFuture<List<ProjectDto>> listProjects(@Param @Nullable String status); @Post("/projects") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) CompletableFuture<ProjectDto> createProject(CreateProjectRequest request, Author author); @Get("/projects/{projectName}") @RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER }) CompletableFuture<ProjectMetadata> getProjectMetadata(
@Param String projectName,
@Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly); @Delete("/projects/{projectName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeProject(Project project, Author author); @Delete("/projects/{projectName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeProject(@Param String projectName, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}") @RequiresAdministrator CompletableFuture<ProjectDto> patchProject(@Param String projectName, JsonNode node, Author author); } | @Test void purgeProject() { removeProject(); final WebClient client = dogma.httpClient(); final AggregatedHttpResponse aRes = client.delete(PROJECTS_PREFIX + "/foo/removed") .aggregate().join(); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(ResponseHeaders.of(headers).status()).isEqualTo(HttpStatus.NO_CONTENT); } |
AdministrativeService extends AbstractService { @Get("/status") public ServerStatus status() { return new ServerStatus(executor().isWritable(), executor().isStarted()); } AdministrativeService(ProjectManager projectManager, CommandExecutor executor); @Get("/status") ServerStatus status(); @Patch("/status") @Consumes("application/json-patch+json") @RequiresAdministrator CompletableFuture<ServerStatus> updateStatus(ServiceRequestContext ctx,
JsonNode patch); } | @Test void status() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.get(API_V1_PATH_PREFIX + "status").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).isEqualTo( "{ \"writable\": true, \"replicating\": true }"); }
@Test void updateStatus_setUnwritable() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": false }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).isEqualTo( "{ \"writable\": false, \"replicating\": true }"); }
@Test void updateStatus_setUnwritableAndNonReplicating() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": false }," + " { \"op\": \"replace\", \"path\": \"/replicating\", \"value\": false }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).isEqualTo( "{ \"writable\": false, \"replicating\": false }"); }
@Test void updateStatus_setWritableAndNonReplicating() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": true }," + " { \"op\": \"replace\", \"path\": \"/replicating\", \"value\": false }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.BAD_REQUEST); }
@Test void redundantUpdateStatus_Writable() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": true }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.NOT_MODIFIED); }
@Test void redundantUpdateStatus_Replicating() { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/replicating\", \"value\": true }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.NOT_MODIFIED); }
@Test void updateStatus_leaveReadOnlyMode() { final WebClient client = dogma.httpClient(); updateStatus_setUnwritable(); final AggregatedHttpResponse res = client.execute( RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH), "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": true }]").aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).isEqualTo( "{ \"writable\": true, \"replicating\": true }"); } |
RemoveOperation extends JsonPatchOperation { @Override JsonNode apply(final JsonNode node) { if (path.toString().isEmpty()) { return MissingNode.getInstance(); } ensureExistence(node); final JsonNode parentNode = node.at(path.head()); final String raw = path.last().getMatchingProperty(); if (parentNode.isObject()) { ((ObjectNode) parentNode).remove(raw); } else { ((ArrayNode) parentNode).remove(Integer.parseInt(raw)); } return node; } @JsonCreator RemoveOperation(@JsonProperty("path") final JsonPointer path); @Override void serialize(final JsonGenerator jgen,
final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); @Override String toString(); } | @Test void removingRootReturnsMissingNode() { final JsonNode node = JsonNodeFactory.instance.nullNode(); final JsonPatchOperation op = new RemoveOperation(EMPTY_JSON_POINTER); final JsonNode ret = op.apply(node); assertThat(ret.isMissingNode()).isTrue(); } |
RepositoryServiceV1 extends AbstractService { @Post("/projects/{projectName}/repos") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<RepositoryDto> createRepository(ServiceRequestContext ctx, Project project, CreateRepositoryRequest request, Author author) { if (Project.isReservedRepoName(request.name())) { return HttpApiUtil.throwResponse(ctx, HttpStatus.FORBIDDEN, "A reserved repository cannot be created."); } return execute(Command.createRepository(author, project.name(), request.name())) .thenCompose(unused -> mds.addRepo(author, project.name(), request.name())) .handle(returnOrThrow(() -> DtoConverter.convert(project.repos().get(request.name())))); } RepositoryServiceV1(ProjectManager projectManager, CommandExecutor executor,
MetadataService mds); @Get("/projects/{projectName}/repos") CompletableFuture<List<RepositoryDto>> listRepositories(ServiceRequestContext ctx, Project project,
@Param @Nullable String status, User user); @Post("/projects/{projectName}/repos") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<RepositoryDto> createRepository(ServiceRequestContext ctx, Project project,
CreateRepositoryRequest request,
Author author); @Delete("/projects/{projectName}/repos/{repoName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeRepository(ServiceRequestContext ctx,
@Param String repoName,
Repository repository,
Author author); @Delete("/projects/{projectName}/repos/{repoName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeRepository(@Param String repoName,
Project project, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}/repos/{repoName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<RepositoryDto> patchRepository(@Param String repoName,
Project project,
JsonNode node,
Author author); @Get("/projects/{projectName}/repos/{repoName}/revision/{revision}") @RequiresReadPermission Map<String, Integer> normalizeRevision(Repository repository, @Param String revision); } | @Test void createRepository() throws IOException { final WebClient client = dogma.httpClient(); final AggregatedHttpResponse aRes = createRepository(client, "myRepo"); final ResponseHeaders headers = ResponseHeaders.of(aRes.headers()); assertThat(headers.status()).isEqualTo(HttpStatus.CREATED); final String location = headers.get(HttpHeaderNames.LOCATION); assertThat(location).isEqualTo("/api/v1/projects/myPro/repos/myRepo"); final JsonNode jsonNode = Jackson.readTree(aRes.contentUtf8()); assertThat(jsonNode.get("name").asText()).isEqualTo("myRepo"); assertThat(jsonNode.get("headRevision").asInt()).isOne(); assertThat(jsonNode.get("createdAt").asText()).isNotNull(); }
@Test void createRepositoryWithSameName() { final WebClient client = dogma.httpClient(); createRepository(client, "myNewRepo"); final AggregatedHttpResponse aRes = createRepository(client, "myNewRepo"); assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.CONFLICT); final String expectedJson = '{' + " \"exception\": \"" + RepositoryExistsException.class.getName() + "\"," + " \"message\": \"Repository 'myPro/myNewRepo' exists already.\"" + '}'; assertThatJson(aRes.contentUtf8()).isEqualTo(expectedJson); } |
RepositoryServiceV1 extends AbstractService { @Delete("/projects/{projectName}/repos/{repoName}") @RequiresRole(roles = ProjectRole.OWNER) public CompletableFuture<Void> removeRepository(ServiceRequestContext ctx, @Param String repoName, Repository repository, Author author) { if (Project.isReservedRepoName(repoName)) { return HttpApiUtil.throwResponse(ctx, HttpStatus.FORBIDDEN, "A reserved repository cannot be removed."); } return execute(Command.removeRepository(author, repository.parent().name(), repository.name())) .thenCompose(unused -> mds.removeRepo(author, repository.parent().name(), repository.name())) .handle(HttpApiUtil::throwUnsafelyIfNonNull); } RepositoryServiceV1(ProjectManager projectManager, CommandExecutor executor,
MetadataService mds); @Get("/projects/{projectName}/repos") CompletableFuture<List<RepositoryDto>> listRepositories(ServiceRequestContext ctx, Project project,
@Param @Nullable String status, User user); @Post("/projects/{projectName}/repos") @StatusCode(201) @ResponseConverter(CreateApiResponseConverter.class) @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<RepositoryDto> createRepository(ServiceRequestContext ctx, Project project,
CreateRepositoryRequest request,
Author author); @Delete("/projects/{projectName}/repos/{repoName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> removeRepository(ServiceRequestContext ctx,
@Param String repoName,
Repository repository,
Author author); @Delete("/projects/{projectName}/repos/{repoName}/removed") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<Void> purgeRepository(@Param String repoName,
Project project, Author author); @Consumes("application/json-patch+json") @Patch("/projects/{projectName}/repos/{repoName}") @RequiresRole(roles = ProjectRole.OWNER) CompletableFuture<RepositoryDto> patchRepository(@Param String repoName,
Project project,
JsonNode node,
Author author); @Get("/projects/{projectName}/repos/{repoName}/revision/{revision}") @RequiresReadPermission Map<String, Integer> normalizeRevision(Repository repository, @Param String revision); } | @Test void removeRepository() { final WebClient client = dogma.httpClient(); createRepository(client,"foo"); final AggregatedHttpResponse aRes = client.delete(REPOS_PREFIX + "/foo").aggregate().join(); assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.NO_CONTENT); } |
MergeQueryRequestConverter implements RequestConverterFunction { @Override public MergeQuery<?> convertRequest( ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType, @Nullable ParameterizedType expectedParameterizedResultType) throws Exception { final String queryString = ctx.query(); if (queryString != null) { final String decodedString = QueryStringDecoder.decodeComponent(queryString); final Iterable<String> queries = querySplitter.split(decodedString); final Builder<MergeSource> mergeSourceBuilder = ImmutableList.builder(); final Builder<String> jsonPathsBuilder = ImmutableList.builder(); for (String query : queries) { final int index = query.indexOf('='); if (index < 0) { continue; } final String key = query.substring(0, index); final String value = query.substring(index + 1); switch (key) { case "path": mergeSourceBuilder.add(MergeSource.ofRequired(value)); break; case "optional_path": mergeSourceBuilder.add(MergeSource.ofOptional(value)); break; case "jsonpath": jsonPathsBuilder.add(value); break; } } return MergeQuery.ofJsonPath(mergeSourceBuilder.build(), jsonPathsBuilder.build()); } return RequestConverterFunction.fallthrough(); } @Override MergeQuery<?> convertRequest(
ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
@Nullable ParameterizedType expectedParameterizedResultType); } | @Test void convert() throws Exception { final ServiceRequestContext ctx = mock(ServiceRequestContext.class); final String queryString = "path=/foo.json" + '&' + "pa%22th=/foo1.json" + '&' + "optional_path=/foo2.json" + '&' + "path=/foo3.json" + '&' + "jsonpath=$.a" + '&' + "revision=9999"; when(ctx.query()).thenReturn(queryString); @SuppressWarnings("unchecked") final MergeQuery<JsonNode> mergeQuery = (MergeQuery<JsonNode>) converter.convertRequest( ctx, mock(AggregatedHttpRequest.class), null, null); assertThat(mergeQuery).isEqualTo( MergeQuery.ofJsonPath( ImmutableList.of(MergeSource.ofRequired("/foo.json"), MergeSource.ofOptional("/foo2.json"), MergeSource.ofRequired("/foo3.json")), ImmutableList.of("$.a"))); } |
ZooKeeperCommandExecutor extends AbstractCommandExecutor implements PathChildrenCacheListener { @VisibleForTesting Optional<ReplicationLog<?>> loadLog(long revision, boolean skipIfSameReplica) { try { createParentNodes(); final String logPath = absolutePath(LOG_PATH) + '/' + pathFromRevision(revision); final LogMeta logMeta = Jackson.readValue(curator.getData().forPath(logPath), LogMeta.class); if (skipIfSameReplica && replicaId() == logMeta.replicaId()) { return Optional.empty(); } final byte[] bytes = new byte[logMeta.size()]; int offset = 0; for (long blockId : logMeta.blocks()) { final String blockPath = absolutePath(LOG_BLOCK_PATH) + '/' + pathFromRevision(blockId); final byte[] b = curator.getData().forPath(blockPath); System.arraycopy(b, 0, bytes, offset, b.length); offset += b.length; } assert logMeta.size() == offset; final ReplicationLog<?> log = Jackson.readValue(bytes, ReplicationLog.class); return Optional.of(log); } catch (Exception e) { logger.error("Failed to load a log at revision {}; entering read-only mode", revision, e); stopLater(); throw new ReplicationException("failed to load a log at revision " + revision, e); } } ZooKeeperCommandExecutor(ZooKeeperReplicationConfig cfg,
File dataDir, CommandExecutor delegate,
MeterRegistry meterRegistry,
@Nullable Consumer<CommandExecutor> onTakeLeadership,
@Nullable Consumer<CommandExecutor> onReleaseLeadership); @Override int replicaId(); @Override void childEvent(CuratorFramework unused, PathChildrenCacheEvent event); } | @Test void testLogWatch() throws Exception { final List<Replica> cluster = buildCluster(5, true , ZooKeeperCommandExecutorTest::newMockDelegate); final Replica replica1 = cluster.get(0); final Replica replica2 = cluster.get(1); final Replica replica3 = cluster.get(2); final Replica replica4 = cluster.get(3); replica4.rm.stop().join(); try { final Command<Void> command1 = Command.createRepository(Author.SYSTEM, "project", "repo1"); replica1.rm.execute(command1).join(); final Optional<ReplicationLog<?>> commandResult2 = replica1.rm.loadLog(0, false); assertThat(commandResult2).isPresent(); assertThat(commandResult2.get().command()).isEqualTo(command1); assertThat(commandResult2.get().result()).isNull(); await().untilAsserted(() -> verify(replica1.delegate).apply(eq(command1))); await().untilAsserted(() -> verify(replica2.delegate).apply(eq(command1))); await().untilAsserted(() -> verify(replica3.delegate).apply(eq(command1))); await().until(replica1::existsLocalRevision); await().until(replica2::existsLocalRevision); await().until(replica3::existsLocalRevision); assertThat(replica1.localRevision()).isEqualTo(0L); assertThat(replica2.localRevision()).isEqualTo(0L); assertThat(replica3.localRevision()).isEqualTo(0L); replica3.rm.stop().join(); final Command<?> command2 = Command.createProject(Author.SYSTEM, "foo"); replica1.rm.execute(command2).join(); await().untilAsserted(() -> verify(replica1.delegate).apply(eq(command2))); await().untilAsserted(() -> verify(replica2.delegate).apply(eq(command2))); await().untilAsserted(() -> verify(replica3.delegate, times(0)).apply(eq(command2))); replica3.rm.start().join(); verifyTwoIndependentCommands(replica3, command1, command2); replica4.rm.start().join(); verifyTwoIndependentCommands(replica4, command1, command2); } finally { for (Replica r : cluster) { r.rm.stop(); } } }
@Test void testRace() throws Exception { final List<Replica> replicas = buildCluster(NUM_REPLICAS, true , () -> { final AtomicInteger counter = new AtomicInteger(); return command -> completedFuture(new Revision(counter.incrementAndGet())); }); try { final Command<Revision> command = Command.push(Author.SYSTEM, "foo", "bar", Revision.HEAD, "", "", Markup.PLAINTEXT); final int COMMANDS_PER_REPLICA = 7; final List<CompletableFuture<Void>> futures = new ArrayList<>(); for (final Replica r : replicas) { futures.add(CompletableFuture.runAsync(() -> { for (int j = 0; j < COMMANDS_PER_REPLICA; j++) { try { r.rm.execute(command).join(); } catch (Exception e) { throw new Error(e); } } })); } for (CompletableFuture<Void> f : futures) { f.get(); } for (Replica r : replicas) { for (int i = 0; i < COMMANDS_PER_REPLICA * replicas.size(); i++) { @SuppressWarnings("unchecked") final ReplicationLog<Revision> log = (ReplicationLog<Revision>) r.rm.loadLog(i, false).get(); assertThat(log.result().major()).isEqualTo(i + 1); } } } finally { replicas.forEach(r -> r.rm.stop()); } } |
RemoveIfExistsOperation extends JsonPatchOperation { @Override JsonNode apply(final JsonNode node) { if (path.toString().isEmpty()) { return MissingNode.getInstance(); } final JsonNode found = node.at(path); if (found.isMissingNode()) { return node; } final JsonNode parentNode = node.at(path.head()); final String raw = path.last().getMatchingProperty(); if (parentNode.isObject()) { ((ObjectNode) parentNode).remove(raw); } else if (parentNode.isArray()) { ((ArrayNode) parentNode).remove(Integer.parseInt(raw)); } return node; } @JsonCreator RemoveIfExistsOperation(@JsonProperty("path") final JsonPointer path); @Override void serialize(final JsonGenerator jgen,
final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); @Override String toString(); } | @Test void removingRootReturnsMissingNode() { final JsonNode node = JsonNodeFactory.instance.nullNode(); final JsonPatchOperation op = new RemoveIfExistsOperation(EMPTY_JSON_POINTER); final JsonNode ret = op.apply(node); assertThat(ret.isMissingNode()).isTrue(); } |
PurgeSchedulingService { @VisibleForTesting void purgeProjectAndRepository(CommandExecutor commandExecutor, MetadataService metadataService) { final long minAllowedTimestamp = System.currentTimeMillis() - maxRemovedRepositoryAgeMillis; final Predicate<Instant> olderThanMinAllowed = removedAt -> removedAt.toEpochMilli() < minAllowedTimestamp; purgeProject(commandExecutor, olderThanMinAllowed); purgeRepository(commandExecutor, metadataService, olderThanMinAllowed); } PurgeSchedulingService(ProjectManager projectManager, ScheduledExecutorService purgeWorker,
long maxRemovedRepositoryAgeMillis); void start(CommandExecutor commandExecutor,
MetadataService metadataService); boolean isStarted(); void stop(); } | @Test void testSchedule() throws InterruptedException { Thread.sleep(10); service.purgeProjectAndRepository(manager.executor(), metadataService); verify(manager.executor()).execute(isA(PurgeProjectCommand.class)); verify(manager.executor()).execute(isA(PurgeRepositoryCommand.class)); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository create(String name, long creationTimeMillis, Author author) { return repos.compute( name, (n, v) -> repoWrapper.apply(delegate.create(name, creationTimeMillis, author))); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void create(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final Repository repo = m.create(name, Author.SYSTEM); assertThat(repo).isInstanceOf(RepositoryWrapper.class); assertThatThrownBy(() -> m.create(name, Author.SYSTEM)).isInstanceOf(RepositoryExistsException.class); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository get(String name) { ensureOpen(); final Repository r = repos.get(name); if (r == null) { throw new RepositoryNotFoundException(name); } return r; } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void get(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final Repository repo = m.create(name, Author.SYSTEM); final Repository repo2 = m.get(name); assertThat(repo).isSameAs(repo2); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public void remove(String name) { repos.compute(name, (n, v) -> { delegate.remove(n); return null; }); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void remove(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); m.remove(name); assertThat(m.exists(name)).isFalse(); }
@Test void remove_failure(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); assertThatThrownBy(() -> m.remove(name)).isInstanceOf(RepositoryNotFoundException.class); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public Repository unremove(String name) { ensureOpen(); return repos.computeIfAbsent(name, n -> repoWrapper.apply(delegate.unremove(n))); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void unremove_failure(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); assertThatThrownBy(() -> m.unremove(name)).isInstanceOf(RepositoryNotFoundException.class); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public Map<String, Repository> list() { ensureOpen(); final int estimatedSize = repos.size(); final String[] names = repos.keySet().toArray(new String[estimatedSize]); Arrays.sort(names); final Map<String, Repository> ret = new LinkedHashMap<>(names.length); for (String name : names) { final Repository repo = repos.get(name); if (repo != null) { ret.put(name, repo); } } return Collections.unmodifiableMap(ret); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void list(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final int numNames = 10; for (int i = 0; i < numNames; i++) { m.create(name + i, Author.SYSTEM); } final List<String> names = new ArrayList<>(m.list().keySet()); for (int i = 0; i < numNames - 1; i++) { if (names.get(i).compareTo(names.get(i + 1)) > 0) { fail("names is not in ascending order"); } } } |
RepositoryManagerWrapper implements RepositoryManager { @Override public void markForPurge(String name) { repos.compute(name, (n, v) -> { delegate.markForPurge(name); return null; }); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void markForPurge(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); m.remove(name); m.markForPurge(name); verify(purgeWorker).execute(any()); assertThat(m.listRemoved().keySet()).doesNotContain(name); } |
RepositoryManagerWrapper implements RepositoryManager { @Override public void purgeMarked() { delegate.purgeMarked(); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void purgeMarked(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); final int numNames = 10; for (int i = 0; i < numNames; i++) { final String targetName = name + i; m.create(targetName, Author.SYSTEM); m.remove(targetName); m.markForPurge(targetName); } m.purgeMarked(); for (int i = 0; i < numNames; i++) { final String targetName = name + i; assertThatThrownBy(() -> m.get(targetName)).isInstanceOf(RepositoryNotFoundException.class); } } |
RepositoryManagerWrapper implements RepositoryManager { @Override public void close(Supplier<CentralDogmaException> failureCauseSupplier) { delegate.close(failureCauseSupplier); } RepositoryManagerWrapper(RepositoryManager repoManager,
Function<Repository, Repository> repoWrapper); @Override Project parent(); @Override void close(Supplier<CentralDogmaException> failureCauseSupplier); @Override boolean exists(String name); @Override Repository get(String name); @Override Repository create(String name, long creationTimeMillis, Author author); @Override Map<String, Repository> list(); @Override Map<String, Instant> listRemoved(); @Override void remove(String name); @Override Repository unremove(String name); @Override void purgeMarked(); @Override void markForPurge(String name); @Override void ensureOpen(); @Override String toString(); } | @Test void close(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); m.create(name, Author.SYSTEM); assertThat(m.exists(name)).isTrue(); m.close(ShuttingDownException::new); assertThatThrownBy(() -> m.get(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.exists(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.remove(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.unremove(name)).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.list()).isInstanceOf(ShuttingDownException.class); assertThatThrownBy(() -> m.listRemoved()).isInstanceOf(ShuttingDownException.class); } |
JsonPatch implements JsonSerializable { public static JsonPatch fromJson(final JsonNode node) throws IOException { requireNonNull(node, "node"); try { return Jackson.treeToValue(node, JsonPatch.class); } catch (JsonMappingException e) { throw new JsonPatchException("invalid JSON patch", e); } } @JsonCreator JsonPatch(final List<JsonPatchOperation> operations); static JsonPatch fromJson(final JsonNode node); static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode); boolean isEmpty(); List<JsonPatchOperation> operations(); JsonNode apply(final JsonNode node); ArrayNode toJson(); @Override String toString(); @Override void serialize(final JsonGenerator jgen, final SerializerProvider provider); @Override void serializeWithType(final JsonGenerator jgen,
final SerializerProvider provider, final TypeSerializer typeSer); } | @Test void nullInputsDuringBuildAreRejected() { assertThatNullPointerException() .isThrownBy(() -> JsonPatch.fromJson(null)); } |
AbstractCommunicator implements Communicator { @Override public void start() { queue.clear(); try { mainThread.start(); } catch (IllegalThreadStateException e) { if (!mainThread.isAlive()) { mainThread = new Thread(this, getClass().getSimpleName()); mainThread.start(); } else { log("Thread " + mainThread.getName() + " is already running."); } } } protected AbstractCommunicator(int port); @Override void run(); @Override void setState(MopedState state); @Override void setValue(MopedDataType type, int value); @Override void addListener(CommunicationListener cl); @Override void start(); @Override void stop(); boolean isRunning(); boolean isLoggingEnabled(); void enableLogging(); void disableLogging(); } | @Test public void testMultipleStarts() { try { Communicator server = new ServerCommunicator(45756); Communicator client = new ClientCommunicator("0.0.0.0", 45756); server.start(); server.start(); Thread.sleep(100); client.start(); client.start(); server.start(); client.start(); } catch (InterruptedException e) { e.printStackTrace(); } } |
CarControlImpl implements CarControl { @Override public synchronized void addThrottle(int value) { setThrottle(currentThrottleValue + value); } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void addThrottle() { carControl.addThrottle(1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
CarControlImpl implements CarControl { @Override public synchronized void addSteer(int value) { setSteerValue(currentSteerValue + value); } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void addSteer() { carControl.addSteer(1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
StreamReader extends Thread { void setOnInputRead(Consumer<String> consumer) { this.onInputRead = consumer; } StreamReader(InputStream inputStream); @Override void run(); } | @Test void testOnDataRead() { final String data = "A"; List<String> receivedData = new ArrayList<>(); Consumer c = new Consumer(receivedData); InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); StreamReader reader = new StreamReader(stream); reader.setOnInputRead(c::stringRecieved); reader.start(); try { reader.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(receivedData.get(0), data); assertEquals(receivedData.get(1), String.valueOf((char) -1)); } |
QuickChangeFilter implements Filter { public double filterValue(double unfilteredValue){ double averageInput = calculateAverageInput(); if (previousInput.size() < maxQueueSize){ previousInput.addFirst(unfilteredValue); lastReturn = unfilteredValue; return unfilteredValue; } previousInput.addFirst(unfilteredValue); previousInput.removeLast(); if (isAcceptableChange(unfilteredValue, lastReturn)){ lastReturn = unfilteredValue; return unfilteredValue; } if (isAcceptableChange(unfilteredValue, averageInput)){ lastReturn = unfilteredValue; return unfilteredValue; } return lastReturn; } QuickChangeFilter(double acceptedChange, int maxQueueSize); double filterValue(double unfilteredValue); } | @Test public void filterValue() { final int maxQueueSize = 10; QuickChangeFilter filter = new QuickChangeFilter(10,maxQueueSize); double[] dataSet = {1,2,3,17,5,6,-18,8,9,10}; for (int i = 0; i < maxQueueSize; i++) { assertTrue(dataSet[i] == filter.filterValue(dataSet[i])); } }
@Test public void filterValue1() { final int maxQueueSize = 10; QuickChangeFilter filter = new QuickChangeFilter(10,maxQueueSize); double[] dataSet = {1,2,3,50,5,6,-50,8,9,10}; for (int i = 0; i < maxQueueSize; i++) { assertTrue(dataSet[i] == filter.filterValue(dataSet[i])); } for (double d: dataSet) { double filteredValue = filter.filterValue(d); assertTrue(filteredValue<=10 && filteredValue>=1); } }
@Test public void filterValue2(){ final int maxQueueSize = 10; QuickChangeFilter filter = new QuickChangeFilter(10,maxQueueSize); double[] zeroSet = {0,0,0,0,0,0,0,0,0,0}; for(double d: zeroSet){ double filteredValue = filter.filterValue(d); } double[] giantSet = {20,20,20,20,20,20,20,20,20,20}; for (int i = 0; i < maxQueueSize/2 +1; i++){ double filteredValue = filter.filterValue(giantSet[i]); assertTrue(filteredValue == 0); } for (int i = 0; i < maxQueueSize/2 -1; i++){ double filteredValue = filter.filterValue(giantSet[i]); assertTrue(filteredValue == 20); } } |
DistanceSensorImpl implements DistanceSensor { @Override public double getDistance() { return currentSensorValue; } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); } | @Test void getDistance(){ sensorInstance.receivedString("1.0\n",new StringBuilder()); assertEquals(0.7,sensorInstance.getDistance(), 0.01); }
@Test void testRecieveData() { CommunicationsMediator cm = new CommunicationsMediator() { private DataReceiver distanceSensor; @Override public void transmitData(String data, Direction direction) { distanceSensor.dataReceived(data); } @Override public void subscribe(Direction direction, DataReceiver receiver) { distanceSensor = receiver; } @Override public void unsubscribe(Direction direction, DataReceiver receiver) { } }; DistanceSensor ds = new DistanceSensorImpl(cm, ardMock, new LowPassFilter(LP_WEIGHT)); cm.transmitData(CAM_TGT_DIST + ",1.0\n", Direction.INTERNAL); assertEquals(0.7, ds.getDistance(),0.01); } |
DistanceSensorImpl implements DistanceSensor { @Override public double getValue() { return getDistance(); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); } | @Test void getValue(){ sensorInstance.receivedString("1.0\n",new StringBuilder()); assertEquals(0.7,sensorInstance.getValue(), 0.01); } |
DistanceSensorImpl implements DistanceSensor { @Override public void subscribe(Consumer<Double> dataConsumer) { dataConsumers.add(dataConsumer); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); } | @Test @DisplayName("should subscribe a consumer") void subscribe() { Consumer<Double> consumer = new ConsumerImpl(); Consumer<Double> consumerSpy = spy(consumer); StringBuilder sb = new StringBuilder(); sensorInstance.subscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); } |
DistanceSensorImpl implements DistanceSensor { @Override public void unsubscribe(Consumer<Double> dataConsumer) { dataConsumers.remove(dataConsumer); } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); } | @Test @DisplayName("should unsubscribe a consumer") void unsubscribe() { Consumer<Double> consumer = new ConsumerImpl(); Consumer<Double> consumerSpy = spy(consumer); StringBuilder sb = new StringBuilder(); sensorInstance.subscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); sensorInstance.unsubscribe(consumerSpy); sensorInstance.receivedString("0.3\n", sb); verify(consumerSpy, times(1)).accept(any()); } |
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void transmitData(String data, Direction direction) { for (DataReceiver dataReceiver : this.subscribers.get(direction)) { dataReceiver.dataReceived(data); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); } | @Test @DisplayName("should transmit data to receivers") void transmitData() { final int[] called = new int[1]; called[0] = 0; DataReceiver receiver1 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; DataReceiver receiver2 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; DataReceiver receiver3 = new DataReceiver() { int[] call = called; @Override public void dataReceived(String data) { call[0]++; } }; comInstance.subscribe(Direction.INTERNAL, receiver1); comInstance.subscribe(Direction.INTERNAL, receiver2); comInstance.subscribe(Direction.INTERNAL, receiver3); comInstance.transmitData(value, Direction.INTERNAL); assertEquals(3, called[0]); } |
DistanceSensorImpl implements DistanceSensor { synchronized void receivedString(String string, StringBuilder sb) { for (char c : string.toCharArray()) { if (c != 10 && c != 13) { sb.append(c); } else { setCurrentSensorValue(sb.toString()); sb.delete(0, sb.length()); } } } DistanceSensorImpl(CommunicationsMediator communicationsMediator,
ArduinoCommunicator arduinoCommunicator,
Filter filter); @Override double getDistance(); @Override double getValue(); @Override void subscribe(Consumer<Double> dataConsumer); @Override void unsubscribe(Consumer<Double> dataConsumer); } | @Test @DisplayName("should build string from input") void receivedString() { StringBuilder sb = new StringBuilder(); sensorInstance.receivedString("100", sb); assertEquals("100", sb.toString()); }
@Test @DisplayName("should reset the StringBuilder on new line") void receivedString2() { StringBuilder sb = new StringBuilder(); sensorInstance.receivedString("100\n", sb); assertEquals("", sb.toString()); } |
LowPassFilter implements Filter { public double filterValue(double nextRawValue) { double calibratedValue; calibratedValue = Double.isNaN(nextRawValue) ? currentValue : calibrateValue(nextRawValue); currentValue = calibratedValue; return calibratedValue; } LowPassFilter(double weight); double filterValue(double nextRawValue); } | @Test @DisplayName("should return positive values") void positiveFilterValue() { final double updatedValue = 10; filter.filterValue(updatedValue); double value = filter.filterValue(updatedValue); assertEquals(1.9, value); }
@Test @DisplayName("should return negative values") void negativeFilterValue() { filter.filterValue(100); double value = filter.filterValue(1); assertEquals(9.1, value); }
@Test @DisplayName("should return values with a set error span") void valueTesting() { for (int i = 0; i < 100; i++) { filter.filterValue(0.3); } filter.filterValue(0.7); for (int i = 0; i < 4; i++) { filter.filterValue(0.3); } double value = filter.filterValue(0.3); assertEquals(0.3,value,0.05); }
@Test @DisplayName("should handle noise spikes") void extremeValueTesting() { for (int i = 0; i < 100; i++) { filter.filterValue(0.3); } filter.filterValue(0.7); double value = filter.filterValue(0.3); assertEquals(0.3,value,0.05); }
@Test @DisplayName("should balance incoming stream of noise") void noiseControl() { double[] arr = {0.3, 0.35, 0.32, 0.28, 0.77, 0.3, 0.28, 0.34, 0.7}; double temp = 0; for (double v : arr) { temp = filter.filterValue(v); } assertEquals(0.3, temp, 0.05); }
@Test @DisplayName("should handle NaN values without fail") void errorProneSensorValue() { double arr[] = { NaN, 0.3, 0.56, 0.34, 0.78, 0.28, NaN, 0.35, NaN }; double value = filter.filterValue(0.37); for (double reading : arr) { value = filter.filterValue(reading); } assertThat(value, not(NaN)); } |
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void subscribe(Direction direction, DataReceiver receiver) { List<DataReceiver> dataReceivers = this.subscribers.get(direction); if (!dataReceivers.contains(receiver)) { dataReceivers.add(receiver); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); } | @Test @DisplayName("should add DataReceiver as a subscriber") void subscribe() { DataReceiver receiver = new DataReceiver() { @Override public void dataReceived(String data) { assertEquals(value, data); } }; comInstance.subscribe(Direction.INTERNAL, receiver); comInstance.transmitData(value, Direction.INTERNAL); } |
CommunicationsMediatorImpl implements CommunicationsMediator { @Override public void unsubscribe(Direction direction, DataReceiver receiver) { int index = -1; List<DataReceiver> receivers = this.subscribers.get(direction); for (int i = 0; i < receivers.size(); i++) { DataReceiver dataReceiver = receivers.get(i); if (dataReceiver == receiver) { index = i; } } if (index != -1) { receivers.remove(index); } } CommunicationsMediatorImpl(); @Override void transmitData(String data, Direction direction); @Override void subscribe(Direction direction, DataReceiver receiver); @Override void unsubscribe(Direction direction, DataReceiver receiver); } | @Test @DisplayName("should unsubscribe a subscribing receiver") void unsubscribe() { DataReceiver receiver = new DataReceiver() { @Override public void dataReceived(String data) { assert false; } }; comInstance.subscribe(Direction.INTERNAL, receiver); comInstance.unsubscribe(Direction.INTERNAL, receiver); comInstance.transmitData(value, Direction.INTERNAL); } |
StrToDoubleConverter { public double convertStringToDouble(String input) { if (input.matches("[0-9.-]+")) { double convertedDistance = Double.valueOf(input); return convertedDistance; } else { return NaN; } } double convertStringToDouble(String input); } | @Test public void convertDistanceTest(){ StrToDoubleConverter strToDoubleConverter = new StrToDoubleConverter(); assertEquals(Double.NaN, strToDoubleConverter.convertStringToDouble("ASD"),0.01); assertEquals(-1, strToDoubleConverter.convertStringToDouble("-1"), 0.01); assertEquals(23.3, strToDoubleConverter.convertStringToDouble("23.3"),0.01); } |
EngineDataConverter { public int convertToMotorValue( double throttle){ double smallestDifference = Double.POSITIVE_INFINITY; int r = 0; for (int i: validMotorValues) { System.out.println(i); double difference = Math.abs(i - throttle); if (smallestDifference > difference){ smallestDifference = difference; r = i; }else if (smallestDifference == difference && throttle < i){ r = i; } } return r; } EngineDataConverter(int[] validMotorValues); int convertToMotorValue( double throttle); } | @Test void convertToMotorValue(){ int [] motorValues = {1,2,3,4,5,6,7,8,9,10}; EngineDataConverter EDC = new EngineDataConverter(motorValues); assertEquals(1,EDC.convertToMotorValue(1.2)); assertEquals(1,EDC.convertToMotorValue(-5)); assertEquals(5,EDC.convertToMotorValue(5.4)); assertEquals(7, EDC.convertToMotorValue(6.5)); } |
CarControlImpl implements CarControl { @Override public int getLastThrottle() { return currentThrottleValue; } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void getLastThrottle() { assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE); } |
CarControlImpl implements CarControl { @Override public int getLastSteer() { return currentSteerValue; } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void getLastSteer() { assertEquals(carControl.getLastSteer(), STEER_VALUE); } |
CarControlImpl implements CarControl { @Override public synchronized void setThrottle(int value) { if (value != currentThrottleValue) { currentThrottleValue = constrainInRange(value, MIN_SPEED, MAX_SPEED); } } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void setThrottle() { carControl.setThrottle(THROTTLE_VALUE + 1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
CarControlImpl implements CarControl { @Override public synchronized void setSteerValue(int value) { if (value != currentSteerValue) { currentSteerValue = constrainInRange(value,MIN_STEER,MAX_STEER); } } CarControlImpl(ArduinoCommunicator arduinoInstance); @Override int getLastThrottle(); @Override int getLastSteer(); @Override synchronized void setThrottle(int value); @Override synchronized void setSteerValue(int value); @Override synchronized void addThrottle(int value); @Override synchronized void addSteer(int value); } | @Test void setSteerValue() { carControl.setSteerValue(STEER_VALUE + 1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
Subsets and Splits