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 =...
@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"...
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 ...
@Test void testValidateFilePath() { assertFilePathValidationSuccess("/foo.txt"); assertFilePathValidationSuccess("/foo/bar.txt"); assertFilePathValidationSuccess("/foo.bar/baz.json"); assertFilePathValidationSuccess("/foo-bar/baz-json"); assertFilePathValidationFailure("foo"); assertFilePathValidationFailure("/"); asse...
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); st...
@Test void testValidateJsonFilePath() { assertJsonFilePathValidationSuccess("/foo.json"); assertJsonFilePathValidationSuccess("/foo/bar.json"); assertJsonFilePathValidationSuccess("/foo.bar/baz.json"); assertJsonFilePathValidationSuccess("/foo.JSON"); assertJsonFilePathValidationSuccess("/foo.Json"); assertJsonFilePath...
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 isV...
@Test void testValidateDirPath() { assertDirPathValidationSuccess("/"); assertDirPathValidationSuccess("/foo"); assertDirPathValidationSuccess("/foo/"); assertDirPathValidationSuccess("/foo/bar"); assertDirPathValidationSuccess("/foo/bar/"); assertDirPathValidationSuccess("/foo.bar/"); assertDirPathValidationSuccess("/...
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 ...
@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(ava...
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() { ...
@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", R...
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { private <T> CompletableFuture<T> normalizeRevisionAndExecuteWithRetries( String projectName, String repositoryName, Revision revision, Function<Revision, CompletableFuture<T>> taskRunner) { return normalizeRevision(projectName, repositoryName, revision) ...
@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( exceptionallyCompletedFutur...
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, RepositoryIn...
@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(dog...
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, S...
@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...
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<Completa...
@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(C...
ReplicationLagTolerantCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> watchRepository( String projectName, String repositoryName, Revision lastKnownRevision, String pathPattern, long timeoutMillis) { return normalizeRevisionAndExecuteWithRetries( projectName, repositoryName, las...
@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.watchRep...
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, lastKnown...
@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(), ...
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, Complet...
@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))) .thenAn...
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...
@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 S...
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 ...
@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 = newClientBuild...
@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 StringBuil...
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".eq...
@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 revisio...
@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\" }")); assertThatJso...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> createProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.createProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIfac...
@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("pro...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> removeProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.removeProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIfac...
@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("pro...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> purgeProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.purgeProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface ...
@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...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> unremoveProject(String projectName) { return run(callback -> { validateProjectName(projectName); client.unremoveProject(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.Async...
@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...
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, Cen...
@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(Immutable...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Set<String>> listRemovedProjects() { return run(client::listRemovedProjects); } LegacyCentralDogma(ScheduledExecutorService executor, CentralDogmaService.AsyncIface client); @Override CompletableFuture<Void> createProject(String projec...
@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(Immu...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> createRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.createRepository(projectName, repositoryName, callback); }); } LegacyCen...
@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();...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> removeRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.removeRepository(projectName, repositoryName, callback); }); } LegacyCen...
@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();...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> purgeRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.purgeRepository(projectName, repositoryName, callback); }); } LegacyCentr...
@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(); ve...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Void> unremoveRepository(String projectName, String repositoryName) { return run(callback -> { validateProjectAndRepositoryName(projectName, repositoryName); client.unremoveRepository(projectName, repositoryName, callback); }); } Legac...
@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()).isN...
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 revis...
@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...
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 futur...
@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", "arthur@dent.com"), "1978-03-08T00:00:00Z", "...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Set<String>> listRemovedRepositories(String projectName) { return run(callback -> { validateProjectName(projectName); client.listRemovedRepositories(projectName, callback); }); } LegacyCentralDogma(ScheduledExecutorService executor, Ce...
@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("projec...
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(project...
@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...
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 -> { validatePro...
@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(anyS...
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<L...
@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(anyStr...
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 -> { validatePr...
@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", "name@sample.com"), TIMESTAMP, "summary", new Comment("detail").setMarkup(TMarkup.PLA...
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 -> { validateP...
@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)....
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(ca...
@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(...
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.UNK...
@Test void push() throws Exception { doAnswer(invocation -> { final AsyncMethodCallback<TCommit> callback = invocation.getArgument(7); callback.onComplete(new TCommit( new TRevision(1), new TAuthor("name", "name@sample.com"), TIMESTAMP, "summary", new Comment("detail"), ImmutableList.of())); return null; }).when(iface)...
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> ...
@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",...
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....
@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 -> { validate...
@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(a...
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, repository...
@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(clien...
LegacyCentralDogma extends AbstractCentralDogma { @Override public CompletableFuture<Revision> watchRepository(String projectName, String repositoryName, Revision lastKnownRevision, String pathPattern, long timeoutMillis) { final CompletableFuture<WatchRepositoryResult> future = run(callback -> { validateProjectAndRepo...
@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(), a...
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(p...
@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(), ...
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 se...
@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\"," + " \...
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 '" + ...
@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, re...
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(St...
@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, Pr...
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, E...
@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<?>[...
@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, P...
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 -> co...
@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.appId...
CreateProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator CreateProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, @JsonProperty("pro...
@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....
PurgeProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator PurgeProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, @JsonProperty("project...
@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.pro...
RemoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator RemoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, @JsonProperty("pro...
@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....
PurgeRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator PurgeRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, @...
@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...
RemoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator RemoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, ...
@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); assertTha...
CreateRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator CreateRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, ...
@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); assertTha...
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(); @Ove...
@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(...
UnremoveRepositoryCommand extends ProjectCommand<Void> { @JsonProperty public String repositoryName() { return repositoryName; } @JsonCreator UnremoveRepositoryCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, ...
@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); ass...
UnremoveProjectCommand extends RootCommand<Void> { @JsonProperty public String projectName() { return projectName; } @JsonCreator UnremoveProjectCommand(@JsonProperty("timestamp") @Nullable Long timestamp, @JsonProperty("author") @Nullable Author author, @JsonPrope...
@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(); assertT...
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(() -> ...
@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...
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...
@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()).is...
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); }...
@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()).isEqualT...
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("a...
@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 vo...
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()) { ((...
@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...
@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 = ...
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)) ...
@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(); i...
@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(...
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 lo...
@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.r...
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 =...
@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()...
@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, ...
@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, ...
@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 ...
@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(() -...
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, R...
@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.leng...
@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).c...
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> repoWrapp...
@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<Cen...
@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...
RepositoryManagerWrapper implements RepositoryManager { @Override public void close(Supplier<CentralDogmaException> failureCauseSupplier) { delegate.close(failureCauseSupplier); } RepositoryManagerWrapper(RepositoryManager repoManager, Function<Repository, Repository> repoWrapper); @...
@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(...
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(...
@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() + " ...
@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.prin...
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); @Overrid...
@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 sy...
@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); r...
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); prev...
@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 ...
DistanceSensorImpl implements DistanceSensor { @Override public double getDistance() { return currentSensorValue; } DistanceSensorImpl(CommunicationsMediator communicationsMediator, ArduinoCommunicator arduinoCommunicator, Filter filter); @Override double getDistance(); @Ov...
@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, Dir...
DistanceSensorImpl implements DistanceSensor { @Override public double getValue() { return getDistance(); } DistanceSensorImpl(CommunicationsMediator communicationsMediator, ArduinoCommunicator arduinoCommunicator, Filter filter); @Override double getDistance(); @Override d...
@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); @Ove...
@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)).acce...
DistanceSensorImpl implements DistanceSensor { @Override public void unsubscribe(Consumer<Double> dataConsumer) { dataConsumers.remove(dataConsumer); } DistanceSensorImpl(CommunicationsMediator communicationsMediator, ArduinoCommunicator arduinoCommunicator, Filter filter);...
@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))....
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 ...
@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 = ca...
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 commu...
@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 StringBuil...
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 nextRaw...
@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.filterVa...
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(); @Overri...
@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 (da...
@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.t...
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.convertStri...
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 ...
@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(...
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...
@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 v...
@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 getLastSte...
@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(); ...
@Test void setSteerValue() { carControl.setSteerValue(STEER_VALUE + 1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); }