method2testcases
stringlengths 118
6.63k
|
---|
### Question:
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(); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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"))); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test void unremove_failure(TestInfo testInfo) { final String name = TestUtil.normalizedDisplayName(testInfo); assertThatThrownBy(() -> m.unremove(name)).isInstanceOf(RepositoryNotFoundException.class); } |
### Question:
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(); }### Answer:
@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"); } } } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test void nullInputsDuringBuildAreRejected() { assertThatNullPointerException() .isThrownBy(() -> JsonPatch.fromJson(null)); } |
### Question:
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(); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@Test void addThrottle() { carControl.addThrottle(1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
### Question:
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); }### Answer:
@Test void addSteer() { carControl.addSteer(1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
### Question:
StreamReader extends Thread { void setOnInputRead(Consumer<String> consumer) { this.onInputRead = consumer; } StreamReader(InputStream inputStream); @Override void run(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test void getValue(){ sensorInstance.receivedString("1.0\n",new StringBuilder()); assertEquals(0.7,sensorInstance.getValue(), 0.01); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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]); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@Test void getLastThrottle() { assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE); } |
### Question:
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); }### Answer:
@Test void getLastSteer() { assertEquals(carControl.getLastSteer(), STEER_VALUE); } |
### Question:
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); }### Answer:
@Test void setThrottle() { carControl.setThrottle(THROTTLE_VALUE + 1); assertEquals(carControl.getLastThrottle(), THROTTLE_VALUE + 1); } |
### Question:
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); }### Answer:
@Test void setSteerValue() { carControl.setSteerValue(STEER_VALUE + 1); assertEquals(carControl.getLastSteer(), STEER_VALUE + 1); } |
### Question:
PathSet implements Set<Path> { public boolean containsAncestor(Path path) { for (Path p : this) { if (p.isAncestorOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void containsAncestor() { assertTrue(data.remove(new Path("/"))); assertTrue(data.containsAncestor(new Path("/foo/baz"))); assertTrue(data.containsAncestor(new Path("/bar/baz"))); assertTrue(!data.containsAncestor(new Path("/foo"))); assertTrue(!data.containsAncestor(new Path("/baz"))); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isDescendantOf(Path other) { if (other.isRoot()) { if (isRoot()) { return false; } else if (isAbsolute()) { return true; } else { return false; } } else { return path.startsWith(other.path + SEPARATOR) && path.length() > other.path.length(); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isDescendantOf() { assertDescendant(new Path("/"), new Path("/foo")); assertDescendant(new Path("/"), new Path("/foo/bar")); assertDescendant(new Path("/foo"), new Path("/foo/bar")); assertNotDescendant(new Path("/foo"), new Path("/bar/foo")); assertNotDescendant(new Path("/foo"), new Path("/")); assertNotDescendant(new Path("/"), new Path("relative")); assertDescendant(new Path("foo/bar"), new Path("foo/bar/baz")); assertNotDescendant(new Path("foo/bar"), new Path("bar")); assertNotDescendant(new Path("/"), new Path("/")); assertNotDescendant(new Path("/foo"), new Path("/foo")); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isRoot() { return path.equals(SEPARATOR); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isRoot() { assertTrue(new Path("/").isRoot()); assertTrue(!new Path("foo").isRoot()); assertTrue(!new Path("/foo").isRoot()); } |
### Question:
Path implements Iterable<String>, Serializable { public Iterator<String> iterator() { return new Iterator<String>() { int idx = 0; public boolean hasNext() { return idx < size(); } public String next() { return part(idx++); } public void remove() { throw new UnsupportedOperationException("Path parts iterator is read only"); } }; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test @SuppressWarnings("unused") public void iterator() { Path path = new Path("/foo/bar/baz"); Set<String> parts = new HashSet<String>(Arrays.asList(new String[]{"foo", "bar", "baz"})); for (String part : path) { assertTrue(parts.remove(part)); } assertTrue(parts.isEmpty()); for (String part : new Path("/")) { fail(); } } |
### Question:
Path implements Iterable<String>, Serializable { public Path parent() { if (isRoot()) { return null; } else { return new Path(path + "/.."); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void parent() { assertTrue(new Path("/").parent() == null); assertEquals(new Path("/foo").parent(), new Path("/")); assertEquals(new Path("/foo/bar").parent(), new Path("/foo")); assertEquals(new Path("foo").parent(), new Path(".")); assertEquals(new Path("foo/bar").parent(), new Path("foo")); assertEquals(new Path(".").parent(), new Path("..")); assertEquals(new Path("../foo").parent(), new Path("..")); assertEquals(new Path("..").parent(), new Path("../..")); } |
### Question:
Path implements Iterable<String>, Serializable { public String part(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } int start = isAbsolute() ? 1 : 0; for (int i = 0; i < index; i++) { start = path.indexOf(SEPARATOR, start); if (start < 0) { throw new IndexOutOfBoundsException(); } start++; } int end = path.indexOf(SEPARATOR, start); if (end < 0) { end = path.length(); } return path.substring(start, end); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void part() { Path path = new Path("/foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); path = new Path("foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); } |
### Question:
Path implements Iterable<String>, Serializable { public int size() { if (isRoot()) { return 0; } int size = 0; int pos = 0; while (pos >= 0) { size++; pos = path.indexOf(SEPARATOR, pos + 1); } return size; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void size() { assertEquals(new Path("/").size(), 0); assertEquals(new Path("/foo").size(), 1); assertEquals(new Path("/foo/bar").size(), 2); assertEquals(new Path("/foo/bar/baz").size(), 3); } |
### Question:
Path implements Iterable<String>, Serializable { public Path subpath(int idx) { if (idx <= 0) { throw new IndexOutOfBoundsException(); } final int size = size(); final boolean abs = isAbsolute(); int chunks = (abs) ? size + 1 : size; if (idx > chunks) { throw new IndexOutOfBoundsException(); } if (idx == chunks) { return this; } int iterations = ((abs) ? idx - 1 : idx); int end = 1; for (int i = 0; i < iterations; i++) { end = path.indexOf(SEPARATOR, end + 1); } if (end == 0) { return new Path("/"); } String newPath = path.substring(0, end); return new Path(newPath); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void subpath() { Path path = new Path("/foo/bar/baz"); assertEquals(new Path("/foo/bar/baz"), path.subpath(4)); assertEquals(new Path("/foo/bar"), path.subpath(3)); assertEquals(new Path("/foo"), path.subpath(2)); assertEquals(new Path("/"), path.subpath(1)); try { path.subpath(5); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(0); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(-1); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } path = new Path("foo/bar/baz"); assertEquals(new Path("foo/bar/baz"), path.subpath(3)); assertEquals(new Path("foo/bar"), path.subpath(2)); assertEquals(new Path("foo"), path.subpath(1)); try { path.subpath(4); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(0); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(-1); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } } |
### Question:
Path implements Iterable<String>, Serializable { public Path toRelative(Path ancestor) { if (isRoot()) { throw new IllegalStateException("Cannot make root path relative"); } if (!isDescendantOf(ancestor)) { throw new IllegalArgumentException("Cannot create relative path because this path: " + this + " is not descendant of ancestor argument: " + ancestor); } Path fragment = new Path(path.substring(ancestor.path.length()), false); if (fragment.isAbsolute()) { fragment = fragment.toRelative(new Path("/")); } return fragment; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void toRelative() { try { new Path("/").toRelative(new Path("/")); fail(); } catch (IllegalStateException e) { } try { new Path("/foo/bar").toRelative(new Path("/bar")); fail(); } catch (IllegalArgumentException e) { } assertEquals(new Path("foo"), new Path("/foo").toRelative(new Path("/"))); assertEquals(new Path("bar"), new Path("/foo/bar").toRelative(new Path("/foo"))); assertEquals(new Path("bar"), new Path("foo/bar").toRelative(new Path("foo"))); } |
### Question:
PathSet implements Set<Path> { public boolean containsParent(Path path) { for (Path p : this) { if (p.isParentOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void containsParent() { assertTrue(!data.containsParent(new Path("/"))); assertTrue(data.containsParent(new Path("/foo"))); assertTrue(data.containsParent(new Path("/foo/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz/boz"))); assertTrue(!data.containsParent(new Path("/foo/baz/bar"))); } |
### Question:
PathSet implements Set<Path> { public void removeDescendants(Path path) { Iterator<Path> i = iterator(); while (i.hasNext()) { Path p = i.next(); if (p.isDescendantOf(path)) { i.remove(); } } } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void removeDescendants() { data.removeDescendants(new Path("/foo")); assertTrue(data.size() == 3); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); assertTrue(data.contains(new Path("/foo"))); data.removeDescendants(new Path("/")); assertTrue(data.size() == 1); assertTrue(data.contains(new Path("/"))); } |
### Question:
PathSet implements Set<Path> { public boolean removeWithDescendants(Path path) { boolean ret = remove(path); removeDescendants(path); return ret; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); }### Answer:
@Test public void removeWithDescendants() { data.removeWithDescendants(new Path("/foo")); assertTrue(data.size() == 2); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); data.removeWithDescendants(new Path("/")); assertTrue(data.isEmpty()); } |
### Question:
Path implements Iterable<String>, Serializable { public Path append(Path relative) { if (relative == null) { throw new IllegalArgumentException("Argument 'relative' cannot be null"); } if (relative.isAbsolute()) { throw new IllegalArgumentException("Cannot append an absolute path"); } StringBuilder appended = new StringBuilder(path.length() + 1 + relative.path.length()); appended.append(path); if (!path.endsWith(SEPARATOR)) { appended.append("/"); } appended.append(relative.path); return new Path(appended.toString()); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void append() { assertEquals(new Path("/").append(new Path("foo")), new Path("/foo")); assertEquals(new Path("/").append(new Path("foo/bar")), new Path("/foo/bar")); assertEquals(new Path("/foo").append(new Path("bar")), new Path("/foo/bar")); assertEquals(new Path("/foo").append(new Path("../bar")), new Path("/bar")); assertEquals(new Path("/foo").append(new Path("../../bar")), new Path("/bar")); assertEquals(new Path("foo").append(new Path("bar")), new Path("foo/bar")); assertEquals(new Path("foo").append(new Path("../bar")), new Path("bar")); assertEquals(new Path("foo").append(new Path("../../bar")), new Path("../bar")); try { new Path("/foo").append(new Path("/")); fail(); } catch (IllegalArgumentException e) { } } |
### Question:
Path implements Iterable<String>, Serializable { @Override public String toString() { return path; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void construction() { assertEquals(new Path("/").toString(), "/"); assertEquals(new Path("/foo").toString(), "/foo"); assertEquals(new Path("/foo/").toString(), "/foo"); assertEquals(new Path("/foo/bar").toString(), "/foo/bar"); assertEquals(new Path("/foo/bar/").toString(), "/foo/bar"); assertEquals(new Path("foo").toString(), "foo"); assertEquals(new Path("foo/").toString(), "foo"); assertEquals(new Path("foo/bar").toString(), "foo/bar"); assertEquals(new Path("foo/bar/").toString(), "foo/bar"); try { new Path(""); fail(); } catch (IllegalArgumentException e) { } try { new Path(null); fail(); } catch (IllegalArgumentException e) { } } |
### Question:
Path implements Iterable<String>, Serializable { public String getName() { if (path.equals(SEPARATOR)) { return path; } else { int last = path.lastIndexOf(SEPARATOR); return path.substring(last + 1); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void getName() { assertEquals(new Path("/").getName(), "/"); assertEquals(new Path("/foo").getName(), "foo"); assertEquals(new Path("/foo/bar").getName(), "bar"); assertEquals(new Path("foo").getName(), "foo"); assertEquals(new Path("foo/bar").getName(), "bar"); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isAbsolute() { return path.startsWith("/"); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isAbsolute() { assertTrue(new Path("/").isAbsolute()); assertTrue(new Path("/foo").isAbsolute()); assertTrue(new Path("/foo/bar").isAbsolute()); assertTrue(!new Path("foo").isAbsolute()); assertTrue(!new Path("foo/bar").isAbsolute()); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isCanonical() { int offset = 0; boolean text = false; if (path.equals(".")) { return true; } if (!isRoot() && path.endsWith("/")) { return false; } while (offset < path.length()) { String sub = path.substring(offset); if (sub.equals("/") || sub.equals("")) { break; } if (sub.startsWith("./") || sub.equals(".")) { return false; } boolean up = sub.startsWith("../") || sub.equals(".."); if (text && up) { return false; } if (up == false) { text = true; } int next = sub.indexOf("/"); if (next == -1) { break; } else if (next == 0 && offset != 0) { return false; } else { offset += next + 1; } } return true; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isCannonical() { assertTrue(new Path("/", false).isCanonical()); assertTrue(new Path("a", false).isCanonical()); assertTrue(new Path("a/b", false).isCanonical()); assertTrue(new Path("a/b/c", false).isCanonical()); assertTrue(new Path("a/..b/c", false).isCanonical()); assertTrue(new Path("a/b/c..", false).isCanonical()); assertTrue(new Path("..", false).isCanonical()); assertTrue(new Path("../", false).isCanonical()); assertTrue(new Path("../..", false).isCanonical()); assertTrue(new Path("../../", false).isCanonical()); assertTrue(new Path("../a", false).isCanonical()); assertTrue(new Path(".", false).isCanonical()); assertTrue(!new Path("./.", false).isCanonical()); assertTrue(!new Path("a assertTrue(!new Path("a/b/c assertTrue(!new Path("/.", false).isCanonical()); assertTrue(!new Path("./a", false).isCanonical()); assertTrue(!new Path("a/.", false).isCanonical()); assertTrue(!new Path("a/./b", false).isCanonical()); assertTrue(!new Path("./a/b/c", false).isCanonical()); assertTrue(!new Path("a/..b/./c", false).isCanonical()); assertTrue(!new Path("a/b/c../.", false).isCanonical()); assertTrue(!new Path("./..", false).isCanonical()); assertTrue(!new Path(".././", false).isCanonical()); assertTrue(!new Path(".././..", false).isCanonical()); assertTrue(!new Path("../.././", false).isCanonical()); assertTrue(!new Path("./../a", false).isCanonical()); assertTrue(!new Path("/..", false).isCanonical()); assertTrue(!new Path("/../..", false).isCanonical()); assertTrue(!new Path("a/..", false).isCanonical()); assertTrue(!new Path("a/../", false).isCanonical()); assertTrue(!new Path("../a/..", false).isCanonical()); assertTrue(!new Path("../../a/..", false).isCanonical()); assertTrue(!new Path("../../../a/..", false).isCanonical()); } |
### Question:
Path implements Iterable<String>, Serializable { public boolean isChildOf(Path other) { return isDescendantOf(other) && size() == other.size() + 1; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; }### Answer:
@Test public void isChildOf() { assertChild(new Path("/"), new Path("/foo")); assertNotChild(new Path("/"), new Path("/foo/bar")); assertChild(new Path("/foo/bar"), new Path("/foo/bar/baz")); assertNotChild(new Path("/foo/bar"), new Path("/foo/baz/bar")); assertNotChild(new Path("/"), new Path("/")); assertNotChild(new Path("/foo"), new Path("/")); } |
### Question:
PoiList { public List<OsmObject> createAlternateList() { return poiList.subList(1, poiList.size()); } private PoiList(); static synchronized PoiList getInstance(); List<OsmObject> getPoiList(); void setPoiList(List<OsmObject> poiList); List<OsmObject> createAlternateList(); void clearPoiList(); void sortList(final double queryLatitude, final double queryLongitude); String serializePoiList(); void decodePoiList(String json); }### Answer:
@Test public void createAlternateList() { List<OsmObject> alternateList = PoiList.getInstance().createAlternateList(); assertEquals(0, alternateList.size()); } |
### Question:
QuestionsPresenter implements QuestionsActivityContract.Presenter { @Override public void assessIntentData(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } QuestionsPresenter(QuestionsActivityContract.View view, SourceContract.Preferences preferences); @Override void addPoiNameToTextview(); @Override void assessIntentData(URI uri); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void assessIntentData() { URI uri = null; try { uri = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } questionsPresenter.assessIntentData(uri); verify(preferences).setStringPreference("oauth_verifier", "1"); verify(preferences).setStringPreference("oauth_token", "1"); verify(view).startOAuth(); } |
### Question:
IntroPresenter implements IntroFragmentContract.Presenter { @Override public void getDetails() { String address = getAddress(); view.showDetails(poi.getName(), address, poi.getDrawable()); } IntroPresenter(IntroFragmentContract.View view); @Override void getDetails(); }### Answer:
@Test public void addPoiToTextview() { introPresenter.getDetails(); verify(view).showDetails("Kitchen", " ", R.drawable.ic_restaurant); } |
### Question:
OsmLoginPresenter implements OsmLoginFragmentContract.Presenter { @Override public void clickedOsmLoginButton() { preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN_SECRET, ""); view.startOAuth(); } OsmLoginPresenter(OsmLoginFragmentContract.View view, SourceContract.Preferences preferences); @Override void clickedOsmLoginButton(); }### Answer:
@Test public void checkPreferencesAreCleared() { presenter.clickedOsmLoginButton(); verify(view).startOAuth(); } |
### Question:
QuestionPresenter implements QuestionFragmentContract.Presenter { @Override public void getQuestion() { List<QuestionsContract> questions = this.listOfQuestions.getQuestion(); QuestionsContract questionsContract = questions.get(position); int question = questionsContract.getQuestion(); int color = questionsContract.getColor(); int drawable = questionsContract.getIcon(); view.showQuestion(question, poi.getName(), color, drawable); String key = questionsContract.getTag(); String answer = poi.getTag(key); if (answer != null) { view.setPreviousAnswer(answer); } else { view.setPreviousAnswer(""); } } QuestionPresenter(QuestionFragmentContract.View view, int position, SourceContract.Preferences preferences); @Override void getQuestion(); @Override void onAnswerSelected(int id); }### Answer:
@Test public void getQuestionTest() { questionPresenter.getQuestion(); verify(view).showQuestion(anyInt(), anyString(), anyInt(), anyInt()); }
@Test public void getPreviousAnswerTest() { questionPresenter.getQuestion(); verify(view).setPreviousAnswer(anyString()); } |
### Question:
QuestionPresenter implements QuestionFragmentContract.Presenter { @Override public void onAnswerSelected(int id) { List<QuestionsContract> questions = this.listOfQuestions.getQuestion(); QuestionsContract questionsContract = questions.get(position); int selectedColor = questionsContract.getColor(); int unselectedColor = R.color.colorPrimary; String answer = null; switch (id) { case R.id.answer_yes: view.setBackgroundColor(selectedColor, unselectedColor, unselectedColor); answer = "yes"; break; case R.id.answer_no: view.setBackgroundColor(unselectedColor, selectedColor, unselectedColor); answer = "no"; break; case R.id.answer_unsure: view.setBackgroundColor(unselectedColor, unselectedColor, selectedColor); answer = "unsure"; break; default: break; } String answerTag = questionsContract.getAnswer(answer); String questionTag = questionsContract.getTag(); addAnswer(questionTag, answerTag); if (position == listOfQuestions.getNoOfQuestions() - 1) { view.createChangesetTags(); new Thread(new Runnable() { @Override public void run() { SourceContract.upload upload = new UploadToOSM(preferences); upload.uploadToOsm(); } }).start(); } } QuestionPresenter(QuestionFragmentContract.View view, int position, SourceContract.Preferences preferences); @Override void getQuestion(); @Override void onAnswerSelected(int id); }### Answer:
@Test public void yesAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_yes); verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); }
@Test public void noAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_no); verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); }
@Test public void unsureAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_unsure); Set<String> keySet = Answers.getAnswerMap().keySet(); String key = keySet.toArray(new String[keySet.size()])[0]; String actual_answer = Answers.getAnswerMap().get(key); String expected_answer = ""; verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); assertEquals(expected_answer, actual_answer); } |
### Question:
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void checkIfOauth(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void checkIfInOAuthFlow() { URI url = null; try { url = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } presenter.checkIfOauth(url); verify(view).startOAuth(); } |
### Question:
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void showIfLoggedIn() { boolean loggedIn = preferences.getBooleanPreference(PreferenceList.LOGGED_IN_TO_OSM); int message; int button; String userName = getUserName(); if (loggedIn) { if ("".equals(userName)) { message = R.string.logged_in; } else { message = R.string.logged_in_as; } button = R.string.log_out; } else { message = R.string.not_logged_in; button = R.string.authorise_openstreetmap; } view.showIfLoggedIn(message, button, userName); } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void checkIfUsernameIsSetCorrectly() { presenter.showIfLoggedIn(); verify(view).showIfLoggedIn(anyInt(), anyInt(), (String) any()); } |
### Question:
QueryOverpass implements SourceContract.Overpass { @Override public String getOverpassUri(double latitude, double longitude, float accuracy) { float measuredAccuracy; if (accuracy < 20) { measuredAccuracy = 20; } else if (accuracy > 100) { measuredAccuracy = 100; } else { measuredAccuracy = accuracy; } String overpassLocation = String.format("around:%s,%s,%s", measuredAccuracy, latitude, longitude); String nwr = "%1$s[~\"^(%2$s)$\"~\".\"](%3$s);"; String types = "shop|amenity|leisure|tourism"; String node = String.format(nwr, "node", types, overpassLocation); String way = String.format(nwr, "way", types, overpassLocation); String relation = String.format(nwr, "relation", types, overpassLocation); return String.format("https: } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); }### Answer:
@Test public void testGenerateOverpassUri() { double latitude = 53; double longitude = -7; float accuracy = 50; String expected_uri = "https: String uri = queryOverpass.getOverpassUri(latitude, longitude, accuracy); assertEquals(expected_uri, uri); } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void findVersion() { String version = BuildConfig.VERSION_NAME; view.setVersion(version); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkVersionNameIsSet() { aboutPresenter.findVersion(); verify(view).setVersion(BuildConfig.VERSION_NAME); } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getLicence() { String uri = "http: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkLicenceDetailsAreSet() { aboutPresenter.getLicence(); verify(view).visitUri("http: } |
### Question:
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getGitHub() { String uri = "https: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); }### Answer:
@Test public void checkSourceDetailsAreSet() { aboutPresenter.getGitHub(); verify(view).visitUri("https: } |
### Question:
Utilities { public static Map<String, List<String>> splitQuery(URI url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } static Map<String, List<String>> splitQuery(URI url); static float computeDistance(double latitude1, double longitude1, double latitude2, double longitude2); }### Answer:
@Test public void splitqueryValidUrl() throws URISyntaxException, UnsupportedEncodingException { String uri = "http: URI url = new URI(uri); Map<String, List<String>> map = Utilities.splitQuery(url); assertEquals("[out:json]", map.get("data").get(0)); } |
### Question:
QueryOverpass implements SourceContract.Overpass { public String getType(JSONObject tags) throws JSONException { String type = ""; if (tags.has("amenity")) { type = tags.getString("amenity"); } if (tags.has("shop")) { type = tags.getString("shop"); } if (tags.has("tourism")) { type = tags.getString("tourism"); } if (tags.has("leisure")) { type = tags.getString("leisure"); } return type; } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); }### Answer:
@Test public void testGetOverpassResultPoiType() throws JSONException { String expected_result = "hairdresser"; JSONObject json = new JSONObject().put("amenity", expected_result); String result = queryOverpass.getType(json); assertEquals(expected_result, result); } |
### Question:
Answers { public static Map<String, String> getAnswerMap() { getInstance(); return answerMap; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); }### Answer:
@Test public void getKeyFromTag() { String tag = this.questionObject.getTag(); String expectedValue = this.questionObject.getAnswerYes(); String actualValue = Answers.getAnswerMap().get(tag); assertEquals(expectedValue, actualValue); } |
### Question:
Answers { public static Map<String, String> getChangesetTags() { getInstance(); return changesetTags; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); }### Answer:
@Test public void checkChangesetTagsAreSet() { Map<String, String> actualTags = Answers.getChangesetTags(); Map<String, String> expectedTags = new HashMap<>(); expectedTags.put("", ""); assertEquals(expectedTags, actualTags); } |
### Question:
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void getPoiDetails() { String name = poiList.get(0).getName(); view.setTextview(name); view.setAdapter(alternateList); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); }### Answer:
@Test public void addPoiToTextview() { notHerePresenter.getPoiDetails(); verify(view).setTextview("Kitchen"); } |
### Question:
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void onItemClicked(int i) { ArrayList<OsmObject> intentList = new ArrayList<>(); intentList.add(0, this.alternateList.get(i)); PoiList.getInstance().setPoiList(intentList); view.startActivity(); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); }### Answer:
@Test public void onClick() { notHerePresenter.onItemClicked(0); verify(view).startActivity(); } |
### Question:
QuestionsPresenter implements QuestionsActivityContract.Presenter { @Override public void addPoiNameToTextview() { List<OsmObject> poiList = PoiList.getInstance().getPoiList(); if (poiList.size() != 0) { String poiType = poiList.get(0).getType(); PoiContract listOfQuestions = PoiTypes.getPoiType(poiType); listOfQuestions.shuffleQuestions(); if (preferences.getBooleanPreference(PreferenceList.LOGGED_IN_TO_OSM)) { view.setViewPager(poiList.get(0), listOfQuestions); if (poiList.size() == 1) { view.makeTextViewInvisible(); } else { view.setTextviewText(poiList.get(0).getName()); } } else { view.startNewActivity(); } } } QuestionsPresenter(QuestionsActivityContract.View view, SourceContract.Preferences preferences); @Override void addPoiNameToTextview(); @Override void assessIntentData(URI uri); @Override void savePoiList(); @Override void restorePoiList(); }### Answer:
@Test public void addPoiNameToTextViewTestSinglePoiInList() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(true); questionsPresenter.addPoiNameToTextview(); verify(view).makeTextViewInvisible(); }
@Test public void addPoiNameToTextViewTestMultiplePoiInList() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "Kitchen", "restaurant", 1, 1, 1)); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(true); questionsPresenter.addPoiNameToTextview(); verify(view).setTextviewText("Kitchen"); }
@Test public void addPoiNameToTextViewTestNotLoggedIn() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "Kitchen", "restaurant", 1, 1, 1)); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(false); questionsPresenter.addPoiNameToTextview(); verify(view).startNewActivity(); } |
### Question:
MigrationRouter { public List<MigrationPair> getMigrationPairOfPNode(int pNodeNo) { return allNodeMigrationPairs.get(pNodeNo); } MigrationRouter(int vNodes, int oldPNodeCount, int newPNodeCount); int getNewPNodeCount(); int getOldPNodeCount(); List<MigrationPair> getMigrationPairOfPNode(int pNodeNo); List<List<MigrationPair>> getAllNodeMigrationPairs(); }### Answer:
@Test public void testGetMigrationPairOfPNode() { MigrationRouter migrationRouter = new MigrationRouter(10000, 3, 4); System.out.println(migrationRouter.getMigrationPairOfPNode(0)); List<List<MigrationPair>> allNodeMigrationPairs = migrationRouter.getAllNodeMigrationPairs(); Assert.assertTrue( allNodeMigrationPairs.size() == 3); List<MigrationPair> pairs = allNodeMigrationPairs.get( 0 ); for (MigrationPair pair : pairs) { if(pair.getVnode() == 3) { Assert.assertEquals(0, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 9) { Assert.assertEquals(1, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 11) { Assert.assertEquals(2, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } } } |
### Question:
ConsistentReportServiceImpl implements ConsistentReportService { public List<ConsistentReportDO> queryConsistentReport(Map params) { return consistentReportDao.queryConsistentReport(params); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); }### Answer:
@Test public void testQueryConsistentReport() { } |
### Question:
PNode2VNodeMapping { public List<Integer> getVNodes(int pNode) { return vpmMapping.get( pNode ); } PNode2VNodeMapping(int vNodes, int pNodeCount); List<Integer> getVNodes(int pNode); int getPNodeCount(); List<List<Integer>> getVpmMapping(); }### Answer:
@Test public void testGetVNodes() { PNode2VNodeMapping mapping = new PNode2VNodeMapping(12, 3); System.out.println( "vNodes: of (12,3): " + mapping); List<Integer> vNodes = mapping.getVNodes(1); System.out.println( "vNodes: of (12,3:1): " + vNodes ); Assert.assertEquals(6, vNodes.get(0).intValue()); Assert.assertEquals(7, vNodes.get(1).intValue()); Assert.assertEquals(8, vNodes.get(2).intValue()); Assert.assertEquals(9, vNodes.get(3).intValue()); } |
### Question:
PropertiesLoadUtil { public static Properties loadProperties(String propLocation) { Properties properties = null; properties = loadAsFile(propLocation); if( properties != null) return properties; properties = loadAsResource(propLocation); return properties; } static Properties loadProperties(String propLocation); }### Answer:
@Test public void testProperty() { Properties properties = PropertiesLoadUtil.loadProperties("./test/test/test/testp.properties"); assertEquals("value1", properties.get("key1")); } |
### Question:
JavaObjectSerializer implements Serializer { public byte[] serialize(Object o, Object arg) { byte[] bvalue = null; if( o == null ) { bvalue = new byte[]{ Byte.valueOf( (byte) 0 )}; return bvalue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject( o ); bvalue = baos.toByteArray(); return bvalue; } catch (IOException e) { throw new RuntimeException("Fail to serialize object: " + o +", cause: " + e, e); }finally { try { baos.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); }### Answer:
@Test public void testSerializeNull() { Serializer serializer = new JavaObjectSerializer(); byte[] bvalue = serializer.serialize(null, null); char c = (char) Byte.valueOf( (byte)0 ).byteValue(); byte s = "0".getBytes()[0] ; System.out.println("asc 0: " + s +", c: " + c); }
@Test public void testSerialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); Assert.assertTrue("string serialize result", bvalue != null); } |
### Question:
JavaObjectSerializer implements Serializer { public Object deserialize(byte[] bvalue, Object deserializeTarget) { if( bvalue == null) return null; ByteArrayInputStream bais = new ByteArrayInputStream( bvalue ); try { ObjectInputStream ois = new ObjectInputStream(bais); Object obj = ois.readObject(); return obj; } catch (Exception e) { throw new RuntimeException("Fail to deserialize object, byte value:" + bvalue +", cause: " + e, e); }finally { try { bais.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); }### Answer:
@Test public void testDeserialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); String result = (String) serializer.deserialize(bvalue, null); Assert.assertEquals("string serialize result",stringObj, result); } |
### Question:
StorageManager { protected void loadStorage(StorageConfig config) { driver.init(config); storage = driver.createStorage(); } StorageManager(); Storage getStorage(); StorageType getStorageType(); void registStorage(Class<?> storageDriverClass); }### Answer:
@Test public void testLoadStorage() { StorageManager manager = new StorageManager(); } |
### Question:
MigrationVirtualNodeFinder { public String getTargetNodeOfVirtualNode(int vnode) { return index.get( vnode ); } MigrationVirtualNodeFinder(List<MigrationRoutePair> migrationRoutePairs); String getTargetNodeOfVirtualNode(int vnode); }### Answer:
@Test public void testGetTargetNodeOfVirtualNode() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); for (int i = 0; i < 1000 ; i++) { MigrationRoutePair pair = new MigrationRoutePair(); pair.setVnode( i ); pair.setTargetPhysicalId("127.0.0.1"); migrationRoutePairs.add( pair ); } MigrationVirtualNodeFinder finder = new MigrationVirtualNodeFinder(migrationRoutePairs); String targetNode1 = finder.getTargetNodeOfVirtualNode( 100 ); assertNotNull("targetNode1 found", targetNode1); String targetNode2 = finder.getTargetNodeOfVirtualNode( 1000 + 1 ); assertNull("targetNode2 not found ", targetNode2); } |
### Question:
ProgressComputer { public int getGrossProgress() { reentrantLock.lock(); try { return grossProgress; }finally { reentrantLock.unlock(); } } ProgressComputer(List<MigrationRoutePair> migrationRoutePairs); synchronized boolean completeOneVNode(String targetNodeId, Integer vnodeId); int getGrossProgress(); int getFinishCount(); int getProgressOfTarget(String tNodeId); }### Answer:
@Test public void testGetGrossProgress() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); int t = 1, v = 10000 ; for (int i = 0; i < t; i++) { for (int j = 0; j < v; j++) { MigrationRoutePair pair = new MigrationRoutePair(j , "t"+i ); migrationRoutePairs.add( pair ); } } ProgressComputer progressComputer = new ProgressComputer(migrationRoutePairs); int lastProgress = -1; for (int i = 0; i < v ; i++) { boolean need = progressComputer.completeOneVNode( "t0", 0); int progress = progressComputer.getGrossProgress(); lastProgress = progress; } assertEquals("Progress=100", 100,lastProgress); } |
### Question:
ConsistentReportServiceImpl implements ConsistentReportService { public Integer saveConsistentReport(ConsistentReportDO consistentReportDO) { return consistentReportDao.insert(consistentReportDO); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); }### Answer:
@Test public void testSaveConsistentReport() { } |
### Question:
BPMNParser extends AbstractXMLParser { public static BPMNProcess generateProcessFromXML(String filePath) { Document doc = readXMLDocument(filePath); return generateBPMNProcess(doc); } static BPMNProcess generateProcessFromXML(String filePath); }### Answer:
@Test public void testComplexProcess() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(complexfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 21); assertTrue(BPMNProcess.getStartEvent().getId().equals("sid-EC585815-8EAC-411C-89C2-553ACA85CF5A")); }
@Test public void testSubProcessImport() { BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(subProcessfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 7); assertTrue(BPMNProcess.hasSubProcesses()); BPMNSubProcess subProcess = BPMNProcess.getSubProcesses().get(0); assertNotNull(subProcess); assertFalse(subProcess.getStartEvent().getSuccessors().isEmpty()); } |
### Question:
XSDParser extends AbstractXMLParser { public static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName) throws XMLParsingException { Document doc = readXMLDocument(filePath); if (doc == null) { throw new XMLParsingException("could not read XSD: " + filePath); } return generateEventType(doc, eventTypeName); } static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName); static SushiEventType generateEventType(Document doc, String schemaName); }### Answer:
@Test public void testXSDParsing() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ SushiEventType eventType = null; try { eventType = XSDParser.generateEventTypeFromXSD(filePath, "EventTaxonomy"); } catch (XMLParsingException e) { fail(); } assertNotNull(eventType); } |
### Question:
XMLParser extends AbstractXMLParser { public static SushiEvent generateEventFromXML(String filePath) throws XMLParsingException { Document doc = readXMLDocument(filePath); return generateEvent(doc, null); } static SushiEvent generateEventFromXML(String filePath); static SushiEvent generateEventFromXML(String filePath, String pathToXSD); static SushiEvent generateEventFromDoc(Document xmlDoc); static Node getFirstChildWithNameFromNode(String name, Node parentNode); static Node getLastChildWithNameFromNode(String name, Node parentNode); static List<Node> getAllChildWithNameFromNode(String name, Node parentNode); }### Answer:
@Test public void testXMLParsing() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, XMLParsingException{ SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePath); assertNotNull(event); }
@Test public void testHierarchicalTimestampParsing() throws XMLParsingException { SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("location.timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePathToXMLWithHierarchicalTimestamp); assertNotNull(event); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2013, 11, 25, 20, 25, 00); assertTrue("Should be " + cal.getTime() + " but was " + event.getTimestamp(), event.getTimestamp().equals(cal.getTime())); }
@Test public void testNonHierarchicalTimestampParsing() throws XMLParsingException { SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePathToXMLWithHierarchicalTimestamp); assertNotNull(event); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2013, 11, 24, 20, 25, 00); assertTrue("Should be " + cal.getTime() + " but was " + event.getTimestamp(), event.getTimestamp().equals(cal.getTime())); } |
### Question:
BPM2XMLToSignavioXMLConverter extends AbstractXMLParser { public String generateSignavioXMLFromBPM2XML(){ SignavioBPMNProcess process = parseBPM2XML(); File file = new File(pathToCoreComponentsFolder + fileNameWithoutExtenxions + ".signavio.xml"); try { FileWriter writer = new FileWriter(file ,false); writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writer.write(System.getProperty("line.separator")); writer.write("<oryxmodel>"); writer.write(System.getProperty("line.separator")); writer.write("<description></description>"); writer.write(System.getProperty("line.separator")); writer.write("<type>BPMN 2.0</type>"); writer.write(System.getProperty("line.separator")); writer.write("<json-representation><![CDATA["); writer.write(process.generateSignavioXMLString()); writer.write("]]></json-representation>"); writer.write(System.getProperty("line.separator")); writer.write("</oryxmodel>"); writer.flush(); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } return file.getName(); } BPM2XMLToSignavioXMLConverter(String bpm2FilePath); String generateSignavioXMLFromBPM2XML(); SignavioBPMNProcess parseBPM2XML(); }### Answer:
@Test public void testConversion(){ BPM2XMLToSignavioXMLConverter converter = new BPM2XMLToSignavioXMLConverter(emptyBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(startEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(taskBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(endEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(edgeBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(simpleBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(testBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(startMessageEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(multipleStartEventsBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(xorBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(andBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(complexBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); } |
### Question:
BPM2XMLToSignavioXMLConverter extends AbstractXMLParser { public SignavioBPMNProcess parseBPM2XML() { Document doc = readXMLDocument(bpm2FilePath); process = new SignavioBPMNProcess(); Node definitionNode = getDefinitionsElementFromBPM(doc); if(definitionNode != null){ process.addPropertyValue("targetnamespace", definitionNode.getAttributes().getNamedItem("targetNamespace").getNodeValue()); process.addPropertyValue("expressionlanguage", definitionNode.getAttributes().getNamedItem("expressionLanguage").getNodeValue()); process.addPropertyValue("typelanguage", definitionNode.getAttributes().getNamedItem("typeLanguage").getNodeValue()); } NodeList processChilds = getProcessElementsFromBPM(doc); for(int i = 0; i < processChilds.getLength(); i++){ process.addChildShape(getProcessChildFromXML(processChilds.item(i), doc)); } return process; } BPM2XMLToSignavioXMLConverter(String bpm2FilePath); String generateSignavioXMLFromBPM2XML(); SignavioBPMNProcess parseBPM2XML(); }### Answer:
@Test public void testParsing(){ BPM2XMLToSignavioXMLConverter converter = new BPM2XMLToSignavioXMLConverter(emptyBpmn2FilePath); converter.parseBPM2XML(); } |
### Question:
AbstractClient { protected static void init() { keywordSet.add("-" + HOST_ARGS); keywordSet.add("-" + HELP_ARGS); keywordSet.add("-" + PORT_ARGS); keywordSet.add("-" + PASSWORD_ARGS); keywordSet.add("-" + USERNAME_ARGS); keywordSet.add("-" + ISO8601_ARGS); keywordSet.add("-" + MAX_PRINT_ROW_COUNT_ARGS); } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); }### Answer:
@Test public void testInit() { AbstractClient.init(); String[] keywords = {AbstractClient.HOST_ARGS, AbstractClient.HELP_ARGS, AbstractClient.PORT_ARGS, AbstractClient.PASSWORD_ARGS, AbstractClient.USERNAME_ARGS, AbstractClient.ISO8601_ARGS, AbstractClient.MAX_PRINT_ROW_COUNT_ARGS,}; for (String keyword : keywords) { if (!AbstractClient.keywordSet.contains("-" + keyword)) { System.out.println(keyword); fail(); } } } |
### Question:
Pair { @Override public String toString() { return "<" + left + "," + right + ">"; } Pair(L l, R r); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); public L left; public R right; }### Answer:
@Test public void testToString() { Pair<String, Integer> p1 = new Pair<String, Integer>("a", 123123); assertEquals("<a,123123>", p1.toString()); Pair<Float, Double> p2 = new Pair<Float, Double>(32.5f, 123.123d); assertEquals("<32.5,123.123>", p2.toString()); } |
### Question:
BytesUtils { public static byte[] intToBytes(int i) { return new byte[]{(byte) ((i >> 24) & 0xFF), (byte) ((i >> 16) & 0xFF), (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testIntToBytes() { int b = 123; byte[] bb = BytesUtils.intToBytes(b); int bf = BytesUtils.bytesToInt(bb); assertEquals("testBytesToFloat", b, bf); } |
### Question:
BytesUtils { public static byte[] floatToBytes(float x) { byte[] b = new byte[4]; int l = Float.floatToIntBits(x); for (int i = 3; i >= 0; i--) { b[i] = new Integer(l).byteValue(); l = l >> 8; } return b; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testFloatToBytes() throws Exception { float b = 25.0f; byte[] bb = BytesUtils.floatToBytes(b); float bf = BytesUtils.bytesToFloat(bb); assertEquals("testBytesToFloat", b, bf, CommonTestConstant.float_min_delta); } |
### Question:
BytesUtils { public static byte[] boolToBytes(boolean x) { byte[] b = new byte[1]; if (x) { b[0] = 1; } else { b[0] = 0; } return b; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testBoolToBytes() throws Exception { boolean b = true; byte[] bb = BytesUtils.boolToBytes(b); boolean bf = BytesUtils.bytesToBool(bb); assertEquals("testBoolToBytes", b, bf); } |
### Question:
BytesUtils { public static byte[] longToBytes(long num) { return longToBytes(num, 8); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testlongToBytes() { long lNum = 32143422454243342L; long iNum = 1032423424L; long lSNum = 10; assertEquals(lNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(lNum, 8), 8)); assertEquals(iNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(iNum, 8), 8)); assertEquals(iNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(iNum, 4), 4)); assertEquals(lSNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(lSNum, 1), 1)); } |
### Question:
BytesUtils { public static long readLong(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(8, in); return BytesUtils.bytesToLong(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void readLongTest() throws IOException { long l = 32143422454243342L; byte[] bs = BytesUtils.longToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readLong(in)); }
@Test public void testReadLong() throws IOException { long l = r.nextLong(); byte[] bs = BytesUtils.longToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readLong(in)); } |
### Question:
BytesUtils { public static byte[] doubleToBytes(double data) { byte[] bytes = new byte[8]; long value = Double.doubleToLongBits(data); for (int i = 7; i >= 0; i--) { bytes[i] = new Long(value).byteValue(); value = value >> 8; } return bytes; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testDoubleToBytes() { double b1 = 2745687.1253123d; byte[] ret = BytesUtils.doubleToBytes(b1); double rb1 = BytesUtils.bytesToDouble(ret); assertEquals(b1, rb1, CommonTestConstant.float_min_delta); } |
### Question:
BytesUtils { public static byte[] stringToBytes(String str) { try { return str.getBytes(TSFileConfig.STRING_ENCODING); } catch (UnsupportedEncodingException e) { LOG.error("catch UnsupportedEncodingException {}", str, e); return null; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testStringToBytes() { String b = "lqfkgv12KLDJSL1@#%"; byte[] ret = BytesUtils.stringToBytes(b); String rb1 = BytesUtils.bytesToString(ret); assertTrue(b.equals(rb1)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.