method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getExecutableReturnValue() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError(ResourceRegistry resourceRegistry, ErrorData error, QueryContext queryContext); ErrorData getErrorData(); Serializable getResourceId(); @Override Object getRootBean(); @Override Object getLeafBean(); @Override Object getInvalidValue(); @Override Object[] getExecutableParameters(); @Override Object getExecutableReturnValue(); @Override String getMessage(); @Override ConstraintDescriptor<?> getConstraintDescriptor(); @Override String getMessageTemplate(); @Override Path getPropertyPath(); @SuppressWarnings({"rawtypes", "unchecked"}) @Override Class getRootBeanClass(); @Override U unwrap(Class<U> arg0); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getExecutableReturnValue() { violation.getExecutableReturnValue(); }
|
### Question:
SecurityModule implements Module { public ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass) { String resourceType = toType(resourceClass); return getResourcePermission(queryContext, resourceType); } protected SecurityModule(); protected SecurityModule(SecurityConfig config); DataRoomMatcher getDataRoomMatcher(); static SecurityModule newServerModule(SecurityConfig config); static SecurityModule newClientModule(); void setEnabled(final boolean enabled); boolean isEnabled(); void setEnabled(Supplier<Boolean> enabled); @Override String getModuleName(); void reconfigure(SecurityConfig config); SecurityConfig getConfig(); @Override void setupModule(ModuleContext context); boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission); boolean isAllowed(QueryContext queryContext, String resourceType, ResourcePermission permission); ResourcePermission getCallerPermissions(QueryContext queryContext, String resourceType); ResourcePermission getRolePermissions(QueryContext queryContext, String resourceType, String checkedRole); ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass); ResourcePermission getResourcePermission(QueryContext queryContext, String resourceType); boolean isUserInRole(QueryContext queryContext, String role); SecurityProvider getCallerSecurityProvider(); }### Answer:
@Test public void testBlackListingOfUnknownResources() { QueryContext queryContext = Mockito.mock(QueryContext.class); Assert.assertEquals(ResourcePermission.EMPTY, securityModule.getResourcePermission(queryContext, "doesNotExist")); }
|
### Question:
ReadOnlyResourceRepositoryBase extends ResourceRepositoryBase<T, I> { @Override public final <S extends T> S save(S resource) { throw new MethodNotAllowedException("method not allowed"); } protected ReadOnlyResourceRepositoryBase(Class<T> resourceClass); @Override final S save(S resource); @Override final S create(S resource); @Override final void delete(I id); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void save() { repo.save(null); }
|
### Question:
ReadOnlyResourceRepositoryBase extends ResourceRepositoryBase<T, I> { @Override public final <S extends T> S create(S resource) { throw new MethodNotAllowedException("method not allowed"); } protected ReadOnlyResourceRepositoryBase(Class<T> resourceClass); @Override final S save(S resource); @Override final S create(S resource); @Override final void delete(I id); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void create() { repo.create(null); }
|
### Question:
ReadOnlyResourceRepositoryBase extends ResourceRepositoryBase<T, I> { @Override public final void delete(I id) { throw new MethodNotAllowedException("method not allowed"); } protected ReadOnlyResourceRepositoryBase(Class<T> resourceClass); @Override final S save(S resource); @Override final S create(S resource); @Override final void delete(I id); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void delete() { repo.delete(null); }
|
### Question:
InMemoryResourceRepository extends ResourceRepositoryBase<T, I> { @Override public ResourceList<T> findAll(QuerySpec querySpec) { return querySpec.apply(resources.values()); } InMemoryResourceRepository(Class<T> resourceClass); Map<I, T> getMap(); void clear(); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S save(S entity); @Override void delete(I id); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); }### Answer:
@Test public void testStandaloneUse() { Task task = new Task(); task.setId(131L); InMemoryResourceRepository<Task, String> repository = new InMemoryResourceRepository<>(Task.class); repository.create(task); ResourceList<Task> list = repository.findAll(new QuerySpec(Task.class)); Assert.assertEquals(list.size(), 1); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public Class<S> getSourceResourceClass() { throw new UnsupportedOperationException("implement getMatcher() or this method"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getSourceResourceClass() { repo.getSourceResourceClass(); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public Class<T> getTargetResourceClass() { throw new UnsupportedOperationException("implement getMatcher() or this method"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getTargetResourceClass() { repo.getTargetResourceClass(); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void findOneTarget() { repo.findOneTarget(null, null, null); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void findManyTargets() { repo.findManyTargets(null, null, null); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public void setRelation(S source, J targetId, String fieldName) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void setRelation() { repo.setRelation(null, null, null); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public void setRelations(S source, Collection<J> targetIds, String fieldName) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void setRelations() { repo.setRelations(null, null, null); }
|
### Question:
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public <U> U unwrap(Class<U> arg0) { return null; } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError(ResourceRegistry resourceRegistry, ErrorData error, QueryContext queryContext); ErrorData getErrorData(); Serializable getResourceId(); @Override Object getRootBean(); @Override Object getLeafBean(); @Override Object getInvalidValue(); @Override Object[] getExecutableParameters(); @Override Object getExecutableReturnValue(); @Override String getMessage(); @Override ConstraintDescriptor<?> getConstraintDescriptor(); @Override String getMessageTemplate(); @Override Path getPropertyPath(); @SuppressWarnings({"rawtypes", "unchecked"}) @Override Class getRootBeanClass(); @Override U unwrap(Class<U> arg0); }### Answer:
@Test public void unwrap() { Assert.assertNull(violation.unwrap(String.class)); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public void addRelations(S source, Collection<J> targetIds, String fieldName) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void addRelations() { repo.addRelations(null, null, null); }
|
### Question:
ReadOnlyRelationshipRepositoryBase implements RelationshipRepository<S, I, T, J> { @Override public void removeRelations(S source, Collection<J> targetIds, String fieldName) { throw new MethodNotAllowedException("method not allowed"); } @Override Class<S> getSourceResourceClass(); @Override Class<T> getTargetResourceClass(); @Override T findOneTarget(I sourceId, String fieldName, QuerySpec querySpec); @Override ResourceList<T> findManyTargets(I sourceId, String fieldName, QuerySpec querySpec); @Override void setRelation(S source, J targetId, String fieldName); @Override void setRelations(S source, Collection<J> targetIds, String fieldName); @Override void addRelations(S source, Collection<J> targetIds, String fieldName); @Override void removeRelations(S source, Collection<J> targetIds, String fieldName); }### Answer:
@Test(expected = MethodNotAllowedException.class) public void removeRelations() { repo.removeRelations(null, null, null); }
|
### Question:
RelationshipMatcher { public boolean matches(ResourceField field) { return rules.stream().filter(it -> it.matches(field)).findAny().isPresent(); } RelationshipMatcherRule rule(); boolean matches(ResourceField field); }### Answer:
@Test public void checkEmpty() { Assert.assertFalse(new RelationshipMatcher().matches(field)); }
|
### Question:
Relationship implements MetaContainer, LinksContainer { public void setData(Nullable<Object> data) { PreconditionUtil.verify(data != null, "make use of Nullable, null not allowed"); if (data.isPresent()) { Object value = data.get(); if (value instanceof Collection) { Collection<?> col = (Collection<?>) value; if (!col.isEmpty()) { Object object = col.iterator().next(); PreconditionUtil.verify(object instanceof ResourceIdentifier, "relationship data must be an instanceof of ResourceIdentifier, got %s", object); PreconditionUtil.verify(!(object instanceof Resource), "relationship data cannot be a Resource, must be a ResourceIdentifier"); } } else { PreconditionUtil.verify(value == null || value instanceof ResourceIdentifier, "value must be a ResourceIdentifier, null or collection, got %s", value); } } this.data = data; } Relationship(); Relationship(ResourceIdentifier resourceId); Relationship(List<ResourceIdentifier> resourceIds); @Override ObjectNode getMeta(); @Override void setMeta(ObjectNode meta); Nullable<Object> getData(); void setData(Nullable<Object> data); @Override ObjectNode getLinks(); @Override void setLinks(ObjectNode links); @JsonIgnore Nullable<ResourceIdentifier> getSingleData(); @JsonIgnore Nullable<List<ResourceIdentifier>> getCollectionData(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void serializeArray() throws IOException { Relationship relationship = new Relationship(); relationship.setData(Nullable.of(Arrays.asList(new ResourceIdentifier("a", "b")))); checkSerialize(relationship); }
@Test public void serializeSingleData() throws IOException { Relationship relationship = new Relationship(); relationship.setData(Nullable.of(new ResourceIdentifier("a", "b"))); checkSerialize(relationship); }
@Test public void serializeNull() throws IOException { Relationship relationship = new Relationship(); relationship.setData(Nullable.nullValue()); checkSerialize(relationship); }
@Test(expected = IllegalStateException.class) public void setInvalidDataThrowsException() { Relationship relationship = new Relationship(); relationship.setData(Nullable.of("not a ResourceIdentifier")); }
|
### Question:
Document implements MetaContainer, LinksContainer { @JsonIgnore public Nullable<List<Resource>> getCollectionData() { if (!data.isPresent()) { return Nullable.empty(); } Object value = data.get(); if (value == null) { return Nullable.of((List<Resource>) (List) Collections.emptyList()); } if (!(value instanceof Iterable)) { return Nullable.of((Collections.singletonList((Resource) value))); } return Nullable.of((List<Resource>) value); } Nullable<Object> getData(); void setData(Nullable<Object> data); @Override ObjectNode getLinks(); @Override void setLinks(ObjectNode links); List<Resource> getIncluded(); void setIncluded(List<Resource> includes); @Override ObjectNode getMeta(); @Override void setMeta(ObjectNode meta); List<ErrorData> getErrors(); void setErrors(List<ErrorData> errors); @JsonIgnore boolean isMultiple(); @JsonIgnore Nullable<Resource> getSingleData(); @Override int hashCode(); @Override boolean equals(Object obj); @JsonIgnore Nullable<List<Resource>> getCollectionData(); ObjectNode getJsonapi(); void setJsonapi(ObjectNode jsonapi); }### Answer:
@Test public void getCollectionData() { Document doc = new Document(); Assert.assertFalse(doc.getCollectionData().isPresent()); doc.setData(Nullable.nullValue()); Assert.assertTrue(doc.getCollectionData().get().isEmpty()); Resource resource1 = Mockito.mock(Resource.class); doc.setData(Nullable.of(resource1)); Assert.assertEquals(1, doc.getCollectionData().get().size()); Resource resource2 = Mockito.mock(Resource.class); doc.setData(Nullable.of(Arrays.asList(resource1, resource2))); Assert.assertEquals(2, doc.getCollectionData().get().size()); }
|
### Question:
ImmediateResult implements Result<T> { @Override public T get() { return object; } ImmediateResult(T object); @Override T get(); @Override Result<D> map(Function<T, D> function); @Override Result<T> onErrorResume(Function<? super Throwable, T> function); @Override void subscribe(Consumer<T> consumer, Consumer<? super Throwable> exceptionConsumer); @Override Result<T> doWork(Consumer<T> function); @Override Result<R> zipWith(Result<D> other, BiFunction<T, D, R> function); @Override Result<R> merge(Function<T, Result<R>> other); @Override Result<T> setTimeout(Duration timeout); }### Answer:
@Test public void checkContextAccess() throws ExecutionException, InterruptedException { Object context = new Object(); Assert.assertFalse(resultFactory.hasThreadContext()); resultFactory.setThreadContext(context); Assert.assertSame(context, resultFactory.getThreadContext()); Assert.assertTrue(resultFactory.hasThreadContext()); ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future<?> future = executorService.submit(new Runnable() { @Override public void run() { Assert.assertFalse(resultFactory.hasThreadContext()); } }); future.get(); Assert.assertFalse(resultFactory.isAsync()); } finally { executorService.shutdownNow(); } }
|
### Question:
ImmediateResult implements Result<T> { @Override public void subscribe(Consumer<T> consumer, Consumer<? super Throwable> exceptionConsumer) { throw new UnsupportedOperationException("only available for async implementations"); } ImmediateResult(T object); @Override T get(); @Override Result<D> map(Function<T, D> function); @Override Result<T> onErrorResume(Function<? super Throwable, T> function); @Override void subscribe(Consumer<T> consumer, Consumer<? super Throwable> exceptionConsumer); @Override Result<T> doWork(Consumer<T> function); @Override Result<R> zipWith(Result<D> other, BiFunction<T, D, R> function); @Override Result<R> merge(Function<T, Result<R>> other); @Override Result<T> setTimeout(Duration timeout); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void subscribeNotSupported() { Result<Object> result = resultFactory.just(new Object()); result.subscribe(null, null); }
|
### Question:
ImmediateResult implements Result<T> { @Override public Result<T> onErrorResume(Function<? super Throwable, T> function) { throw new UnsupportedOperationException("only available for async implementations"); } ImmediateResult(T object); @Override T get(); @Override Result<D> map(Function<T, D> function); @Override Result<T> onErrorResume(Function<? super Throwable, T> function); @Override void subscribe(Consumer<T> consumer, Consumer<? super Throwable> exceptionConsumer); @Override Result<T> doWork(Consumer<T> function); @Override Result<R> zipWith(Result<D> other, BiFunction<T, D, R> function); @Override Result<R> merge(Function<T, Result<R>> other); @Override Result<T> setTimeout(Duration timeout); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void onErrorResumeNotSupported() { Result<Object> result = resultFactory.just(new Object()); result.onErrorResume(null); }
|
### Question:
AbstractDocumentFilter implements DocumentFilter { @Override public Response filter(DocumentFilterContext context, DocumentFilterChain chain) { return chain.doFilter(context); } @Override Response filter(DocumentFilterContext context, DocumentFilterChain chain); }### Answer:
@Test public void test() { DocumentFilterContext context = Mockito.mock(DocumentFilterContext.class); DocumentFilterChain chain = Mockito.mock(DocumentFilterChain.class); AbstractDocumentFilter filter = new AbstractDocumentFilter(); filter.filter(context, chain); Mockito.verify(chain, Mockito.times(1)).doFilter(Mockito.eq(context)); }
|
### Question:
DefaultResourceRegistryPart extends ResourceRegistryPartBase { @Override public RegistryEntry addEntry(RegistryEntry entry) { ResourceInformation resourceInformation = entry.getResourceInformation(); Type implementationType = resourceInformation.getImplementationType(); String resourceType = resourceInformation.getResourceType(); String resourcePath = resourceInformation.getResourcePath(); PreconditionUtil.verify(resourceType != null, "no resourceType set for entry %s", entry); PreconditionUtil .verify(!resourcesByType.containsKey(resourceType), "resourceType '%s' already exists, cannot add entry %s", resourceType, entry); if (entry.hasResourceRepository()) { PreconditionUtil .verify(!resourcesByPath.containsKey(resourcePath), "resourceType '%s' already exists, cannot add entry %s", resourcePath, entry); resourcesByPath.put(resourcePath != null ? resourcePath : resourceType, entry); } resourcesByImplementationType.put(implementationType, entry); resourcesByType.put(resourceType, entry); latestVersion = Math.max(latestVersion, ignoreUnbounded(resourceInformation.getVersionRange().getMax())); for (ResourceField field : resourceInformation.getFields()) { latestVersion = Math.max(latestVersion, ignoreUnbounded(field.getVersionRange().getMax())); } logger.debug("Added resource '{}' to ResourceRegistry", resourceType); notifyChange(); return entry; } DefaultResourceRegistryPart(); @Override RegistryEntry addEntry(RegistryEntry entry); @Override boolean hasEntry(Class<?> implementationClass); @Override boolean hasEntry(Type implementationType); @Override boolean hasEntry(String resourceType); @Override RegistryEntry getEntry(Class<?> implementationClass); @Override RegistryEntry getEntry(Type implementationType); Set<RegistryEntry> getEntries(); RegistryEntry getEntry(String resourceType); RegistryEntry getEntryByPath(String resourcePath); @Override int getLatestVersion(); }### Answer:
@Test public void checkListenerEvent() { ResourceRegistryPartListener listener = Mockito.mock(ResourceRegistryPartListener.class); part.addListener(listener); part.addEntry(entry); ArgumentCaptor<ResourceRegistryPartEvent> eventCaptor = ArgumentCaptor.forClass(ResourceRegistryPartEvent.class); Mockito.verify(listener, Mockito.times(1)).onChanged(eventCaptor.capture()); }
@Test public void checkAddRemoveListeners() { ResourceRegistryPartListener listener = Mockito.mock(ResourceRegistryPartListener.class); part.addListener(listener); part.addEntry(entry); part.removeListener(listener); part.addEntry(entry2); Mockito.verify(listener, Mockito.times(1)).onChanged(Mockito.any(ResourceRegistryPartEvent.class)); part.addListener(listener); part.addEntry(entry3); Mockito.verify(listener, Mockito.times(2)).onChanged(Mockito.any(ResourceRegistryPartEvent.class)); }
|
### Question:
HierarchicalResourceRegistryPart extends ResourceRegistryPartBase { public void putPart(String prefix, ResourceRegistryPart part) { if (partMap.containsKey(prefix)) { throw new IllegalStateException("part with prefx " + prefix + " already exists"); } partMap.put(prefix, part); partList.add(part); part.addListener(childListener); } void putPart(String prefix, ResourceRegistryPart part); @Override RegistryEntry addEntry(RegistryEntry entry); @Override boolean hasEntry(Class<?> implementationClass); @Override boolean hasEntry(Type implementationType); @Override boolean hasEntry(String resourceType); @Override RegistryEntry getEntry(String resourceType); @Override RegistryEntry getEntryByPath(String resourcePath); @Override int getLatestVersion(); @Override Collection<RegistryEntry> getEntries(); @Override RegistryEntry getEntry(Class<?> implementationClass); @Override RegistryEntry getEntry(Type implementationType); }### Answer:
@Test(expected = IllegalStateException.class) public void testDuplicatePartThrowsException() { HierarchicalResourceRegistryPart part = new HierarchicalResourceRegistryPart(); part.putPart("", new DefaultResourceRegistryPart()); part.putPart("", new DefaultResourceRegistryPart()); }
|
### Question:
ExceptionMapperRegistry { int getDistanceBetweenExceptions(Class<?> clazz, Class<?> mapperTypeClazz) { int distance = 0; Class<?> superClazz = clazz; if (!mapperTypeClazz.isAssignableFrom(clazz)) { return Integer.MAX_VALUE; } while (superClazz != mapperTypeClazz) { superClazz = superClazz.getSuperclass(); distance++; } return distance; } ExceptionMapperRegistry(List<ExceptionMapperType> exceptionMappers); Optional<ExceptionMapper> findMapperFor(Class<? extends Throwable> exceptionClass); @SuppressWarnings({"rawtypes", "unchecked"}) Optional<ExceptionMapper<E>> findMapperFor(ErrorResponse errorResponse); Response toResponse(Throwable e); Response toErrorResponse(Throwable e); }### Answer:
@Test public void shouldReturnIntegerMAXForNotRelatedClassesFromException() { int distance = exceptionMapperRegistry.getDistanceBetweenExceptions(Exception.class, SomeException.class); assertThat(distance).isEqualTo(Integer.MAX_VALUE); }
@Test public void shouldReturn0DistanceBetweenSameClassFromException() { int distance = exceptionMapperRegistry.getDistanceBetweenExceptions(Exception.class, Exception.class); assertThat(distance).isEqualTo(0); }
@Test public void shouldReturn1AsADistanceBetweenSameClassFromException() { int distance = exceptionMapperRegistry.getDistanceBetweenExceptions(SomeException.class, Exception.class); assertThat(distance).isEqualTo(1); }
|
### Question:
ExceptionMapperRegistry { public Optional<ExceptionMapper> findMapperFor(Class<? extends Throwable> exceptionClass) { int currentDistance = Integer.MAX_VALUE; ExceptionMapper closestExceptionMapper = null; for (ExceptionMapperType mapperType : exceptionMappers) { int tempDistance = getDistanceBetweenExceptions(exceptionClass, mapperType.getExceptionClass()); if (tempDistance < currentDistance) { currentDistance = tempDistance; closestExceptionMapper = mapperType.getExceptionMapper(); if (currentDistance == 0) { break; } } } return Optional.ofNullable(closestExceptionMapper); } ExceptionMapperRegistry(List<ExceptionMapperType> exceptionMappers); Optional<ExceptionMapper> findMapperFor(Class<? extends Throwable> exceptionClass); @SuppressWarnings({"rawtypes", "unchecked"}) Optional<ExceptionMapper<E>> findMapperFor(ErrorResponse errorResponse); Response toResponse(Throwable e); Response toErrorResponse(Throwable e); }### Answer:
@Test public void shouldNotFindMapperIfSuperClassIsNotMappedFromException() { Optional<ExceptionMapper> mapper = exceptionMapperRegistry.findMapperFor(RuntimeException.class); assertThat(mapper.isPresent()).isFalse(); }
@Test public void shouldFindDirectExceptionMapperFromException() { Optional<ExceptionMapper> mapper = exceptionMapperRegistry.findMapperFor(IllegalStateException.class); assertThat(mapper.isPresent()).isTrue(); assertThat(mapper.get()).isExactlyInstanceOf(IllegalStateExceptionMapper.class); }
@Test public void shouldFindDescendantExceptionMapperFromException() { Optional<ExceptionMapper> mapper = exceptionMapperRegistry.findMapperFor(ClosedFileSystemException.class); assertThat(mapper.isPresent()).isTrue(); assertThat(mapper.get()).isExactlyInstanceOf(IllegalStateExceptionMapper.class); }
@Test public void shouldFindDirectExceptionMapperFromError() { ErrorResponse response = ErrorResponse.builder().setStatus(HttpStatus.BAD_REQUEST_400).build(); Optional<ExceptionMapper<?>> mapper = (Optional) exceptionMapperRegistry.findMapperFor(response); assertThat(mapper.isPresent()).isTrue(); assertThat(mapper.get()).isExactlyInstanceOf(IllegalStateExceptionMapper.class); Throwable throwable = mapper.get().fromErrorResponse(response); assertThat(throwable).isExactlyInstanceOf(IllegalStateException.class); }
@Test public void shouldFindDescendantExceptionMapperFromError() { ErrorData errorData = ErrorData.builder().setId("someId").build(); ErrorResponse response = ErrorResponse.builder().setStatus(HttpStatus.BAD_REQUEST_400).setSingleErrorData(errorData).build(); Optional<ExceptionMapper<?>> mapper = (Optional) exceptionMapperRegistry.findMapperFor(response); assertThat(mapper.isPresent()).isTrue(); assertThat(mapper.get()).isExactlyInstanceOf(SomeIllegalStateExceptionMapper.class); Throwable throwable = mapper.get().fromErrorResponse(response); assertThat(throwable).isExactlyInstanceOf(SomeIllegalStateException.class); }
@Test public void shouldNotFindDescendantExceptionMapperFromError() { ErrorData errorData = ErrorData.builder().setId("someOtherId").build(); ErrorResponse response = ErrorResponse.builder().setStatus(HttpStatus.BAD_REQUEST_400).setSingleErrorData(errorData).build(); Optional<ExceptionMapper<?>> mapper = (Optional) exceptionMapperRegistry.findMapperFor(response); assertThat(mapper.isPresent()).isTrue(); assertThat(mapper.get()).isExactlyInstanceOf(IllegalStateExceptionMapper.class); }
|
### Question:
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public ConstraintDescriptor<?> getConstraintDescriptor() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError(ResourceRegistry resourceRegistry, ErrorData error, QueryContext queryContext); ErrorData getErrorData(); Serializable getResourceId(); @Override Object getRootBean(); @Override Object getLeafBean(); @Override Object getInvalidValue(); @Override Object[] getExecutableParameters(); @Override Object getExecutableReturnValue(); @Override String getMessage(); @Override ConstraintDescriptor<?> getConstraintDescriptor(); @Override String getMessageTemplate(); @Override Path getPropertyPath(); @SuppressWarnings({"rawtypes", "unchecked"}) @Override Class getRootBeanClass(); @Override U unwrap(Class<U> arg0); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void getConstraintDescriptor() { violation.getConstraintDescriptor(); }
|
### Question:
ExceptionMapperType implements Prioritizable { @Override public String toString() { return "ExceptionMapperType[" + "exceptionClass=" + exceptionClass.getName() + ", exceptionMapper=" + exceptionMapper + ']'; } ExceptionMapperType(Class<? extends Throwable> exceptionClass, ExceptionMapper exceptionMapper); Class<? extends Throwable> getExceptionClass(); ExceptionMapper getExceptionMapper(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override int getPriority(); }### Answer:
@Test public void checkToString() { ExceptionMapper mapper = Mockito.mock(ExceptionMapper.class); Mockito.when(mapper.toString()).thenReturn("customMapper"); ExceptionMapperType type = new ExceptionMapperType(IllegalStateException.class, mapper); Assert.assertEquals("ExceptionMapperType[exceptionClass=java.lang.IllegalStateException, exceptionMapper=customMapper]", type.toString()); }
|
### Question:
ValidationClientModuleFactory implements ClientModuleFactory { @Override public ValidationModule create() { return ValidationModule.create(); } @Override ValidationModule create(); }### Answer:
@Test public void test() { ServiceLoader<ClientModuleFactory> loader = ServiceLoader.load(ClientModuleFactory.class); Iterator<ClientModuleFactory> iterator = loader.iterator(); Set<Class> moduleClasses = new HashSet<>(); while (iterator.hasNext()) { ClientModuleFactory moduleFactory = iterator.next(); Module module = moduleFactory.create(); moduleClasses.add(module.getClass()); } Assert.assertEquals(2, moduleClasses.size()); Assert.assertTrue(moduleClasses.contains(ValidationModule.class)); Assert.assertTrue(moduleClasses.contains(MetaModule.class)); }
|
### Question:
HomeModuleExtension implements ModuleExtension { public void addPath(String path) { paths.add(path); } @Override Class<? extends Module> getTargetModule(); @Override boolean isOptional(); void addPath(String path); }### Answer:
@Test public void test() { HomeModuleExtension extension = new HomeModuleExtension(); extension.addPath("/test/directory/"); extension.addPath("/test/something"); SimpleModule extensionModule = new SimpleModule("extension"); extensionModule.addExtension(extension); HomeModule module = Mockito.spy(HomeModule.create(HomeFormat.JSON_HOME)); CrnkBoot boot = new CrnkBoot(); boot.addModule(module); boot.addModule(extensionModule); boot.setServiceUrlProvider(new ConstantServiceUrlProvider("http: boot.boot(); List<String> list = module.list("/", new QueryContext()); Assert.assertTrue(list.toString(), list.contains("test/")); list = module.list("/test/", new QueryContext()); Assert.assertTrue(list.toString(), list.contains("directory/")); Assert.assertTrue(list.toString(), list.contains("something")); }
|
### Question:
HomeModule implements Module, ModuleExtensionAware<HomeModuleExtension> { protected HttpRequestProcessor getRequestProcessor() { return requestProcessor; } protected HomeModule(); static HomeModule create(); static HomeModule create(HomeFormat defaultFormat); void addPathFilter(Predicate<HttpRequestContext> pathFilter); @Override String getModuleName(); @Override void setupModule(final ModuleContext context); List<String> list(String requestPath, QueryContext queryContext); boolean hasPotentialFilterIssues(); @Override void setExtensions(List<HomeModuleExtension> extensions); @Override void init(); static final String JSON_HOME_CONTENT_TYPE; static final String JSON_CONTENT_TYPE; }### Answer:
@Test public void checkAccepts() { HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class); Mockito.when(context.getMethod()).thenReturn("GET"); Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE); HttpRequestProcessor requestProcessor = module.getRequestProcessor(); HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context); Mockito.when(context.getPath()).thenReturn("/"); Assert.assertTrue(requestProcessor.accepts(contextAdapter)); Mockito.when(context.getPath()).thenReturn("/doesNotExists"); Assert.assertFalse(requestProcessor.accepts(contextAdapter)); Mockito.when(context.getPath()).thenReturn("/tasks"); Assert.assertFalse(requestProcessor.accepts(contextAdapter)); }
|
### Question:
DocumentMapperUtil { public ResourceIdentifier toResourceId(Object entity) { if (entity == null) { return null; } RegistryEntry entry = resourceRegistry.findEntry(entity); ResourceInformation resourceInformation = entry.getResourceInformation(); return resourceInformation.toResourceIdentifier(entity); } DocumentMapperUtil(ResourceRegistry resourceRegistry, ObjectMapper objectMapper,
PropertiesProvider propertiesProvider, UrlBuilder urlBuilder); @SuppressWarnings({ "unchecked", "rawtypes" }) static List<T> toList(Object entity); Link getRelationshipLink(Resource resource, ResourceField field, boolean related); List<ResourceIdentifier> toResourceIds(Collection<?> entities); ResourceIdentifier toResourceId(Object entity); void setLinks(LinksContainer container, LinksInformation linksInformation, QueryAdapter queryAdapter); void setMeta(MetaContainer container, MetaInformation metaInformation); ResourceInformation getResourceInformation(Object resource); ResourceInformation getResourceInformation(String resourceType); boolean hasResourceInformation(String resourceType); String getSelfUrl(QueryContext queryContext, ResourceInformation resourceInformation, Object entity); static SerializerUtil getSerializerUtil(); }### Answer:
@Test public void toResourceId() { Task task = new Task(); task.setId(12L); ResourceIdentifier id = util.toResourceId(task); Assert.assertEquals("tasks", id.getType()); Assert.assertEquals("12", id.getId()); }
@Test public void nullRoResourceId() { Assert.assertNull(util.toResourceId(null)); }
|
### Question:
DocumentMapperUtil { public List<ResourceIdentifier> toResourceIds(Collection<?> entities) { List<ResourceIdentifier> results = new ArrayList<>(); for (Object entity : entities) { results.add(toResourceId(entity)); } return results; } DocumentMapperUtil(ResourceRegistry resourceRegistry, ObjectMapper objectMapper,
PropertiesProvider propertiesProvider, UrlBuilder urlBuilder); @SuppressWarnings({ "unchecked", "rawtypes" }) static List<T> toList(Object entity); Link getRelationshipLink(Resource resource, ResourceField field, boolean related); List<ResourceIdentifier> toResourceIds(Collection<?> entities); ResourceIdentifier toResourceId(Object entity); void setLinks(LinksContainer container, LinksInformation linksInformation, QueryAdapter queryAdapter); void setMeta(MetaContainer container, MetaInformation metaInformation); ResourceInformation getResourceInformation(Object resource); ResourceInformation getResourceInformation(String resourceType); boolean hasResourceInformation(String resourceType); String getSelfUrl(QueryContext queryContext, ResourceInformation resourceInformation, Object entity); static SerializerUtil getSerializerUtil(); }### Answer:
@Test public void toResourceIds() { Task task = new Task(); task.setId(12L); List<ResourceIdentifier> ids = util.toResourceIds(Arrays.asList(task)); ResourceIdentifier id = ids.get(0); Assert.assertEquals("tasks", id.getType()); Assert.assertEquals("12", id.getId()); }
|
### Question:
DefaultInformationBuilder implements InformationBuilder { @Override public RelationshipRepositoryInformationBuilder createRelationshipRepository(String sourceResourceType, String targetResourceType) { RelationshipMatcher matcher = new RelationshipMatcher(); matcher.rule().target(targetResourceType).source(sourceResourceType).add(); return createRelationshipRepository(matcher); } DefaultInformationBuilder(TypeParser typeParser); @Override FieldInformationBuilder createResourceField(); @Override RelationshipRepositoryInformationBuilder createRelationshipRepository(String sourceResourceType, String targetResourceType); @Override RelationshipRepositoryInformationBuilder createRelationshipRepository(RelationshipMatcher matcher); @Override ResourceRepositoryInformationBuilder createResourceRepository(); @Override ResourceInformationBuilder createResource(Class<?> resourceClass, String resourceType); @Override ResourceInformationBuilder createResource(Class<?> resourceClass, String resourceType, String resourcePath); }### Answer:
@Test public void checkRelationshipRepository() { InformationBuilder.RelationshipRepositoryInformationBuilder repositoryBuilder = builder.createRelationshipRepository("projects", "tasks"); RepositoryMethodAccess expectedAccess = new RepositoryMethodAccess(true, false, true, false); repositoryBuilder.setAccess(expectedAccess); RelationshipRepositoryInformation repositoryInformation = repositoryBuilder.build(); RepositoryMethodAccess actualAccess = repositoryInformation.getAccess(); Assert.assertEquals(expectedAccess, actualAccess); }
|
### Question:
HomeModule implements Module, ModuleExtensionAware<HomeModuleExtension> { @Override public String getModuleName() { return "home"; } protected HomeModule(); static HomeModule create(); static HomeModule create(HomeFormat defaultFormat); void addPathFilter(Predicate<HttpRequestContext> pathFilter); @Override String getModuleName(); @Override void setupModule(final ModuleContext context); List<String> list(String requestPath, QueryContext queryContext); boolean hasPotentialFilterIssues(); @Override void setExtensions(List<HomeModuleExtension> extensions); @Override void init(); static final String JSON_HOME_CONTENT_TYPE; static final String JSON_CONTENT_TYPE; }### Answer:
@Test public void moduleName() { HomeModule module = boot.getModuleRegistry().getModule(HomeModule.class).get(); Assert.assertEquals("home", module.getModuleName()); }
|
### Question:
RepositoryAdapterUtils { public static LinksInformation enrichLinksInformation(ModuleRegistry moduleRegistry, LinksInformation linksInformation, Object resource, RepositoryRequestSpec requestSpec) { if (requestSpec.getQueryAdapter() instanceof QuerySpecAdapter && resource instanceof ResourceList) { ResourceList<?> resources = (ResourceList<?>) resource; linksInformation = enrichPageLinksInformation(moduleRegistry, linksInformation, resources, requestSpec); } return linksInformation; } static LinksInformation enrichLinksInformation(ModuleRegistry moduleRegistry,
LinksInformation linksInformation, Object resource,
RepositoryRequestSpec requestSpec); }### Answer:
@Test public void enrichSelfLinksInformationNoQuerySpec() { ResourceList resources = new DefaultResourceList(); when(requestSpec.getQueryAdapter()).thenReturn(mock(QueryAdapter.class)); LinksInformation result = RepositoryAdapterUtils.enrichLinksInformation(moduleRegistry, null, resources, requestSpec); assertThat(result, is(nullValue())); }
|
### Question:
StringUtils { public static String join(String delimiter, Iterable<?> stringsIterable) { List<String> strings = new LinkedList<>(); Iterator<?> iterator = stringsIterable.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj == null) { strings.add(null); } else { strings.add(obj.toString()); } } StringBuilder ab = new StringBuilder(); for (int i = 0; i < strings.size(); i++) { ab.append(strings.get(i)); if (i != strings.size() - 1) { ab.append(delimiter); } } return ab.toString(); } private StringUtils(); static String join(String delimiter, Iterable<?> stringsIterable); static boolean isBlank(String value); static String emptyToNull(String value); static String decapitalize(String name); static String firstToUpper(String name); static String nullToEmpty(String value); static final String EMPTY; }### Answer:
@Test public void onSingleElementShouldReturnTheSameValue() { String string = "hello world"; List<String> values = Collections.singletonList(string); String result = StringUtils.join(",", values); assertThat(result).isEqualTo(string); }
@Test public void onTwoElementsShouldReturnJoinedValues() { List<String> values = Arrays.asList("hello", "world"); String result = StringUtils.join(" ", values); assertThat(result).isEqualTo("hello world"); }
@Test public void onJoinOfNulls() { Assert.assertEquals("null,null", StringUtils.join(",", Arrays.asList(null, null))); }
|
### Question:
StringUtils { public static boolean isBlank(String value) { int strLen; if (value == null || (strLen = value.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((!Character.isWhitespace(value.charAt(i)))) { return false; } } return true; } private StringUtils(); static String join(String delimiter, Iterable<?> stringsIterable); static boolean isBlank(String value); static String emptyToNull(String value); static String decapitalize(String name); static String firstToUpper(String name); static String nullToEmpty(String value); static final String EMPTY; }### Answer:
@Test public void onIsBlankValues() { assertTrue(StringUtils.isBlank(null)); assertTrue(StringUtils.isBlank("")); assertTrue(StringUtils.isBlank(" ")); assertFalse(StringUtils.isBlank("crnk")); assertFalse(StringUtils.isBlank(" crnk ")); }
|
### Question:
StringUtils { public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } char[] chars = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } private StringUtils(); static String join(String delimiter, Iterable<?> stringsIterable); static boolean isBlank(String value); static String emptyToNull(String value); static String decapitalize(String name); static String firstToUpper(String name); static String nullToEmpty(String value); static final String EMPTY; }### Answer:
@Test public void checkDecapitalize() { Assert.assertEquals("", StringUtils.decapitalize("")); Assert.assertEquals("test", StringUtils.decapitalize("Test")); Assert.assertEquals("someTest", StringUtils.decapitalize("SomeTest")); }
|
### Question:
PropertyUtils { public static Object getProperty(Object bean, String field) { INSTANCE.checkParameters(bean, field); try { return INSTANCE.getPropertyValue(bean, field); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw handleReflectionException(bean.getClass(), field, e); } } private PropertyUtils(); static Object getProperty(Object bean, String field); static Class<?> getPropertyClass(Class<?> beanClass, String field); static Type getPropertyType(Class<?> beanClass, String field); static Object getProperty(Object bean, List<String> propertyPath); static Class<?> getPropertyClass(Class<?> clazz, List<String> propertyPath); static void setProperty(Object bean, String field, Object value); @SuppressWarnings("unchecked") static Object prepareValue(Object value, Class<?> fieldClass); }### Answer:
@Test public void onNullBeanGetShouldThrowException() { expectedException.expect(IllegalArgumentException.class); PropertyUtils.getProperty(null, "privatePropertyWithMutators"); }
@Test public void onBooleanWithGetPrefix() { Bean bean = new Bean(); bean.setBooleanWithGetPrefix(true); Object result = PropertyUtils.getProperty(bean, "booleanWithGetPrefix"); assertThat(result).isEqualTo(true); }
@Test public void onNullFieldGetShouldThrowException() { Bean bean = new Bean(); expectedException.expect(IllegalArgumentException.class); PropertyUtils.getProperty(bean, (String) null); }
@Test public void onBooleanPrimitiveWithMutatorsShouldReturnValue() { Bean bean = new Bean(); bean.setBooleanPrimitivePropertyWithMutators(true); Object result = PropertyUtils .getProperty(bean, "booleanPrimitivePropertyWithMutators"); assertThat(result).isEqualTo(true); }
@Test public void methodPropertyShouldReturnValue() { Bean bean = new Bean(); Object result = PropertyUtils .getProperty(bean, "methodProperty"); assertThat(result).isEqualTo("noFieldsHere"); }
@Test public void onBooleanWithMutatorsShouldReturnValue() { Bean bean = new Bean(); bean.setBooleanPropertyWithMutators(true); Object result = PropertyUtils.getProperty(bean, "booleanPropertyWithMutators"); assertThat(result).isEqualTo(true); }
@Test public void onStringPublicWithMutatorsShouldReturnValue() { Bean bean = new Bean(); bean.publicProperty = "value"; Object result = PropertyUtils.getProperty(bean, "publicProperty"); assertThat(result).isEqualTo("value"); }
@Test public void onStringProtectedGetWithMutatorsShouldThrowException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.getProperty(bean, "protectedProperty"); }
@Test public void onInheritedStringPrivateWithMutatorsShouldReturnValue() { Bean bean = new ChildBean(); bean.setPrivatePropertyWithMutators("value"); Object result = PropertyUtils.getProperty(bean, "privatePropertyWithMutators"); assertThat(result).isEqualTo("value"); }
@Test public void onMethodAccessorOnlyShouldReturnValue() { GetterTest bean = new GetterTest(); Object result = PropertyUtils.getProperty(bean, "property"); assertThat(result).isEqualTo("valueProperty"); }
@Test public void onNonExistingPropertyShouldThrowException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.getProperty(bean, "nonExistingProperty"); }
@Test public void onFieldWithThrowingUncheckedExceptionGetterShouldThrowException() { Bean bean = new Bean(); expectedException.expect(IllegalStateException.class); PropertyUtils.getProperty(bean, "uncheckedExceptionalField"); }
@Test public void onFieldWithThrowingCheckedExceptionGetterShouldThrowException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.getProperty(bean, "PropertyException"); }
@Test public void nullBeanResultsInNullValue() { Bean bean = null; Object result = PropertyUtils.getProperty(bean, Arrays.asList("publicProperty")); assertThat(result).isNull(); }
|
### Question:
CrnkClient { public void setObjectMapper(ObjectMapper objectMapper) { PreconditionUtil.verify(this.objectMapper == null, "ObjectMapper already configured, consider calling SetObjectMapper earlier or and avoid multiple calls"); this.objectMapper = objectMapper; this.configureObjectMapper(); } CrnkClient(String serviceUrl); CrnkClient(String serviceUrl, ClientType clientType); CrnkClient(ServiceUrlProvider serviceUrlProvider, ClientType clientType); int getVersion(); void setVersion(int version); ClientFormat getFormat(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); QueryContext getQueryContext(); void findModules(); void setProxyFactory(ClientProxyFactory proxyFactory); void registerHttpAdapterProvider(HttpAdapterProvider httpAdapterProvider); List<HttpAdapterProvider> getHttpAdapterProviders(); @SuppressWarnings("unchecked") R getRepositoryForInterface(Class<R> repositoryInterfaceClass); @SuppressWarnings({ "unchecked", "rawtypes" }) ResourceRepository<T, I> getRepositoryForType(Class<T> resourceClass); ResourceRepository<Resource, String> getRepositoryForPath(String resourceType); RelationshipRepository<Resource, String, Resource, String> getRepositoryForPath(String sourceResourceType,
String targetResourceType); @SuppressWarnings({ "unchecked", "rawtypes" }) RelationshipRepository<T, I, D, J> getRepositoryForType(
Class<T> sourceClass, Class<D> targetClass); ManyRelationshipRepository<T, I, D, J> getManyRepositoryForType(
Class<T> sourceClass, Class<D> targetClass); OneRelationshipRepository<T, I, D, J> getOneRepositoryForType(
Class<T> sourceClass, Class<D> targetClass); ObjectMapper getObjectMapper(); void setObjectMapper(ObjectMapper objectMapper); ResourceRegistry getRegistry(); void addModule(Module module); HttpAdapter getHttpAdapter(); void setHttpAdapter(HttpAdapter httpAdapter); ExceptionMapperRegistry getExceptionMapperRegistry(); ActionStubFactory getActionStubFactory(); void setActionStubFactory(ActionStubFactory actionStubFactory); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); ModuleRegistry getModuleRegistry(); ClientDocumentMapper getDocumentMapper(); ServiceUrlProvider getServiceUrlProvider(); }### Answer:
@Test public void testSetObjectMapper() { ObjectMapper myObjectMapper = new ObjectMapper(); client = new CrnkClient(getBaseUri().toString()) { protected ObjectMapper createDefaultObjectMapper() { throw new IllegalStateException("this should not happer"); } }; client.setObjectMapper(myObjectMapper); Assert.assertSame(myObjectMapper, client.getObjectMapper()); ResourceRepository<Schedule, Object> repository = client.getRepositoryForType(Schedule.class); repository.findAll(new QuerySpec(Schedule.class)); }
|
### Question:
PropertyUtils { public static Class<?> getPropertyClass(Class<?> beanClass, String field) { return INSTANCE.findPropertyClass(beanClass, field); } private PropertyUtils(); static Object getProperty(Object bean, String field); static Class<?> getPropertyClass(Class<?> beanClass, String field); static Type getPropertyType(Class<?> beanClass, String field); static Object getProperty(Object bean, List<String> propertyPath); static Class<?> getPropertyClass(Class<?> clazz, List<String> propertyPath); static void setProperty(Object bean, String field, Object value); @SuppressWarnings("unchecked") static Object prepareValue(Object value, Class<?> fieldClass); }### Answer:
@Test public void getPropertyClassForMethodPropertyShouldReturnClass() { Object result = PropertyUtils.getPropertyClass(Bean.class, "methodProperty"); assertThat(result).isEqualTo(String.class); }
@Test public void onStringPublicReturnStringClass() { Object result = PropertyUtils.getPropertyClass(Bean.class, "publicProperty"); assertThat(result).isEqualTo(String.class); }
@Test public void getPropertyClassShouldThrowExceptionForInvalidField() { try { PropertyUtils.getPropertyClass(Bean.class, "doesNotExist"); Assert.fail(); } catch (PropertyException e) { Assert.assertEquals("doesNotExist", e.getField()); Assert.assertEquals(Bean.class, e.getResourceClass()); } }
@Test public void onBooleanPropertyWithMutatorsReturnBooleanClass() { Object result = PropertyUtils.getPropertyClass(Bean.class, "booleanPropertyWithMutators"); assertThat(result).isEqualTo(Boolean.class); }
@Test public void unknownPropertyClassThrowingException() { expectedException.expect(PropertyException.class); PropertyUtils.getPropertyClass(Bean.class, "attrThatDoesNotExist"); }
|
### Question:
PropertyUtils { public static Type getPropertyType(Class<?> beanClass, String field) { return INSTANCE.findPropertyType(beanClass, field); } private PropertyUtils(); static Object getProperty(Object bean, String field); static Class<?> getPropertyClass(Class<?> beanClass, String field); static Type getPropertyType(Class<?> beanClass, String field); static Object getProperty(Object bean, List<String> propertyPath); static Class<?> getPropertyClass(Class<?> clazz, List<String> propertyPath); static void setProperty(Object bean, String field, Object value); @SuppressWarnings("unchecked") static Object prepareValue(Object value, Class<?> fieldClass); }### Answer:
@Test public void getPropertyTypeForMethodPropertyShouldReturnType() { Object result = PropertyUtils.getPropertyType(Bean.class, "methodProperty"); assertThat(result).isEqualTo(String.class); }
@Test public void getPropertyTypeForSetShouldReturnGenericType() { Object result = PropertyUtils.getPropertyType(Bean.class, "setProperty"); assertThat(ParameterizedType.class).isAssignableFrom(result.getClass()); }
@Test public void getPropertyTypeShouldThrowExceptionForInvalidField() { try { PropertyUtils.getPropertyType(Bean.class, "doesNotExist"); Assert.fail(); } catch (PropertyException e) { Assert.assertEquals("doesNotExist", e.getField()); Assert.assertEquals(Bean.class, e.getResourceClass()); } }
@Test public void onStringPublicReturnStringType() { Object result = PropertyUtils.getPropertyType(Bean.class, "publicProperty"); assertThat(result).isEqualTo(String.class); }
@Test public void unknownPropertyTypeThrowingException() { expectedException.expect(PropertyException.class); PropertyUtils.getPropertyType(Bean.class, "attrThatDoesNotExist"); }
|
### Question:
ClientResourceUpsert extends ResourceUpsert { public String getUID(ResourceIdentifier id) { return id.getType() + "#" + id.getId(); } ClientResourceUpsert(ClientProxyFactory proxyFactory); String getUID(ResourceIdentifier id); String getUID(RegistryEntry entry, Serializable id); void setRelations(List<Resource> resources, QueryContext queryContext); List<Object> allocateResources(List<Resource> resources, QueryContext queryContext); @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test public void testUIDComputation() { Serializable id = "test"; RegistryEntry entry = Mockito.mock(RegistryEntry.class); ResourceInformation resourceInformation = Mockito.mock(ResourceInformation.class); Mockito.when(resourceInformation.getResourceType()).thenReturn("someType"); Mockito.when(resourceInformation.toIdString(Mockito.eq(id))).thenReturn("someId"); Mockito.when(entry.getResourceInformation()).thenReturn(resourceInformation); String uid = upsert.getUID(entry, id); Assert.assertEquals("someType#someId", uid); }
|
### Question:
PropertyUtils { public static void setProperty(Object bean, String field, Object value) { INSTANCE.checkParameters(bean, field); try { INSTANCE.setPropertyValue(bean, field, value); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw handleReflectionException(bean.getClass(), field, e); } } private PropertyUtils(); static Object getProperty(Object bean, String field); static Class<?> getPropertyClass(Class<?> beanClass, String field); static Type getPropertyType(Class<?> beanClass, String field); static Object getProperty(Object bean, List<String> propertyPath); static Class<?> getPropertyClass(Class<?> clazz, List<String> propertyPath); static void setProperty(Object bean, String field, Object value); @SuppressWarnings("unchecked") static Object prepareValue(Object value, Class<?> fieldClass); }### Answer:
@Test public void onListValueForSetPropertyShouldGetConverted() { Bean bean = new Bean(); PropertyUtils.setProperty(bean, "setProperty", Arrays.asList("4", "1", "3", "2")); assertEquals(bean.getSetProperty(), new LinkedHashSet(Arrays.asList("4", "1", "3", "2"))); }
@Test public void onNullBeanSetShouldThrowException() { expectedException.expect(IllegalArgumentException.class); PropertyUtils.setProperty(null, "privatePropertyWithMutators", null); }
@Test public void onNullFieldSetShouldThrowException() { Bean bean = new Bean(); expectedException.expect(IllegalArgumentException.class); PropertyUtils.setProperty(bean, null, null); }
@Test public void onBooleanPrimitiveWithMutatorsShouldSetValue() { Bean bean = new Bean(); PropertyUtils.setProperty(bean, "booleanPrimitivePropertyWithMutators", true); assertThat(bean.isBooleanPrimitivePropertyWithMutators()).isEqualTo(true); }
@Test public void onBooleanWithMutatorsShouldSetValue() { Bean bean = new Bean(); PropertyUtils.setProperty(bean, "booleanPropertyWithMutators", true); assertThat(bean.getBooleanPropertyWithMutators()).isEqualTo(true); }
@Test public void onStringPublicWithMutatorsShouldSetValue() { Bean bean = new Bean(); PropertyUtils.setProperty(bean, "publicProperty", "value"); assertThat(bean.publicProperty).isEqualTo("value"); }
@Test public void onStringProtectedSetWithMutatorsShouldThrowException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.setProperty(bean, "protectedProperty", null); }
@Test public void onInheritedStringPrivateWithMutatorsShouldSetValue() { Bean bean = new ChildBean(); PropertyUtils.setProperty(bean, "privatePropertyWithMutators", "value"); assertThat(bean.getPrivatePropertyWithMutators()).isEqualTo("value"); }
@Test public void onFieldListShouldSetValue() { FieldListTest bean = new FieldListTest(); List<String> value = Collections.singletonList("asd"); PropertyUtils.setProperty(bean, "property", value); assertThat(bean.property).isEqualTo(value); }
@Test public void onFieldSetShouldSetValue() { FieldSetTest bean = new FieldSetTest(); Set<String> value = Collections.singleton("asd"); PropertyUtils.setProperty(bean, "property", value); assertThat(bean.property).isEqualTo(value); }
@Test public void onFieldWithThrowingUncheckedExceptionSetterShouldThrowException() { Bean bean = new Bean(); expectedException.expect(IllegalStateException.class); PropertyUtils.setProperty(bean, "uncheckedExceptionalField", "value"); }
@Test public void onFieldWithThrowingCheckedExceptionSetterShouldThrowException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.setProperty(bean, "checkedExceptionalField", "value"); }
@Test public void unknownPropertyThrowingException() { Bean bean = new Bean(); expectedException.expect(PropertyException.class); PropertyUtils.setProperty(bean, "attrThatDoesNotExist", "value"); }
|
### Question:
ClientResourceUpsert extends ResourceUpsert { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { throw new UnsupportedOperationException(); } ClientResourceUpsert(ClientProxyFactory proxyFactory); String getUID(ResourceIdentifier id); String getUID(RegistryEntry entry, Serializable id); void setRelations(List<Resource> resources, QueryContext queryContext); List<Object> allocateResources(List<Resource> resources, QueryContext queryContext); @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testAcceptableNotSupported() { upsert.isAcceptable(null, null); }
|
### Question:
SecurityModule implements Module { public boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission) { String resourceType = toType(resourceClass); return isAllowed(queryContext, resourceType, permission); } protected SecurityModule(); protected SecurityModule(SecurityConfig config); DataRoomMatcher getDataRoomMatcher(); static SecurityModule newServerModule(SecurityConfig config); static SecurityModule newClientModule(); void setEnabled(final boolean enabled); boolean isEnabled(); void setEnabled(Supplier<Boolean> enabled); @Override String getModuleName(); void reconfigure(SecurityConfig config); SecurityConfig getConfig(); @Override void setupModule(ModuleContext context); boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission); boolean isAllowed(QueryContext queryContext, String resourceType, ResourcePermission permission); ResourcePermission getCallerPermissions(QueryContext queryContext, String resourceType); ResourcePermission getRolePermissions(QueryContext queryContext, String resourceType, String checkedRole); ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass); ResourcePermission getResourcePermission(QueryContext queryContext, String resourceType); boolean isUserInRole(QueryContext queryContext, String role); SecurityProvider getCallerSecurityProvider(); }### Answer:
@Test(expected = RepositoryNotFoundException.class) public void testBlackListingOfUnknownClass() { QueryContext queryContext = Mockito.mock(QueryContext.class); securityModule.isAllowed(queryContext, UnknownResource.class, ResourcePermission.GET); }
@Test public void testUnknownResource() { QueryContext queryContext = Mockito.mock(QueryContext.class); allowedRule = "taskRole"; Assert.assertTrue(securityModule.isAllowed(queryContext, Task.class, ResourcePermission.GET)); Assert.assertTrue(securityModule.isAllowed(queryContext, Task.class, ResourcePermission.ALL)); Assert.assertFalse(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.DELETE)); Assert.assertFalse(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.POST)); allowedRule = "projectRole"; Assert.assertTrue(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.GET)); Assert.assertTrue(securityModule.isAllowed(queryContext, Task.class, ResourcePermission.GET)); Assert.assertFalse(securityModule.isAllowed(queryContext, Task.class, ResourcePermission.ALL)); Assert.assertFalse(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.DELETE)); Assert.assertTrue(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.POST)); }
|
### Question:
ClientResourceUpsert extends ResourceUpsert { @Override protected HttpMethod getHttpMethod() { throw new UnsupportedOperationException(); } ClientResourceUpsert(ClientProxyFactory proxyFactory); String getUID(ResourceIdentifier id); String getUID(RegistryEntry entry, Serializable id); void setRelations(List<Resource> resources, QueryContext queryContext); List<Object> allocateResources(List<Resource> resources, QueryContext queryContext); @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testMethodNotSupported() { upsert.getHttpMethod(); }
|
### Question:
ClassUtils { public static boolean existsClass(String className) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); loadClass(classLoader, className); return true; } catch (IllegalStateException e) { return false; } } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void stringMustExist() { Assert.assertTrue(ClassUtils.existsClass(String.class.getName())); }
@Test public void unknownClassMustNotExist() { Assert.assertFalse(ClassUtils.existsClass("does.not.exist")); }
|
### Question:
ClassUtils { public static Class<?> getRawType(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return getRawType(((ParameterizedType) type).getRawType()); } else if (type instanceof TypeVariable<?>) { return getRawType(((TypeVariable<?>) type).getBounds()[0]); } else if (type instanceof WildcardType) { return getRawType(((WildcardType) type).getUpperBounds()[0]); } throw new IllegalStateException("unknown type: " + type); } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void rawTypeFromParameterizedType() { Class<?> result = ClassUtils.getRawType(ProjectRepository.class.getGenericSuperclass()); assertThat(result).isEqualTo(ResourceRepositoryBase.class); }
@Test public void rawTypeFromRawType() { Class<?> result = ClassUtils.getRawType(String.class); assertThat(result).isEqualTo(String.class); }
@Test(expected = IllegalStateException.class) public void exceptionForUnknownRawType() { ClassUtils.getRawType(null); }
|
### Question:
ClassUtils { public static List<Field> getClassFields(Class<?> beanClass) { Map<String, Field> resultMap = new HashMap<>(); LinkedList<Field> results = new LinkedList<>(); Class<?> currentClass = beanClass; while (currentClass != null && currentClass != Object.class) { for (Field field : currentClass.getDeclaredFields()) { if (!field.isSynthetic()) { Field v = resultMap.get(field.getName()); if (v == null) { resultMap.put(field.getName(), field); results.add(field); } } } currentClass = currentClass.getSuperclass(); } return results; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onClassInheritanceShouldReturnInheritedClasses() { List<Field> result = ClassUtils.getClassFields(ChildClass.class); assertThat(result).hasSize(2); }
|
### Question:
ClassUtils { public static Field findClassField(Class<?> beanClass, String fieldName) { Class<?> currentClass = beanClass; while (currentClass != null && currentClass != Object.class) { for (Field field : currentClass.getDeclaredFields()) { if (field.isSynthetic()) { continue; } if (field.getName().equals(fieldName)) { return field; } } currentClass = currentClass.getSuperclass(); } return null; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onClassInheritanceShouldReturnInheritedField() { Field result = ClassUtils.findClassField(ChildClass.class, "parentField"); assertThat(result).isNotNull(); assertThat(result.getName()).isEqualTo("parentField"); assertThat(result.getDeclaringClass()).isEqualTo(ParentClass.class); }
|
### Question:
ClientDocumentMapper extends DocumentMapper { public Object fromDocument(Document document, boolean getList, QueryContext queryContext) { ControllerContext controllerContext = new ControllerContext(moduleRegistry, () -> this); ClientResourceUpsert upsert = new ClientResourceUpsert(proxyFactory); upsert.init(controllerContext); PreconditionUtil.verify(document.getErrors() == null || document.getErrors().isEmpty(), "document contains json api errors and cannot be processed, use exception mapper instead"); if (!document.getData().isPresent()) { return null; } List<Resource> included = document.getIncluded(); List<Resource> data = document.getCollectionData().get(); List<Object> dataObjects = upsert.allocateResources(data, queryContext); if (included != null) { upsert.allocateResources(included, queryContext); } upsert.setRelations(data, queryContext); if (included != null) { upsert.setRelations(included, queryContext); } if (getList) { DefaultResourceList<Object> resourceList = new DefaultResourceList(); resourceList.addAll(dataObjects); if (document.getLinks() != null) { resourceList.setLinks(new JsonLinksInformation(document.getLinks(), objectMapper)); } if (document.getMeta() != null) { resourceList.setMeta(new JsonMetaInformation(document.getMeta(), objectMapper)); } return resourceList; } else { if (dataObjects.isEmpty()) { return null; } if (document.isMultiple()) { return dataObjects; } PreconditionUtil.verify(dataObjects.size() == 1, "expected unique result, got %s", dataObjects); return dataObjects.get(0); } } ClientDocumentMapper(ModuleRegistry moduleRegistry, ObjectMapper objectMapper, PropertiesProvider
propertiesProvider); void setProxyFactory(ClientProxyFactory proxyFactory); Object fromDocument(Document document, boolean getList, QueryContext queryContext); }### Answer:
@Test public void testNullData() { Document doc = new Document(); doc.setData(Nullable.nullValue()); Assert.assertNull(documentMapper.fromDocument(doc, false, queryContext)); }
@Test public void testNoData() { Document doc = new Document(); doc.setData(Nullable.empty()); Assert.assertNull(documentMapper.fromDocument(doc, false, queryContext)); }
@Test(expected = IllegalStateException.class) public void testCannotHaveErrors() { Document doc = new Document(); doc.setErrors(Arrays.asList(new ErrorDataBuilder().build())); doc.setData(Nullable.nullValue()); documentMapper.fromDocument(doc, false, queryContext); }
|
### Question:
ClassUtils { public static List<Method> getClassGetters(Class<?> beanClass) { Map<String, Method> resultMap = new HashMap<>(); LinkedList<Method> results = new LinkedList<>(); Class<?> currentClass = beanClass; while (currentClass != null && currentClass != Object.class) { getDeclaredClassGetters(currentClass, resultMap, results); currentClass = currentClass.getSuperclass(); } return results; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onGetGettersShouldReturnMethodsStartingWithGet() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("aetParentField")); }
@Test public void onGetGettersShouldReturnMethodsThatNotTakeParams() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("getParentFieldWithParameter", String.class)); }
@Test public void onGetGettersShouldReturnMethodsThatReturnValue() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("getParentFieldReturningVoid")); }
@Test public void onGetGettersShouldReturnBooleanGettersThatHaveName() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("is")); }
@Test public void onGetGettersShouldReturnNonBooleanGettersThatHaveName() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("get")); }
@Test public void onClassInheritanceShouldReturnInheritedGetters() { List<Method> result = ClassUtils.getClassGetters(ChildClass.class); assertThat(result).hasSize(5); }
|
### Question:
ClassUtils { public static Method findGetter(Class<?> beanClass, String fieldName) { for (Method method : beanClass.getMethods()) { if (!isGetter(method)) { continue; } String methodGetterName = getGetterFieldName(method); if (fieldName.equals(methodGetterName)) { return method; } } return null; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onFindGetterShouldReturnBooleanPropertyWithGet() { Method method = ClassUtils.findGetter(ParentClass.class, "booleanPropertyWithGet"); assertThat(method.getName()).isEqualTo("getBooleanPropertyWithGet"); }
@Test public void onFindGetterShouldReturnIntegerMethod() { Method method = ClassUtils.findGetter(IntegerClass.class, "id"); assertThat(method.getName()).isEqualTo("getId"); }
@Test public void onFindGetterShouldReturnPrimitiveBooleanMethod() { Method method = ClassUtils.findGetter(ParentClass.class, "primitiveBooleanProperty"); assertThat(method.getName()).isEqualTo("isPrimitiveBooleanProperty"); }
@Test public void onFindGetterShouldReturnBooleanMethod() { Method method = ClassUtils.findGetter(ParentClass.class, "booleanProperty"); assertThat(method.getName()).isEqualTo("isBooleanProperty"); }
@Test public void onFindGetterShouldNotReturnNonBooleanIsMethods() { Method method = ClassUtils.findGetter(InvalidBooleanClass.class, "notABooleanReturnType"); assertThat(method).isNull(); }
|
### Question:
ClassUtils { public static List<Method> getClassSetters(Class<?> beanClass) { Map<String, Method> result = new HashMap<>(); Class<?> currentClass = beanClass; while (currentClass != null && currentClass != Object.class) { for (Method method : currentClass.getDeclaredMethods()) { if (!method.isSynthetic() && isSetter(method)) { result.putIfAbsent(method.getName(), method); } } currentClass = currentClass.getSuperclass(); } return new LinkedList<>(result.values()); } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onGetSettersShouldReturnMethodsThatSetValue() throws Exception { List<Method> result = ClassUtils.getClassSetters(ParentClass.class); assertThat(result).containsOnly(ParentClass.class.getDeclaredMethod("setValue", String.class)); }
@Test public void onClassInheritanceShouldReturnInheritedSetters() { List<Method> result = ClassUtils.getClassSetters(ChildClass.class); assertThat(result).hasSize(1); }
|
### Question:
ClassUtils { public static <T extends Annotation> Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass) { Class<?> currentClass = beanClass; while (currentClass != null && currentClass != Object.class) { if (currentClass.isAnnotationPresent(annotationClass)) { return Optional.of(currentClass.getAnnotation(annotationClass)); } currentClass = currentClass.getSuperclass(); } return Optional.empty(); } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onGetAnnotationShouldReturnAnnotation() { Optional<JsonApiResource> result = ClassUtils.getAnnotation(ResourceClass.class, JsonApiResource.class); assertThat(result.get()).isInstanceOf(JsonApiResource.class); }
@Test public void onGetAnnotationShouldReturnParentAnnotation() { Optional<JsonPropertyOrder> result = ClassUtils.getAnnotation(ChildClass.class, JsonPropertyOrder.class); assertThat(result.get()).isInstanceOf(JsonPropertyOrder.class); }
@Test public void onNonExistingAnnotationShouldReturnEmptyResult() { Optional<JsonIgnore> result = ClassUtils.getAnnotation(ResourceClass.class, JsonIgnore.class); assertThat(result.isPresent()).isFalse(); }
|
### Question:
ClassUtils { public static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ResourceException(String.format("couldn't create a new instance of %s", clazz), e); } } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onValidClassShouldCreateNewInstance() { ResourceClass result = ClassUtils.newInstance(ResourceClass.class); assertThat(result).isInstanceOf(ResourceClass.class); }
@Test(expected = IllegalStateException.class) public void onClassWithCrushingConstructorShouldThrowException() { ClassUtils.newInstance(ClassWithCrashingConstructor.class); }
@Test(expected = ResourceException.class) public void onClassWithoutDefaultConstructorShouldThrowException() { ClassUtils.newInstance(ClassWithoutDefaultConstructor.class); }
|
### Question:
ClassUtils { public static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType) { String upperCaseName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); String methodName = "set" + upperCaseName; try { return beanClass.getMethod(methodName, fieldType); } catch (NoSuchMethodException e1) { } Method[] methods = beanClass.getMethods(); for (Method method : methods) { Class<?>[] params = method.getParameterTypes(); if (methodName.equals(method.getName()) && params.length == 1 && params[0].isAssignableFrom(fieldType)) { return method; } } return null; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void onFindSetterShouldReturnIntegerMethod() { Method method = ClassUtils.findSetter(IntegerClass.class, "id", Integer.class); assertThat(method.getName()).isEqualTo("setId"); }
|
### Question:
ClassUtils { public static boolean isPrimitiveType(Class<?> type) { boolean isInt = type == byte.class || type == short.class || type == int.class || type == long.class; boolean isDecimal = type == short.class || type == double.class; return type == boolean.class || isInt || isDecimal; } private ClassUtils(); static boolean existsClass(String className); static Class<?> loadClass(ClassLoader classLoader, String className); static List<Field> getClassFields(Class<?> beanClass); static Optional<T> getAnnotation(Class<?> beanClass, Class<T> annotationClass); static Field findClassField(Class<?> beanClass, String fieldName); static Method findGetter(Class<?> beanClass, String fieldName); static String getGetterFieldName(Method getter); static Method findSetter(Class<?> beanClass, String fieldName, Class<?> fieldType); static List<Method> getClassGetters(Class<?> beanClass); static List<Method> getClassSetters(Class<?> beanClass); static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass); static T newInstance(Class<T> clazz); static boolean isBooleanGetter(Method method); static Class<?> getRawType(Type type); static boolean isPrimitiveType(Class<?> type); static Type getElementType(Type genericType); static final String PREFIX_GETTER_IS; static final String PREFIX_GETTER_GET; }### Answer:
@Test public void testIsPrimitiveType() { assertThat(ClassUtils.isPrimitiveType(boolean.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(byte.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(short.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(int.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(long.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(short.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(double.class)).isTrue(); assertThat(ClassUtils.isPrimitiveType(String.class)).isFalse(); assertThat(ClassUtils.isPrimitiveType(Object.class)).isFalse(); assertThat(ClassUtils.isPrimitiveType(int[].class)).isFalse(); }
|
### Question:
PreconditionUtil { public static void assertTrue(String message, boolean condition) { verify(condition, message); } private PreconditionUtil(); static void assertEquals(String message, Object expected, Object actual); static void verifyEquals(Object expected, Object actual, String message, Object... args); static void fail(String message, Object... args); static void assertNotNull(String message, Object object); static void assertTrue(String message, boolean condition); static void assertTrue(boolean condition, String message, Object... args); static void assertFalse(boolean condition, String message, Object... args); static void assertFalse(String message, boolean condition); static void assertNull(String message, Object object); static void verify(boolean condition, String messageFormat, Object... args); }### Answer:
@Test public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<PreconditionUtil> constructor = PreconditionUtil.class.getDeclaredConstructor(); Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
@Test(expected = IllegalStateException.class) public void testTrueNotSatisfied() { PreconditionUtil.assertTrue(null, false); }
|
### Question:
PreconditionUtil { public static void assertEquals(String message, Object expected, Object actual) { verifyEquals(expected, actual, message); } private PreconditionUtil(); static void assertEquals(String message, Object expected, Object actual); static void verifyEquals(Object expected, Object actual, String message, Object... args); static void fail(String message, Object... args); static void assertNotNull(String message, Object object); static void assertTrue(String message, boolean condition); static void assertTrue(boolean condition, String message, Object... args); static void assertFalse(boolean condition, String message, Object... args); static void assertFalse(String message, boolean condition); static void assertNull(String message, Object object); static void verify(boolean condition, String messageFormat, Object... args); }### Answer:
@Test(expected = IllegalStateException.class) public void testObjectEqualsNotSatisfied() { PreconditionUtil.assertEquals("message", new Object(), new Object()); }
@Test(expected = IllegalStateException.class) public void testEqualsNotSatisfied() { PreconditionUtil.assertEquals(null, 1, 2); }
@Test(expected = IllegalStateException.class) public void testEqualsNotSatisfied2() { PreconditionUtil.assertEquals(null, "a", "b"); }
|
### Question:
PreconditionUtil { public static void assertFalse(boolean condition, String message, Object... args) { verify(!condition, message, args); } private PreconditionUtil(); static void assertEquals(String message, Object expected, Object actual); static void verifyEquals(Object expected, Object actual, String message, Object... args); static void fail(String message, Object... args); static void assertNotNull(String message, Object object); static void assertTrue(String message, boolean condition); static void assertTrue(boolean condition, String message, Object... args); static void assertFalse(boolean condition, String message, Object... args); static void assertFalse(String message, boolean condition); static void assertNull(String message, Object object); static void verify(boolean condition, String messageFormat, Object... args); }### Answer:
@Test(expected = IllegalStateException.class) public void testFalseNotSatisfied() { PreconditionUtil.assertFalse(null, true); }
|
### Question:
PreconditionUtil { public static void assertNotNull(String message, Object object) { assertTrue(message, object != null); } private PreconditionUtil(); static void assertEquals(String message, Object expected, Object actual); static void verifyEquals(Object expected, Object actual, String message, Object... args); static void fail(String message, Object... args); static void assertNotNull(String message, Object object); static void assertTrue(String message, boolean condition); static void assertTrue(boolean condition, String message, Object... args); static void assertFalse(boolean condition, String message, Object... args); static void assertFalse(String message, boolean condition); static void assertNull(String message, Object object); static void verify(boolean condition, String messageFormat, Object... args); }### Answer:
@Test(expected = IllegalStateException.class) public void testNotNullNotSatisfied() { PreconditionUtil.assertNotNull(null, null); }
|
### Question:
ClientStubBase { protected RuntimeException handleError(String url, HttpAdapterResponse response) throws IOException { RuntimeException e = handleError(client, response, client.getFormat()); if (e instanceof CrnkException) { CrnkException crnkException = (CrnkException) e; crnkException.setUrl(url); } return e; } ClientStubBase(CrnkClient client, UrlBuilder urlBuilder, Class<?> resourceClass); static RuntimeException handleError(CrnkClient client, HttpAdapterResponse response, ClientFormat format); }### Answer:
@Test public void check404AndNoBodyGivesNotFoundException() throws IOException { HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(""); Mockito.when(response.code()).thenReturn(404); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof ResourceNotFoundException); }
@Test public void check500AndNoBodyGivesInternalServerErrorException() throws IOException { HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(""); Mockito.when(response.code()).thenReturn(500); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof InternalServerErrorException); }
@Test public void checkCheckedException() throws IOException { HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(""); Mockito.when(response.code()).thenReturn(599); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof ClientException); Assert.assertTrue(exception.getCause() instanceof IOException); }
@Test public void checkBodyWithNoErrorsAnd500Status() throws IOException { Document document = new Document(); document.setErrors(new ArrayList<ErrorData>()); String body = client.getObjectMapper().writeValueAsString(document); HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(body); Mockito.when(response.code()).thenReturn(500); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof InternalServerErrorException); }
@Test public void checkBodyWithErrors() throws IOException { Document document = new Document(); ErrorData errorData = new ErrorDataBuilder().setCode("404").setDetail("detail").build(); document.setErrors(Arrays.asList(errorData)); String body = client.getObjectMapper().writeValueAsString(document); HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(body); Mockito.when(response.getResponseHeader(HttpHeaders.HTTP_CONTENT_TYPE)) .thenReturn(HttpHeaders.JSONAPI_CONTENT_TYPE); Mockito.when(response.code()).thenReturn(404); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof ResourceNotFoundException); Assert.assertEquals("detail", exception.getMessage()); }
@Test public void checkBodyWithErrorsButInvalidContentType() throws IOException { Document document = new Document(); ErrorData errorData = new ErrorDataBuilder().setCode("404").setDetail("detail").build(); document.setErrors(Arrays.asList(errorData)); String body = client.getObjectMapper().writeValueAsString(document); HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class); Mockito.when(response.body()).thenReturn(body); Mockito.when(response.getResponseHeader(HttpHeaders.HTTP_CONTENT_TYPE)).thenReturn("not json api"); Mockito.when(response.code()).thenReturn(404); RuntimeException exception = stub.handleError(null, response); Assert.assertTrue(exception instanceof ResourceNotFoundException); Assert.assertNull(exception.getMessage()); }
|
### Question:
PreconditionUtil { public static void assertNull(String message, Object object) { assertTrue(message, object == null); } private PreconditionUtil(); static void assertEquals(String message, Object expected, Object actual); static void verifyEquals(Object expected, Object actual, String message, Object... args); static void fail(String message, Object... args); static void assertNotNull(String message, Object object); static void assertTrue(String message, boolean condition); static void assertTrue(boolean condition, String message, Object... args); static void assertFalse(boolean condition, String message, Object... args); static void assertFalse(String message, boolean condition); static void assertNull(String message, Object object); static void verify(boolean condition, String messageFormat, Object... args); }### Answer:
@Test(expected = IllegalStateException.class) public void testNullNotSatisfied() { PreconditionUtil.assertNull(null, "not null"); }
|
### Question:
CompareUtils { public static boolean isEquals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } private CompareUtils(); static boolean isEquals(Object a, Object b); }### Answer:
@Test public void test() { Assert.assertTrue(CompareUtils.isEquals("a", "a")); Assert.assertFalse(CompareUtils.isEquals(null, "a")); Assert.assertFalse(CompareUtils.isEquals("a", null)); Assert.assertTrue(CompareUtils.isEquals(null, null)); Assert.assertFalse(CompareUtils.isEquals("b", "a")); }
|
### Question:
UrlUtils { public static String removeTrailingSlash(String url) { if (url != null && url.endsWith("/")) { return url.substring(0, url.length() - 1); } else { return url; } } private UrlUtils(); static String removeTrailingSlash(String url); static String addTrailingSlash(String url); static String removeLeadingSlash(String url); static String addLeadingSlash(String url); static String concat(String baseUrl, String... paths); static String appendRelativePath(String baseUrl, String relativePath); }### Answer:
@Test public void testRemoveTrailingSlash() { Assert.assertNull(UrlUtils.removeTrailingSlash(null)); Assert.assertEquals("/test", UrlUtils.removeTrailingSlash("/test/")); Assert.assertEquals("test", UrlUtils.removeTrailingSlash("test/")); Assert.assertEquals("/test", UrlUtils.removeTrailingSlash("/test")); Assert.assertEquals("test", UrlUtils.removeTrailingSlash("test")); }
|
### Question:
UrlUtils { public static String removeLeadingSlash(String url) { if (url != null && url.startsWith("/")) { return url.substring(1); } else { return url; } } private UrlUtils(); static String removeTrailingSlash(String url); static String addTrailingSlash(String url); static String removeLeadingSlash(String url); static String addLeadingSlash(String url); static String concat(String baseUrl, String... paths); static String appendRelativePath(String baseUrl, String relativePath); }### Answer:
@Test public void testRemoveLeadingSlash() { Assert.assertNull(UrlUtils.removeLeadingSlash(null)); Assert.assertEquals("test/", UrlUtils.removeLeadingSlash("/test/")); Assert.assertEquals("test/", UrlUtils.removeLeadingSlash("test/")); Assert.assertEquals("test", UrlUtils.removeLeadingSlash("/test")); Assert.assertEquals("test", UrlUtils.removeLeadingSlash("test")); }
|
### Question:
IOUtils { public static byte[] readFully(InputStream is) throws IOException { int nRead; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } private IOUtils(); static byte[] readFully(InputStream is); static void writeFile(File file, String text); }### Answer:
@Test public void readFully() throws IOException { Random r = new Random(); for (int i = 0; i < 100; i++) { byte[] b = new byte[i * 100]; r.nextBytes(b); Assert.assertTrue(Arrays.equals(b, IOUtils.readFully(new ByteArrayInputStream(b)))); } }
|
### Question:
JsonApiUrlBuilder implements UrlBuilder { @Override public String buildUrl(QueryContext queryContext, Object resource) { RegistryEntry entry = moduleRegistry.getResourceRegistry().findEntry(resource); ResourceInformation resourceInformation = entry.getResourceInformation(); Object id = resourceInformation.getId(resource); return buildUrl(queryContext, resourceInformation, id, null); } JsonApiUrlBuilder(ModuleRegistry moduleRegistry); @Override void addPropagatedParameter(String name); @Override Set<String> getPropagatedParameters(); @Override String buildUrl(QueryContext queryContext, Object resource); @Override String buildUrl(QueryContext queryContext, Object resource, QuerySpec querySpec); @Override String buildUrl(QueryContext queryContext, Object resource, QuerySpec querySpec, String relationshipName); @Override String buildUrl(QueryContext queryContext, Object resource, QuerySpec querySpec, String relationshipName, boolean selfLink); @Override String buildUrl(QueryContext queryContext, ResourceInformation resourceInformation); @Override String buildUrl(QueryContext queryContext, ResourceInformation resourceInformation, Object id, QuerySpec querySpec); @Override String buildUrl(QueryContext queryContext, ResourceInformation resourceInformation, Object id, QuerySpec querySpec, String relationshipName); String buildUrl(QueryContext queryContext, ResourceInformation resourceInformation, Object id, QuerySpec querySpec, String relationshipName, boolean selfLink); @Override String filterUrl(String url, QueryContext queryContext); }### Answer:
@Test public void test() { QuerySpec querySpec = new QuerySpec(Task.class); querySpec.addFilter(PathSpec.of("name").filter(FilterOperator.EQ, "bar")); Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("http: Assert.assertEquals("http: }
|
### Question:
MethodCache { public Optional<Method> find(Class<?> clazz, String name, Class<?>... parameters) { MethodCacheKey entry = new MethodCacheKey(clazz, name, parameters); Optional<Method> method = cache.get(entry); if (method == null) { try { method = Optional.of(clazz.getMethod(name, parameters)); } catch (NoSuchMethodException e) { method = Optional.empty(); } cache.put(entry, method); } return method; } Optional<Method> find(Class<?> clazz, String name, Class<?>... parameters); }### Answer:
@Test public void testMethod() { MethodCache cache = new MethodCache(); Optional<Method> method = cache.find(Date.class, "parse", String.class); Assert.assertTrue(method.isPresent()); Assert.assertEquals("parse", method.get().getName()); Optional<Method> method2 = cache.find(Date.class, "parse", String.class); Assert.assertSame(method, method2); }
@Test public void testNonExistingMethod() { MethodCache cache = new MethodCache(); Optional<Method> method = cache.find(Date.class, "doesNotExist", String.class); Assert.assertFalse(method.isPresent()); }
|
### Question:
ResourceDeleteController extends BaseController { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { return jsonPath instanceof ResourcePath && HttpMethod.DELETE.name().equals(method); } @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test public void onValidRequestShouldAcceptIt() { JsonPath jsonPath = pathBuilder.build("tasks/1", queryContext); ResourceDeleteController sut = new ResourceDeleteController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); assertThat(result).isTrue(); }
@Test public void onNonRelationRequestShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("tasks/1/relationships/project", queryContext); ResourceDeleteController sut = new ResourceDeleteController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); assertThat(result).isFalse(); }
|
### Question:
CollectionGetController extends ResourceIncludeField { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { return jsonPath.isCollection() && jsonPath instanceof ResourcePath && HttpMethod.GET.name().equals(method); } @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestBody); Response toResponse(Document document); }### Answer:
@Test public void onGivenRequestCollectionGetShouldAcceptIt() { JsonPath jsonPath = pathBuilder.build("/tasks/", queryContext); CollectionGetController sut = new CollectionGetController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, true); }
@Test public void onGivenRequestCollectionGetShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("/tasks/2", queryContext); CollectionGetController sut = new CollectionGetController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, false); }
|
### Question:
ResourceGetController extends ResourceIncludeField { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { return !jsonPath.isCollection() && jsonPath instanceof ResourcePath && HttpMethod.GET.name().equals(method); } @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestBody); Response toResponse(Document document); }### Answer:
@Test public void onGivenRequestCollectionGetShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("/tasks/", queryContext); ResourceGetController sut = new ResourceGetController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, false); }
@Test public void onGivenRequestResourceGetShouldAcceptIt() { JsonPath jsonPath = pathBuilder.build("/tasks/2", queryContext); ResourceGetController sut = new ResourceGetController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, true); }
@Test public void onMethodMismatchShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("/tasks/2", queryContext); ResourceGetController sut = new ResourceGetController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, "POST"); Assert.assertEquals(result, false); }
|
### Question:
ResourcePostController extends ResourceUpsert { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { boolean nestedOne = jsonPath.getParentField() != null && !jsonPath.getParentField().isCollection(); return (jsonPath.isCollection() || nestedOne) && jsonPath instanceof ResourcePath && HttpMethod.POST.name().equals(method); } @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test public void onGivenRequestCollectionGetShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("/tasks/1", queryContext); ResourcePostController sut = new ResourcePostController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, false); }
@Test public void onGivenRequestResourceGetShouldAcceptIt() { JsonPath jsonPath = pathBuilder.build("/tasks/", queryContext); ResourcePostController sut = new ResourcePostController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, true); }
|
### Question:
ResourcePatchController extends ResourceUpsert { @Override public boolean isAcceptable(JsonPath jsonPath, String method) { return !jsonPath.isCollection() && jsonPath instanceof ResourcePath && HttpMethod.PATCH.name().equals(method); } @Override boolean isAcceptable(JsonPath jsonPath, String method); @Override Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestDocument); }### Answer:
@Test public void onGivenRequestCollectionGetShouldDenyIt() { JsonPath jsonPath = pathBuilder.build("/tasks/", queryContext); ResourcePatchController sut = new ResourcePatchController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, false); }
@Test public void onGivenRequestResourceGetShouldAcceptIt() { JsonPath jsonPath = pathBuilder.build("/tasks/1", queryContext); ResourcePatchController sut = new ResourcePatchController(); sut.init(controllerContext); boolean result = sut.isAcceptable(jsonPath, REQUEST_TYPE); Assert.assertEquals(result, true); }
|
### Question:
PathBuilder { public JsonPath build(String path, QueryContext queryContext) { String[] pathElements = splitPath(path); if (pathElements.length == 0 || (pathElements.length == 1 && "".equals(pathElements[0]))) { LOGGER.debug("requested root path: {}", path); return null; } return parseResourcePath(new LinkedList<>(Arrays.asList(pathElements)), queryContext); } PathBuilder(ResourceRegistry resourceRegistry, TypeParser parser); JsonPath build(String path, QueryContext queryContext); static final String SEPARATOR; static final String RELATIONSHIP_MARK; }### Answer:
@Test public void onEmptyPathReturnsNull() { String path = "/"; JsonPath jsonPath = pathBuilder.build(path, queryContext); assertThat(jsonPath).isNull(); }
@Test public void onNestedResourceInstancePathShouldThrowException() { String path = "/tasks/1/project/2"; expectedException.expect(BadRequestException.class); pathBuilder.build(path, queryContext); }
@Test public void onNonRelationshipFieldShouldThrowException() { String path = "/tasks/1/relationships/name/"; expectedException.expect(BadRequestException.class); pathBuilder.build(path, queryContext); }
@Test public void onRelationshipFieldInRelationshipsShouldThrowException() { String path = "/users/1/relationships/projects"; expectedException.expect(BadRequestException.class); expectedException.expectMessage("projects"); pathBuilder.build(path, queryContext); }
@Test public void onNestedWrongResourceRelationshipPathShouldThrowException() { String path = "/tasks/1/relationships/"; expectedException.expect(BadRequestException.class); pathBuilder.build(path, queryContext); }
@Test public void onRelationshipsPathWithIdShouldThrowException() { String path = "/tasks/1/relationships/project/1"; expectedException.expect(BadRequestException.class); pathBuilder.build(path, queryContext); }
@Test public void onNonExistingFieldShouldThrowException() { String path = "/tasks/1/nonExistingField/"; expectedException.expect(BadRequestException.class); expectedException.expectMessage("nonExistingField"); pathBuilder.build(path, queryContext); }
@Test public void onNonExistingResourceShouldThrowException() { String path = "/nonExistingResource"; Assert.assertNull(pathBuilder.build(path, queryContext)); }
@Test public void onResourceStaringWithRelationshipsShouldThrowException() { String path = "/relationships"; Assert.assertNull(pathBuilder.build(path, queryContext)); }
@Test public void ignoreEntriesNotBeingExposed() { String path = "/notExposed/1/"; JsonPath jsonPath = pathBuilder.build(path, queryContext); Assert.assertNull(jsonPath); }
|
### Question:
TypeParser { public String toString(Object input) { if (input == null) { return null; } Class<?> clazz = input.getClass(); if (String.class.equals(clazz)) { return (String) input; } StringMapper mapper = getMapper(clazz); if (mapper == null) { throw new ParserException(String.format("Cannot map to %s : %s", clazz.getName(), input)); } return mapper.toString(input); } TypeParser(); boolean isEnforceJackson(); void setEnforceJackson(boolean enforceJackson); boolean isUseJackson(); void setUseJackson(boolean useJackson); void addParser(Class<T> clazz, StringParser<T> parser); void addMapper(Class<T> clazz, StringMapper<T> mapper); Iterable<T> parse(Iterable<String> inputs, Class<T> clazz); T parse(String input, Class<T> clazz); String toString(Object input); StringMapper<T> getMapper(Class<T> clazz); boolean supports(Class<?> clazz); void setObjectMapper(ObjectMapper objectMapper); StringParser<T> getParser(Class<T> clazz); final Map<Class, StringParser> parsers; final Map<Class, StringMapper> mappers; }### Answer:
@Test public void checkBooleanToString() { assertThat(sut.toString(Boolean.FALSE)).isEqualTo("false"); assertThat(sut.toString(Boolean.TRUE)).isEqualTo("true"); }
@Test public void checkNullToString() { assertThat(sut.toString(null)).isNull(); }
|
### Question:
TypeParser { public <T> void addParser(Class<T> clazz, StringParser<T> parser) { parsers.put(clazz, parser); } TypeParser(); boolean isEnforceJackson(); void setEnforceJackson(boolean enforceJackson); boolean isUseJackson(); void setUseJackson(boolean useJackson); void addParser(Class<T> clazz, StringParser<T> parser); void addMapper(Class<T> clazz, StringMapper<T> mapper); Iterable<T> parse(Iterable<String> inputs, Class<T> clazz); T parse(String input, Class<T> clazz); String toString(Object input); StringMapper<T> getMapper(Class<T> clazz); boolean supports(Class<?> clazz); void setObjectMapper(ObjectMapper objectMapper); StringParser<T> getParser(Class<T> clazz); final Map<Class, StringParser> parsers; final Map<Class, StringMapper> mappers; }### Answer:
@Test public void testAddParser() { sut.addParser(Boolean.class, new StringParser<Boolean>() { @Override public Boolean parse(String input) { return true; } }); Assert.assertTrue(sut.parse("input", Boolean.class)); }
|
### Question:
SecurityModule implements Module { public void reconfigure(SecurityConfig config) { this.config = config; LOGGER.debug("reconfiguring with {} rules", config.getRules().size()); Map<String, Map<String, ResourcePermission>> newPermissions = new HashMap<>(); for (SecurityRule rule : config.getRules()) { String resourceType = rule.getResourceType(); if (resourceType == null) { Class<?> resourceClass = rule.getResourceClass(); if (resourceClass != null) { resourceType = toType(resourceClass); } } if (resourceType == null) { Collection<RegistryEntry> entries = moduleContext.getResourceRegistry().getEntries(); for (RegistryEntry entry : entries) { String entryResourceType = entry.getResourceInformation().getResourceType(); configureRule(newPermissions, entryResourceType, rule.getRole(), rule.getPermission()); } } else { ResourceRegistry resourceRegistry = moduleContext.getResourceRegistry(); RegistryEntry entry = resourceRegistry.getEntry(resourceType); if (entry == null) { throw new RepositoryNotFoundException(resourceType); } configureRule(newPermissions, resourceType, rule.getRole(), rule.getPermission()); } } this.permissions = newPermissions; } protected SecurityModule(); protected SecurityModule(SecurityConfig config); DataRoomMatcher getDataRoomMatcher(); static SecurityModule newServerModule(SecurityConfig config); static SecurityModule newClientModule(); void setEnabled(final boolean enabled); boolean isEnabled(); void setEnabled(Supplier<Boolean> enabled); @Override String getModuleName(); void reconfigure(SecurityConfig config); SecurityConfig getConfig(); @Override void setupModule(ModuleContext context); boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission); boolean isAllowed(QueryContext queryContext, String resourceType, ResourcePermission permission); ResourcePermission getCallerPermissions(QueryContext queryContext, String resourceType); ResourcePermission getRolePermissions(QueryContext queryContext, String resourceType, String checkedRole); ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass); ResourcePermission getResourcePermission(QueryContext queryContext, String resourceType); boolean isUserInRole(QueryContext queryContext, String role); SecurityProvider getCallerSecurityProvider(); }### Answer:
@Test public void testReconfigure() { QueryContext queryContext = Mockito.mock(QueryContext.class); Assert.assertTrue(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.GET)); Assert.assertFalse(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.DELETE)); Builder builder = SecurityConfig.builder(); builder.permitRole(allowedRule, "projects", ResourcePermission.DELETE); securityModule.reconfigure(builder.build()); Assert.assertFalse(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.GET)); Assert.assertTrue(securityModule.isAllowed(queryContext, Project.class, ResourcePermission.DELETE)); }
|
### Question:
Nullable { public static <T> Nullable<T> ofNullable(T value) { return value == null ? Nullable.empty() : of(value); } private Nullable(); private Nullable(T value); @SuppressWarnings("unchecked") static Nullable<T> empty(); static Nullable<T> of(T value); static Nullable<T> ofNullable(T value); static Nullable<T> nullValue(); boolean isPresent(); T get(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void ofNullable() { Assert.assertEquals(13, Nullable.ofNullable(13).get().intValue()); Assert.assertFalse(Nullable.ofNullable(null).isPresent()); }
|
### Question:
ModuleRegistry { public List<PagingBehavior> getPagingBehaviors() { return this.aggregatedModule.getPagingBehaviors(); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void checkAddingPagingBehavior() { Assert.assertEquals(1, moduleRegistry.getPagingBehaviors().size()); }
|
### Question:
ModuleRegistry { public List<Module> getModules() { return modules; } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void getModules() { Assert.assertEquals(4, moduleRegistry.getModules().size()); }
|
### Question:
ModuleRegistry { public ServiceDiscovery getServiceDiscovery() { PreconditionUtil.verify(serviceDiscovery != null, "serviceDiscovery not yet available"); return serviceDiscovery; } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testGetServiceDiscovery() { Assert.assertEquals(serviceDiscovery, moduleRegistry.getServiceDiscovery()); Assert.assertEquals(serviceDiscovery, testModule.context.getServiceDiscovery()); }
|
### Question:
ModuleRegistry { public ResourceRegistry getResourceRegistry() { if (resourceRegistry == null) { throw new IllegalStateException("resourceRegistry not yet available"); } return resourceRegistry; } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test(expected = IllegalStateException.class) public void testNotInitialized() { moduleRegistry = new ModuleRegistry(); moduleRegistry.getResourceRegistry(); }
@Test public void testGetResourceRegistry() { Assert.assertSame(resourceRegistry, testModule.getContext().getResourceRegistry()); }
|
### Question:
ModuleRegistry { public void init(ObjectMapper objectMapper) { if (resultFactory == null) { resultFactory = new ImmediateResultFactory(); } PreconditionUtil.verifyEquals(InitializedState.NOT_INITIALIZED, initializedState, "already initialized"); this.initializedState = InitializedState.INITIALIZING; this.objectMapper = objectMapper; this.objectMapper.registerModules(getJacksonModules()); typeParser.setObjectMapper(objectMapper); initializeModules(); if (isServer) { applyRepositoryRegistrations(); applyResourceRegistrations(); } ExceptionMapperLookup exceptionMapperLookup = getExceptionMapperLookup(); ExceptionMapperRegistryBuilder mapperRegistryBuilder = new ExceptionMapperRegistryBuilder(); exceptionMapperRegistry = mapperRegistryBuilder.build(exceptionMapperLookup); filterBehaviorProvider = new ResourceFilterDirectoryImpl(aggregatedModule.getResourceFilters(), httpRequestContextProvider, resourceRegistry); this.initializedState = InitializedState.INITIALIZED; } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test(expected = IllegalStateException.class) public void testDuplicateInitialization() { ObjectMapper objectMapper = new ObjectMapper(); moduleRegistry.init(objectMapper); }
|
### Question:
ModuleRegistry { public <T extends Module> Optional<T> getModule(Class<T> clazz) { for (Module module : modules) { if (clazz.isInstance(module)) { return Optional.of((T) module); } } return Optional.empty(); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void checkGetModule() { Module notRegisteredModule = Mockito.mock(Module.class); Assert.assertNotNull(moduleRegistry.getModule(TestModule.class).get()); Assert.assertFalse(moduleRegistry.getModule(notRegisteredModule.getClass()).isPresent()); }
|
### Question:
ModuleRegistry { public ExceptionMapperLookup getExceptionMapperLookup() { return new CombinedExceptionMapperLookup(aggregatedModule.getExceptionMapperLookups()); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testExceptionMappers() { ExceptionMapperLookup exceptionMapperLookup = moduleRegistry.getExceptionMapperLookup(); List<ExceptionMapper> exceptionMappers = exceptionMapperLookup.getExceptionMappers(); Set<Class<?>> classes = new HashSet<>(); for (ExceptionMapper exceptionMapper : exceptionMappers) { classes.add(exceptionMapper.getClass()); } Assert.assertTrue(classes.contains(IllegalStateExceptionMapper.class)); Assert.assertTrue(classes.contains(SomeIllegalStateExceptionMapper.class)); }
|
### Question:
ModuleRegistry { public void addModule(Module module) { checkState(InitializedState.NOT_INITIALIZED, InitializedState.NOT_INITIALIZED); LOGGER.debug("adding module {}", module); module.setupModule(new ModuleContextImpl(module)); modules.add(module); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test(expected = IllegalStateException.class) public void testModuleChangeAfterAddModule() { SimpleModule module = new SimpleModule("test2"); moduleRegistry.addModule(module); module.addFilter(new TestFilter()); }
|
### Question:
ModuleRegistry { public ResourceLookup getResourceLookup() { checkState(InitializedState.INITIALIZING, InitializedState.INITIALIZED); return new MultiResourceLookup(aggregatedModule.getResourceLookups()); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testResourceLookup() { ResourceLookup resourceLookup = moduleRegistry.getResourceLookup(); Assert.assertFalse(resourceLookup.getResourceClasses().contains(Object.class)); Assert.assertFalse(resourceLookup.getResourceClasses().contains(String.class)); Assert.assertTrue(resourceLookup.getResourceClasses().contains(TestResource.class)); }
|
### Question:
ModuleRegistry { public List<com.fasterxml.jackson.databind.Module> getJacksonModules() { return aggregatedModule.getJacksonModules(); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testJacksonModule() { List<com.fasterxml.jackson.databind.Module> jacksonModules = moduleRegistry.getJacksonModules(); Assert.assertEquals(1, jacksonModules.size()); com.fasterxml.jackson.databind.Module jacksonModule = jacksonModules.get(0); Assert.assertEquals("test", jacksonModule.getModuleName()); }
|
### Question:
ModuleRegistry { public List<DocumentFilter> getFilters() { return Prioritizable.prioritze(aggregatedModule.getFilters()); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testFilter() { List<DocumentFilter> filters = moduleRegistry.getFilters(); Assert.assertEquals(1, filters.size()); }
|
### Question:
ModuleRegistry { public List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories() { return aggregatedModule.getRepositoryDecoratorFactories(); } ModuleRegistry(); ModuleRegistry(boolean isServer); QueryAdapterBuilder getQueryAdapterBuilder(); @Deprecated void setControllerRegistry(ControllerRegistry controllerRegistry); @Deprecated void setQueryAdapterBuilder(QueryAdapterBuilder queryAdapterBuilder); ControllerRegistry getControllerRegistry(); ObjectMapper getObjectMapper(); void setDocumentMapper(DocumentMapper documentMapper); DocumentMappingConfig getDocumentMappingConfig(); List<NamingStrategy> getNamingStrategies(); DefaultInformationBuilder getInformationBuilder(); List<ResourceModificationFilter> getResourceModificationFilters(); void setServerInfo(Map<String, String> serverInfo); Map<String, String> getServerInfo(); ResultFactory getResultFactory(); Collection<Object> getRepositories(); void setResultFactory(ResultFactory resultFactory); void addModule(Module module); UrlBuilder getUrlBuilder(); void addPagingBehavior(PagingBehavior pagingBehavior); void addAllPagingBehaviors(List<PagingBehavior> pagingBehaviors); List<PagingBehavior> getPagingBehaviors(); List<ResourceFieldContributor> getResourceFieldContributors(); ResourceRegistry getResourceRegistry(); void setResourceRegistry(ResourceRegistry resourceRegistry); void setRequestDispatcher(RequestDispatcher requestDispatcher); List<com.fasterxml.jackson.databind.Module> getJacksonModules(); ResourceInformationProvider getResourceInformationBuilder(); RepositoryInformationProvider getRepositoryInformationBuilder(); ResourceLookup getResourceLookup(); List<HttpRequestProcessor> getHttpRequestProcessors(); SecurityProvider getSecurityProvider(); List<SecurityProvider> getSecurityProviders(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); void init(ObjectMapper objectMapper); HttpRequestContextProvider getHttpRequestContextProvider(); @Deprecated // not official API, to be moved at some point void initOpposites(boolean allowMissing); List<DocumentFilter> getFilters(); List<RepositoryFilter> getRepositoryFilters(); List<RepositoryDecoratorFactory> getRepositoryDecoratorFactories(); ExceptionMapperLookup getExceptionMapperLookup(); List<Module> getModules(); Optional<T> getModule(Class<T> clazz); TypeParser getTypeParser(); RepositoryInformation getRepositoryInformation(Object repository); ModuleContext getContext(); ExceptionMapperRegistry getExceptionMapperRegistry(); Map<String, ResourceRegistryPart> getRegistryParts(); List<RegistryEntry> getRegistryEntries(); void setObjectMapper(ObjectMapper objectMapper); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); QuerySpecUrlMapper getUrlMapper(); void setUrlMapper(QuerySpecUrlMapper urlMapper); PagingBehavior findPagingBehavior(Class<? extends PagingSpec> pagingSpecType); List<HttpStatusBehavior> getHttpStatusProviders(); HttpStatusBehavior getHttpStatusProvider(); }### Answer:
@Test public void testDecorators() { List<RepositoryDecoratorFactory> decorators = moduleRegistry.getRepositoryDecoratorFactories(); Assert.assertEquals(1, decorators.size()); RegistryEntry entry = this.resourceRegistry.getEntry(Schedule.class); Object resourceRepository = entry.getResourceRepository().getImplementation(); Assert.assertNotNull(resourceRepository); Assert.assertTrue(resourceRepository instanceof ScheduleRepository); Assert.assertTrue(resourceRepository instanceof DecoratedScheduleRepository); }
|
### Question:
SimpleModule implements Module { @Override public String getModuleName() { return moduleName; } SimpleModule(String moduleName); @Override String getModuleName(); @Override void setupModule(ModuleContext context); void addResourceInformationProvider(ResourceInformationProvider resourceInformationProvider); void addRepositoryInformationBuilder(RepositoryInformationProvider repositoryInformationProvider); void addExceptionMapperLookup(ExceptionMapperLookup exceptionMapperLookup); void addExceptionMapper(@SuppressWarnings("rawtypes") ExceptionMapper exceptionMapper); Map<String, ResourceRegistryPart> getRegistryParts(); void addExtension(ModuleExtension extension); void addFilter(DocumentFilter filter); void addRepositoryFilter(RepositoryFilter filter); void addResourceFilter(ResourceFilter filter); void addHttpStatusBehavior(HttpStatusBehavior httpStatusBehavior); void addResourceFieldContributor(ResourceFieldContributor resourceFieldContributor); void addResourceModificationFilter(ResourceModificationFilter filter); void addRepositoryDecoratorFactory(RepositoryDecoratorFactory decorator); void addSecurityProvider(SecurityProvider securityProvider); void addJacksonModule(com.fasterxml.jackson.databind.Module module); void addPagingBehavior(PagingBehavior pagingBehavior); List<PagingBehavior> getPagingBehaviors(); void addResourceLookup(ResourceLookup resourceLookup); void addRepository(Object repository); List<Object> getRepositories(); List<ExceptionMapperLookup> getExceptionMapperLookups(); List<SecurityProvider> getSecurityProviders(); List<HttpStatusBehavior> getHttpStatusBehaviors(); void addHttpRequestProcessor(HttpRequestProcessor httpRequestProcessor); List<HttpRequestProcessor> getHttpRequestProcessors(); void addRepositoryAdapterFactory(RepositoryAdapterFactory repositoryAdapterFactory); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); void addNamingStrategy(NamingStrategy namingStrategy); List<NamingStrategy> getNamingStrategies(); void addRegistryPart(String prefix, ResourceRegistryPart part); List<RegistryEntry> getRegistryEntries(); void addRegistryEntry(RegistryEntry entry); }### Answer:
@Test public void testGetModuleName() { Assert.assertEquals("simple", module.getModuleName()); }
|
### Question:
SimpleModule implements Module { public void addPagingBehavior(PagingBehavior pagingBehavior) { checkInitialized(); boolean behaviorTypeAdded = pagingBehaviors .stream() .anyMatch(pbh -> pbh.getClass().equals(pagingBehavior.getClass())); if (!behaviorTypeAdded) { pagingBehaviors.add(pagingBehavior); } else { throw new IllegalArgumentException( "PagingBehavior of same type already added. Type:" + pagingBehavior.getClass().getSimpleName()); } } SimpleModule(String moduleName); @Override String getModuleName(); @Override void setupModule(ModuleContext context); void addResourceInformationProvider(ResourceInformationProvider resourceInformationProvider); void addRepositoryInformationBuilder(RepositoryInformationProvider repositoryInformationProvider); void addExceptionMapperLookup(ExceptionMapperLookup exceptionMapperLookup); void addExceptionMapper(@SuppressWarnings("rawtypes") ExceptionMapper exceptionMapper); Map<String, ResourceRegistryPart> getRegistryParts(); void addExtension(ModuleExtension extension); void addFilter(DocumentFilter filter); void addRepositoryFilter(RepositoryFilter filter); void addResourceFilter(ResourceFilter filter); void addHttpStatusBehavior(HttpStatusBehavior httpStatusBehavior); void addResourceFieldContributor(ResourceFieldContributor resourceFieldContributor); void addResourceModificationFilter(ResourceModificationFilter filter); void addRepositoryDecoratorFactory(RepositoryDecoratorFactory decorator); void addSecurityProvider(SecurityProvider securityProvider); void addJacksonModule(com.fasterxml.jackson.databind.Module module); void addPagingBehavior(PagingBehavior pagingBehavior); List<PagingBehavior> getPagingBehaviors(); void addResourceLookup(ResourceLookup resourceLookup); void addRepository(Object repository); List<Object> getRepositories(); List<ExceptionMapperLookup> getExceptionMapperLookups(); List<SecurityProvider> getSecurityProviders(); List<HttpStatusBehavior> getHttpStatusBehaviors(); void addHttpRequestProcessor(HttpRequestProcessor httpRequestProcessor); List<HttpRequestProcessor> getHttpRequestProcessors(); void addRepositoryAdapterFactory(RepositoryAdapterFactory repositoryAdapterFactory); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); void addNamingStrategy(NamingStrategy namingStrategy); List<NamingStrategy> getNamingStrategies(); void addRegistryPart(String prefix, ResourceRegistryPart part); List<RegistryEntry> getRegistryEntries(); void addRegistryEntry(RegistryEntry entry); }### Answer:
@Test public void testDuplicatePagingBehaviorRegistration() { module.addPagingBehavior(Mockito.mock(OffsetLimitPagingBehavior.class)); try { module.addPagingBehavior(Mockito.mock(OffsetLimitPagingBehavior.class)); Assert.fail("IllegalArgumentException expected, paging was added already"); } catch (IllegalArgumentException e) { } }
|
### Question:
SimpleModule implements Module { public void addRepository(Object repository) { checkInitialized(); repositories.add(repository); } SimpleModule(String moduleName); @Override String getModuleName(); @Override void setupModule(ModuleContext context); void addResourceInformationProvider(ResourceInformationProvider resourceInformationProvider); void addRepositoryInformationBuilder(RepositoryInformationProvider repositoryInformationProvider); void addExceptionMapperLookup(ExceptionMapperLookup exceptionMapperLookup); void addExceptionMapper(@SuppressWarnings("rawtypes") ExceptionMapper exceptionMapper); Map<String, ResourceRegistryPart> getRegistryParts(); void addExtension(ModuleExtension extension); void addFilter(DocumentFilter filter); void addRepositoryFilter(RepositoryFilter filter); void addResourceFilter(ResourceFilter filter); void addHttpStatusBehavior(HttpStatusBehavior httpStatusBehavior); void addResourceFieldContributor(ResourceFieldContributor resourceFieldContributor); void addResourceModificationFilter(ResourceModificationFilter filter); void addRepositoryDecoratorFactory(RepositoryDecoratorFactory decorator); void addSecurityProvider(SecurityProvider securityProvider); void addJacksonModule(com.fasterxml.jackson.databind.Module module); void addPagingBehavior(PagingBehavior pagingBehavior); List<PagingBehavior> getPagingBehaviors(); void addResourceLookup(ResourceLookup resourceLookup); void addRepository(Object repository); List<Object> getRepositories(); List<ExceptionMapperLookup> getExceptionMapperLookups(); List<SecurityProvider> getSecurityProviders(); List<HttpStatusBehavior> getHttpStatusBehaviors(); void addHttpRequestProcessor(HttpRequestProcessor httpRequestProcessor); List<HttpRequestProcessor> getHttpRequestProcessors(); void addRepositoryAdapterFactory(RepositoryAdapterFactory repositoryAdapterFactory); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); void addNamingStrategy(NamingStrategy namingStrategy); List<NamingStrategy> getNamingStrategies(); void addRegistryPart(String prefix, ResourceRegistryPart part); List<RegistryEntry> getRegistryEntries(); void addRegistryEntry(RegistryEntry entry); }### Answer:
@Test public void testAddRepository() { TestRelationshipRepository repository = new TestRelationshipRepository(); module.addRepository(repository); Assert.assertEquals(1, module.getRepositories().size()); module.setupModule(context); Assert.assertEquals(0, context.numResourceInformationBuilds); Assert.assertEquals(0, context.numResourceLookups); Assert.assertEquals(0, context.numFilters); Assert.assertEquals(0, context.numJacksonModules); Assert.assertEquals(1, context.numRepositories); Assert.assertEquals(0, context.numExceptionMapperLookup); }
|
### Question:
SimpleModule implements Module { public void addExceptionMapper(@SuppressWarnings("rawtypes") ExceptionMapper exceptionMapper) { checkInitialized(); ExceptionMapperLookup exceptionMapperLookup = new CollectionExceptionMapperLookup(exceptionMapper); exceptionMapperLookups.add(exceptionMapperLookup); } SimpleModule(String moduleName); @Override String getModuleName(); @Override void setupModule(ModuleContext context); void addResourceInformationProvider(ResourceInformationProvider resourceInformationProvider); void addRepositoryInformationBuilder(RepositoryInformationProvider repositoryInformationProvider); void addExceptionMapperLookup(ExceptionMapperLookup exceptionMapperLookup); void addExceptionMapper(@SuppressWarnings("rawtypes") ExceptionMapper exceptionMapper); Map<String, ResourceRegistryPart> getRegistryParts(); void addExtension(ModuleExtension extension); void addFilter(DocumentFilter filter); void addRepositoryFilter(RepositoryFilter filter); void addResourceFilter(ResourceFilter filter); void addHttpStatusBehavior(HttpStatusBehavior httpStatusBehavior); void addResourceFieldContributor(ResourceFieldContributor resourceFieldContributor); void addResourceModificationFilter(ResourceModificationFilter filter); void addRepositoryDecoratorFactory(RepositoryDecoratorFactory decorator); void addSecurityProvider(SecurityProvider securityProvider); void addJacksonModule(com.fasterxml.jackson.databind.Module module); void addPagingBehavior(PagingBehavior pagingBehavior); List<PagingBehavior> getPagingBehaviors(); void addResourceLookup(ResourceLookup resourceLookup); void addRepository(Object repository); List<Object> getRepositories(); List<ExceptionMapperLookup> getExceptionMapperLookups(); List<SecurityProvider> getSecurityProviders(); List<HttpStatusBehavior> getHttpStatusBehaviors(); void addHttpRequestProcessor(HttpRequestProcessor httpRequestProcessor); List<HttpRequestProcessor> getHttpRequestProcessors(); void addRepositoryAdapterFactory(RepositoryAdapterFactory repositoryAdapterFactory); List<RepositoryAdapterFactory> getRepositoryAdapterFactories(); void addNamingStrategy(NamingStrategy namingStrategy); List<NamingStrategy> getNamingStrategies(); void addRegistryPart(String prefix, ResourceRegistryPart part); List<RegistryEntry> getRegistryEntries(); void addRegistryEntry(RegistryEntry entry); }### Answer:
@Test public void testAddExceptionMapper() { module.addExceptionMapper(new IllegalStateExceptionMapper()); Assert.assertEquals(1, module.getExceptionMapperLookups().size()); module.setupModule(context); Assert.assertEquals(0, context.numResourceInformationBuilds); Assert.assertEquals(0, context.numResourceLookups); Assert.assertEquals(0, context.numFilters); Assert.assertEquals(0, context.numJacksonModules); Assert.assertEquals(0, context.numRepositories); Assert.assertEquals(1, context.numExceptionMapperLookup); }
|
### Question:
DefaultServiceDiscoveryFactory implements ServiceDiscoveryFactory { @Override public ServiceDiscovery getInstance() { ServiceLoader<ServiceDiscovery> loader = ServiceLoader.load(ServiceDiscovery.class); Iterator<ServiceDiscovery> iterator = loader.iterator(); if (iterator.hasNext()) { ServiceDiscovery discovery = iterator.next(); PreconditionUtil.verify(!iterator.hasNext(), "expected unique ServiceDiscovery implementation, got: %s", loader); return discovery; } return new EmptyServiceDiscovery(); } @Override ServiceDiscovery getInstance(); }### Answer:
@Test public void test() { DefaultServiceDiscoveryFactory factory = new DefaultServiceDiscoveryFactory(); ServiceDiscovery instance = factory.getInstance(); Assert.assertTrue(instance instanceof TestServiceDiscovery); }
|
### Question:
CrnkBoot { public void setObjectMapper(ObjectMapper objectMapper) { checkNotConfiguredYet(); PreconditionUtil.verify(this.objectMapper == null, "ObjectMapper already set"); this.objectMapper = objectMapper; } void putServerInfo(String key, String value); void setServiceDiscoveryFactory(ServiceDiscoveryFactory factory); void addModule(Module module); void setServiceUrlProvider(ServiceUrlProvider serviceUrlProvider); void boot(); ExceptionMapperRegistry getExceptionMapperRegistry(); DocumentMapper getDocumentMapper(); UrlBuilder getUrlBuilder(); HttpRequestDispatcherImpl getRequestDispatcher(); ResourceRegistry getResourceRegistry(); ObjectMapper getObjectMapper(); void setObjectMapper(ObjectMapper objectMapper); PropertiesProvider getPropertiesProvider(); void setPropertiesProvider(PropertiesProvider propertiesProvider); String getWebPathPrefix(); ServiceDiscovery getServiceDiscovery(); void setServiceDiscovery(ServiceDiscovery serviceDiscovery); void setDefaultPageLimit(Long defaultPageLimit); void setMaxPageLimit(Long maxPageLimit); void setAllowUnknownAttributes(); void setAllowUnknownParameters(); ModuleRegistry getModuleRegistry(); void setUrlMapper(QuerySpecUrlMapper urlMapper); boolean isNullDataResponseEnabled(); ServiceUrlProvider getServiceUrlProvider(); List<PagingBehavior> getPagingBehaviors(); ControllerRegistry getControllerRegistry(); QueryAdapterBuilder getQueryAdapterBuilder(); CoreModule getCoreModule(); QuerySpecUrlMapper getUrlMapper(); void setWebPathPrefix(String webPathPrefix); }### Answer:
@Test public void setObjectMapper() { CrnkBoot boot = new CrnkBoot(); ObjectMapper mapper = new ObjectMapper(); boot.setObjectMapper(mapper); Assert.assertSame(mapper, boot.getObjectMapper()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.