src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
NumberSizePagingBehavior extends PagingBehaviorBase<NumberSizePagingSpec> { @Override public boolean isRequired(final NumberSizePagingSpec pagingSpec) { return pagingSpec.getNumber() != 1 || pagingSpec.getSize() != null; } NumberSizePagingBehavior(); @Override boolean supports(Class<? extends PagingSpec> pagingSpecType...
@Test public void testIsPagingRequired() { PagingBehavior pagingBehavior = new NumberSizePagingBehavior(); assertTrue(pagingBehavior.isRequired(new NumberSizePagingSpec(2, null))); assertTrue(pagingBehavior.isRequired(new NumberSizePagingSpec(1, 30))); assertFalse(pagingBehavior.isRequired(new NumberSizePagingSpec(1, n...
NumberSizePagingBehavior extends PagingBehaviorBase<NumberSizePagingSpec> { @Override public void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder) { Long totalCount = getTotalCount(resources); Boolean isNextPageA...
@Test public void testBuild() { PagingBehavior pagingBehavior = new NumberSizePagingBehavior(); NumberSizePagingSpec pagingSpec = new NumberSizePagingSpec(1, 10); ModuleRegistry moduleRegistry = new ModuleRegistry(); ResourceRegistry resourceRegistry = new ResourceRegistryImpl(new DefaultResourceRegistryPart(), moduleR...
OffsetLimitPagingBehavior extends PagingBehaviorBase<OffsetLimitPagingSpec> { @Override public Map<String, Set<String>> serialize(final OffsetLimitPagingSpec pagingSpec, final String resourceType) { Map<String, Set<String>> values = new HashMap<>(); if (pagingSpec.getOffset() != 0) { values.put(String.format("page[%s]"...
@Test public void testSerializeDefault() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); Map<String, Set<String>> result = pagingBehavior.serialize(new OffsetLimitPagingSpec(), "tasks"); assertFalse(result.containsKey("page[offset]")); assertFalse(result.containsKey("page[limit]")); assert...
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getLeafBean() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError(ResourceRegi...
@Test(expected = UnsupportedOperationException.class) public void getLeafBean() { violation.getLeafBean(); }
OffsetLimitPagingBehavior extends PagingBehaviorBase<OffsetLimitPagingSpec> { @Override public OffsetLimitPagingSpec deserialize(final Map<String, Set<String>> parameters) { OffsetLimitPagingSpec result = createDefaultPagingSpec(); for (Map.Entry<String, Set<String>> param : parameters.entrySet()) { if (OFFSET_PARAMETE...
@Test public void testDeserializeDefaultWithNoParameters() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec result = pagingBehavior.deserialize(Collections.emptyMap()); assertEquals(new OffsetLimitPagingSpec(0L, null), result); } @Test public void testDeserializeDefaul...
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getInvalidValue() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError(Resource...
@Test(expected = UnsupportedOperationException.class) public void getInvalidValue() { violation.getInvalidValue(); }
OffsetLimitPagingBehavior extends PagingBehaviorBase<OffsetLimitPagingSpec> { @Override public boolean isRequired(final OffsetLimitPagingSpec pagingSpec) { return pagingSpec.getOffset() != 0 || pagingSpec.getLimit() != null; } OffsetLimitPagingBehavior(); @Override Map<String, Set<String>> serialize(final OffsetLimitPa...
@Test public void testIsPagingRequired() { PagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); assertTrue(pagingBehavior.isRequired(new OffsetLimitPagingSpec(1L, null))); assertTrue(pagingBehavior.isRequired(new OffsetLimitPagingSpec(0L, 30L))); } @Test public void testIsNotRequired() { assertFalse(new Off...
OffsetLimitPagingBehavior extends PagingBehaviorBase<OffsetLimitPagingSpec> { @Override public void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder) { Long totalCount = getTotalCount(resources); Boolean isNextPag...
@Test public void testBuild() { PagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec pagingSpec = new OffsetLimitPagingSpec(0L, 10L); ModuleRegistry moduleRegistry = new ModuleRegistry(); ResourceRegistry resourceRegistry = new ResourceRegistryImpl(new DefaultResourceRegistryPart(), mo...
IncludeRelationSpec extends IncludeSpec { @Override public IncludeRelationSpec clone() { return new IncludeRelationSpec(path.clone()); } IncludeRelationSpec(List<String> path); IncludeRelationSpec(PathSpec path); @Override IncludeRelationSpec clone(); }
@Test public void testClone() { IncludeRelationSpec spec = new IncludeRelationSpec(Arrays.asList("sortAttr")); IncludeRelationSpec duplicate = spec.clone(); Assert.assertNotSame(spec, duplicate); Assert.assertNotSame(spec.getAttributePath(), duplicate.getAttributePath()); }
IncludeFieldSpec extends IncludeSpec { public IncludeFieldSpec clone() { return new IncludeFieldSpec(path.clone()); } IncludeFieldSpec(List<String> path); IncludeFieldSpec(PathSpec path); IncludeFieldSpec clone(); }
@Test public void testClone() { IncludeFieldSpec spec = new IncludeFieldSpec(Arrays.asList("sortAttr")); IncludeFieldSpec duplicate = spec.clone(); Assert.assertNotSame(spec, duplicate); Assert.assertNotSame(spec.getAttributePath(), duplicate.getAttributePath()); }
QuerySpec { public QuerySpec getOrCreateQuerySpec(String resourceType) { return getOrCreateQuerySpec(null, resourceType); } QuerySpec(Class<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QueryS...
@Test(expected = IllegalArgumentException.class) public void testCannotGetAndCreateWithResourceClass() { new QuerySpec(Task.class).getOrCreateQuerySpec(Resource.class); }
QuerySpec { public Class<?> getResourceClass() { return resourceClass; } QuerySpec(Class<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QuerySpecVisitor visitor); String getResourceType(); Clas...
@Test public void testResourceClassIgnored() { QuerySpec querySpec = new QuerySpec(Resource.class, "tasks"); assertNull(querySpec.getResourceClass()); }
QuerySpec { public QuerySpec clone() { QuerySpec copy = new QuerySpec(resourceClass, resourceType); if (pagingSpec != null) { copy.pagingSpec = pagingSpec.clone(); } for (IncludeFieldSpec includedField : includedFields) { copy.includedFields.add(includedField.clone()); } for (IncludeRelationSpec includeRelationSpec : i...
@Test public void testClone() { FilterSpec filterSpec = new FilterSpec(Arrays.asList("filterAttr"), FilterOperator.EQ, "test"); SortSpec sortSpec = new SortSpec(Arrays.asList("sortAttr"), Direction.ASC); QuerySpec spec = new QuerySpec(Project.class); spec.addFilter(filterSpec); spec.addSort(sortSpec); spec.includeField...
QuerySpec { public void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec) { if (relatedResourceClass.equals(resourceClass)) { throw new IllegalArgumentException("cannot set related spec with root resourceClass"); } classRelatedSpecs.put(relatedResourceClass, relatedSpec); } QuerySpec(Class<?> resourc...
@Test(expected = IllegalArgumentException.class) public void putRelatedSpecShouldFailIfClassMatchesRoot() { QuerySpec spec = new QuerySpec(Project.class); QuerySpec relatedSpec = new QuerySpec(Task.class); spec.putRelatedSpec(Project.class, relatedSpec); }
QuerySpec { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } QuerySpec other = (QuerySpec) obj; return CompareUtils.isEquals(filters, other.filters) && CompareUtils.isEquals(includedFields, other.includedFields) && Compare...
@Test public void testEquals() { QuerySpec spec1 = new QuerySpec(Task.class); spec1.addFilter(new FilterSpec(Arrays.asList("filterAttr"), FilterOperator.EQ, "test")); spec1.addSort(new SortSpec(Arrays.asList("sortAttr"), Direction.ASC)); spec1.includeField(Arrays.asList("includedField")); spec1.includeRelation(Arrays.a...
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object[] getExecutableParameters() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromErro...
@Test(expected = UnsupportedOperationException.class) public void getExecutableParameters() { violation.getExecutableParameters(); }
QuerySpec { public void accept(QuerySpecVisitor visitor) { if (visitor.visitStart(this)) { visitFilters(visitor, filters); for (SortSpec spec : sort) { if (visitor.visitSort(spec)) { visitor.visitPath(spec.getPath()); } } for (IncludeFieldSpec spec : includedFields) { if (visitor.visitField(spec)) { visitor.visitPath(s...
@Test public void testVisitorWithFilterAbort() { QuerySpec spec = createTestQueySpec(); QuerySpecVisitorBase visitor = Mockito.mock(QuerySpecVisitorBase.class); Mockito.when(visitor.visitStart(Mockito.any(QuerySpec.class))).thenReturn(true); Mockito.when(visitor.visitFilterStart(Mockito.any(FilterSpec.class))).thenRetu...
SortSpec extends AbstractPathSpec implements Serializable { public Direction getDirection() { return direction; } SortSpec(List<String> path, Direction direction); SortSpec(PathSpec path, Direction direction); static SortSpec asc(List<String> expression); static SortSpec desc(List<String> attributeName); Direction get...
@Test public void testBasic() { SortSpec spec = new SortSpec(Arrays.asList("name"), Direction.ASC); Assert.assertEquals(Direction.ASC, spec.getDirection()); Assert.assertEquals(Arrays.asList("name"), spec.getAttributePath()); }
SortSpec extends AbstractPathSpec implements Serializable { @Override public String toString() { StringBuilder b = new StringBuilder(); b.append(path.toString()); b.append(' '); b.append(direction); return b.toString(); } SortSpec(List<String> path, Direction direction); SortSpec(PathSpec path, Direction direction); s...
@Test public void testToString() { Assert.assertEquals("name ASC", new SortSpec(Arrays.asList("name"), Direction.ASC).toString()); Assert.assertEquals("name1.name2 ASC", new SortSpec(Arrays.asList("name1", "name2"), Direction.ASC).toString()); Assert.assertEquals("name DESC", new SortSpec(Arrays.asList("name"), Directi...
SortSpec extends AbstractPathSpec implements Serializable { public SortSpec reverse() { return new SortSpec(path, direction == Direction.ASC ? Direction.DESC : Direction.ASC); } SortSpec(List<String> path, Direction direction); SortSpec(PathSpec path, Direction direction); static SortSpec asc(List<String> expression);...
@Test public void testReverse() { SortSpec specAsc = new SortSpec(Arrays.asList("name1"), Direction.ASC); SortSpec specDesc = new SortSpec(Arrays.asList("name1"), Direction.DESC); Assert.assertEquals(specDesc, specAsc.reverse()); Assert.assertEquals(specAsc, specDesc.reverse()); }
SortSpec extends AbstractPathSpec implements Serializable { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } SortSpec other = (SortSpec) obj; return direction == other.direction; } SortSpec(List<String> path, Direction direction); SortSpec(PathSp...
@Test public void testEquals() { EqualsVerifier.forClass(SortSpec.class).usingGetClass().suppress(Warning.NONFINAL_FIELDS).verify(); SortSpec spec1 = new SortSpec(Arrays.asList("name1"), Direction.ASC); SortSpec spec2 = new SortSpec(Arrays.asList("name1"), Direction.ASC); SortSpec spec3 = new SortSpec(Arrays.asList("na...
SortSpec extends AbstractPathSpec implements Serializable { @Override public SortSpec clone() { return new SortSpec(path.clone(), direction); } SortSpec(List<String> path, Direction direction); SortSpec(PathSpec path, Direction direction); static SortSpec asc(List<String> expression); static SortSpec desc(List<String>...
@Test public void testClone() { SortSpec sortSpec = new SortSpec(Arrays.asList("sortAttr"), Direction.ASC); SortSpec duplicate = sortSpec.clone(); Assert.assertNotSame(sortSpec, duplicate); Assert.assertNotSame(sortSpec.getAttributePath(), duplicate.getAttributePath()); Assert.assertSame(sortSpec.getDirection(), duplic...
DefaultPagedMetaInformation implements PagedMetaInformation { @Override public void setTotalResourceCount(Long totalResourceCount) { this.totalResourceCount = totalResourceCount; } @Override Long getTotalResourceCount(); @Override void setTotalResourceCount(Long totalResourceCount); }
@Test public void nonNullMustBeSerialized() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writerFor(DefaultPagedMetaInformation.class); DefaultPagedMetaInformation metaInformation = new DefaultPagedMetaInformation(); metaInformation.setTotalResourceCount(12L); S...
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getExecutableReturnValue() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolationImpl fromError...
@Test(expected = UnsupportedOperationException.class) public void getExecutableReturnValue() { violation.getExecutableReturnValue(); }
SecurityModule implements Module { public ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass) { String resourceType = toType(resourceClass); return getResourcePermission(queryContext, resourceType); } protected SecurityModule(); protected SecurityModule(SecurityConfig config); ...
@Test public void testBlackListingOfUnknownResources() { QueryContext queryContext = Mockito.mock(QueryContext.class); Assert.assertEquals(ResourcePermission.EMPTY, securityModule.getResourcePermission(queryContext, "doesNotExist")); }
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 r...
@Test(expected = MethodNotAllowedException.class) public void save() { repo.save(null); }
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...
@Test(expected = MethodNotAllowedException.class) public void create() { repo.create(null); }
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); @Over...
@Test(expected = MethodNotAllowedException.class) public void delete() { repo.delete(null); }
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); @O...
@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); }
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...
@Test(expected = UnsupportedOperationException.class) public void getSourceResourceClass() { repo.getSourceResourceClass(); }
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...
@Test(expected = UnsupportedOperationException.class) public void getTargetResourceClass() { repo.getTargetResourceClass(); }
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();...
@Test(expected = MethodNotAllowedException.class) public void findOneTarget() { repo.findOneTarget(null, null, null); }
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> getTarget...
@Test(expected = MethodNotAllowedException.class) public void findManyTargets() { repo.findManyTargets(null, null, null); }
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...
@Test(expected = MethodNotAllowedException.class) public void setRelation() { repo.setRelation(null, null, null); }
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> getTargetResourceClas...
@Test(expected = MethodNotAllowedException.class) public void setRelations() { repo.setRelations(null, null, null); }
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, ...
@Test public void unwrap() { Assert.assertNull(violation.unwrap(String.class)); }
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> getTargetResourceClas...
@Test(expected = MethodNotAllowedException.class) public void addRelations() { repo.addRelations(null, null, null); }
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> getTargetResourceC...
@Test(expected = MethodNotAllowedException.class) public void removeRelations() { repo.removeRelations(null, null, null); }
RelationshipMatcher { public boolean matches(ResourceField field) { return rules.stream().filter(it -> it.matches(field)).findAny().isPresent(); } RelationshipMatcherRule rule(); boolean matches(ResourceField field); }
@Test public void checkEmpty() { Assert.assertFalse(new RelationshipMatcher().matches(field)); }
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....
@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 Relatio...
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...
@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.as...
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 T...
@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.hasThreadCo...
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> functi...
@Test(expected = UnsupportedOperationException.class) public void subscribeNotSupported() { Result<Object> result = resultFactory.just(new Object()); result.subscribe(null, null); }
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 Resu...
@Test(expected = UnsupportedOperationException.class) public void onErrorResumeNotSupported() { Result<Object> result = resultFactory.just(new Object()); result.onErrorResume(null); }
AbstractDocumentFilter implements DocumentFilter { @Override public Response filter(DocumentFilterContext context, DocumentFilterChain chain) { return chain.doFilter(context); } @Override Response filter(DocumentFilterContext context, DocumentFilterChain chain); }
@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...
DefaultResourceRegistryPart extends ResourceRegistryPartBase { @Override public RegistryEntry addEntry(RegistryEntry entry) { ResourceInformation resourceInformation = entry.getResourceInformation(); Type implementationType = resourceInformation.getImplementationType(); String resourceType = resourceInformation.getReso...
@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, ...
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(child...
@Test(expected = IllegalStateException.class) public void testDuplicatePartThrowsException() { HierarchicalResourceRegistryPart part = new HierarchicalResourceRegistryPart(); part.putPart("", new DefaultResourceRegistryPart()); part.putPart("", new DefaultResourceRegistryPart()); }
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++; }...
@Test public void shouldReturnIntegerMAXForNotRelatedClassesFromException() { int distance = exceptionMapperRegistry.getDistanceBetweenExceptions(Exception.class, SomeException.class); assertThat(distance).isEqualTo(Integer.MAX_VALUE); } @Test public void shouldReturn0DistanceBetweenSameClassFromException() { int dista...
ExceptionMapperRegistry { public Optional<ExceptionMapper> findMapperFor(Class<? extends Throwable> exceptionClass) { int currentDistance = Integer.MAX_VALUE; ExceptionMapper closestExceptionMapper = null; for (ExceptionMapperType mapperType : exceptionMappers) { int tempDistance = getDistanceBetweenExceptions(exceptio...
@Test public void shouldNotFindMapperIfSuperClassIsNotMappedFromException() { Optional<ExceptionMapper> mapper = exceptionMapperRegistry.findMapperFor(RuntimeException.class); assertThat(mapper.isPresent()).isFalse(); } @Test public void shouldFindDirectExceptionMapperFromException() { Optional<ExceptionMapper> mapper ...
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public ConstraintDescriptor<?> getConstraintDescriptor() { throw new UnsupportedOperationException(); } private ConstraintViolationImpl(ResourceRegistry resourceRegistry, ErrorData errorData, QueryContext queryContext); static ConstraintViolati...
@Test(expected = UnsupportedOperationException.class) public void getConstraintDescriptor() { violation.getConstraintDescriptor(); }
ExceptionMapperType implements Prioritizable { @Override public String toString() { return "ExceptionMapperType[" + "exceptionClass=" + exceptionClass.getName() + ", exceptionMapper=" + exceptionMapper + ']'; } ExceptionMapperType(Class<? extends Throwable> exceptionClass, ExceptionMapper exceptionMapper); Class<? exte...
@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.Illegal...
DocumentMapper { public Result<Document> toDocument(JsonApiResponse response, QueryAdapter queryAdapter, DocumentMappingConfig mappingConfig) { if (response == null) { LOGGER.debug("null response returned"); return null; } int requestVersion = queryAdapter.getQueryContext().getRequestVersion(); ResourceMappingConfig re...
@Test public void testAttributesBasic() { Task task = createTask(2, "sample task"); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resour...
ValidationClientModuleFactory implements ClientModuleFactory { @Override public ValidationModule create() { return ValidationModule.create(); } @Override ValidationModule create(); }
@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 = ...
HomeModuleExtension implements ModuleExtension { public void addPath(String path) { paths.add(path); } @Override Class<? extends Module> getTargetModule(); @Override boolean isOptional(); void addPath(String path); }
@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(Home...
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...
@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 requestP...
DocumentMapperUtil { public ResourceIdentifier toResourceId(Object entity) { if (entity == null) { return null; } RegistryEntry entry = resourceRegistry.findEntry(entity); ResourceInformation resourceInformation = entry.getResourceInformation(); return resourceInformation.toResourceIdentifier(entity); } DocumentMapperU...
@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)); }
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, P...
@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()); }
DefaultInformationBuilder implements InformationBuilder { @Override public ResourceInformationBuilder createResource(Class<?> resourceClass, String resourceType) { return createResource(resourceClass, resourceType, null); } DefaultInformationBuilder(TypeParser typeParser); @Override FieldInformationBuilder createResour...
@Test public void resourceWithNoResourcePath() { InformationBuilder.ResourceInformationBuilder resource = builder.createResource(Task.class, "tasks"); ResourceInformation info = resource.build(); resource.superResourceType("superTask"); resource.implementationType(Project.class); Assert.assertEquals("tasks", info.getRe...
DefaultInformationBuilder implements InformationBuilder { @Override public RelationshipRepositoryInformationBuilder createRelationshipRepository(String sourceResourceType, String targetResourceType) { RelationshipMatcher matcher = new RelationshipMatcher(); matcher.rule().target(targetResourceType).source(sourceResourc...
@Test public void checkRelationshipRepository() { InformationBuilder.RelationshipRepositoryInformationBuilder repositoryBuilder = builder.createRelationshipRepository("projects", "tasks"); RepositoryMethodAccess expectedAccess = new RepositoryMethodAccess(true, false, true, false); repositoryBuilder.setAccess(expectedA...
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 get...
@Test public void moduleName() { HomeModule module = boot.getModuleRegistry().getModule(HomeModule.class).get(); Assert.assertEquals("home", module.getModuleName()); }
RepositoryAdapterUtils { public static LinksInformation enrichLinksInformation(ModuleRegistry moduleRegistry, LinksInformation linksInformation, Object resource, RepositoryRequestSpec requestSpec) { if (requestSpec.getQueryAdapter() instanceof QuerySpecAdapter && resource instanceof ResourceList) { ResourceList<?> reso...
@Test public void enrichSelfLinksInformationNoQuerySpec() { ResourceList resources = new DefaultResourceList(); when(requestSpec.getQueryAdapter()).thenReturn(mock(QueryAdapter.class)); LinksInformation result = RepositoryAdapterUtils.enrichLinksInformation(moduleRegistry, null, resources, requestSpec); assertThat(resu...
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()); } ...
@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 = A...
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,...
@Test public void onIsBlankValues() { assertTrue(StringUtils.isBlank(null)); assertTrue(StringUtils.isBlank("")); assertTrue(StringUtils.isBlank(" ")); assertFalse(StringUtils.isBlank("crnk")); assertFalse(StringUtils.isBlank(" crnk ")); }
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); st...
@Test public void checkDecapitalize() { Assert.assertEquals("", StringUtils.decapitalize("")); Assert.assertEquals("test", StringUtils.decapitalize("Test")); Assert.assertEquals("someTest", StringUtils.decapitalize("SomeTest")); }
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); }...
@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.getPr...
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 serviceUr...
@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(my...
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 getPropertyTy...
@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, "publicPro...
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(Cla...
@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, "...
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> resourc...
@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.toId...
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(), ...
@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() ...
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 setR...
@Test(expected = UnsupportedOperationException.class) public void testAcceptableNotSupported() { upsert.isAcceptable(null, null); }
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 c...
@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 = ...
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> r...
@Test(expected = UnsupportedOperationException.class) public void testMethodNotSupported() { upsert.getHttpMethod(); }
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); st...
@Test public void stringMustExist() { Assert.assertTrue(ClassUtils.existsClass(String.class.getName())); } @Test public void unknownClassMustNotExist() { Assert.assertFalse(ClassUtils.existsClass("does.not.exist")); }
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(...
@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).isE...
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(...
@Test public void onClassInheritanceShouldReturnInheritedClasses() { List<Field> result = ClassUtils.getClassFields(ChildClass.class); assertThat(result).hasSize(2); }
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)) {...
@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); }
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(controllerC...
@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(do...
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, resultMa...
@Test public void onGetGettersShouldReturnMethodsStartingWithGet() throws Exception { List<Method> result = ClassUtils.getClassGetters(ParentClass.class); assertThat(result).doesNotContain(ParentClass.class.getDeclaredMethod("aetParentField")); } @Test public void onGetGettersShouldReturnMethodsThatNotTakeParams() thro...
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()...
@Test public void onFindGetterShouldReturnBooleanPropertyWithGet() { Method method = ClassUtils.findGetter(ParentClass.class, "booleanPropertyWithGet"); assertThat(method.getName()).isEqualTo("getBooleanPropertyWithGet"); } @Test public void onFindGetterShouldReturnIntegerMethod() { Method method = ClassUtils.findGette...
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(me...
@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() { L...
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.getAnnota...
@Test public void onGetAnnotationShouldReturnAnnotation() { Optional<JsonApiResource> result = ClassUtils.getAnnotation(ResourceClass.class, JsonApiResource.class); assertThat(result.get()).isInstanceOf(JsonApiResource.class); } @Test public void onGetAnnotationShouldReturnParentAnnotation() { Optional<JsonPropertyOrde...
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 classN...
@Test public void onValidClassShouldCreateNewInstance() { ResourceClass result = ClassUtils.newInstance(ResourceClass.class); assertThat(result).isInstanceOf(ResourceClass.class); } @Test(expected = IllegalStateException.class) public void onClassWithCrushingConstructorShouldThrowException() { ClassUtils.newInstance(Cl...
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 (NoSuchMethodExcep...
@Test public void onFindSetterShouldReturnIntegerMethod() { Method method = ClassUtils.findSetter(IntegerClass.class, "id", Integer.class); assertThat(method.getName()).isEqualTo("setId"); }
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 b...
@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.isPrimiti...
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...
@Test public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor<PreconditionUtil> constructor = PreconditionUtil.class.getDeclaredConstructor(); Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); construct...
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, ...
@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 = IllegalSta...
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, Obje...
@Test(expected = IllegalStateException.class) public void testFalseNotSatisfied() { PreconditionUtil.assertFalse(null, true); }
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); sta...
@Test(expected = IllegalStateException.class) public void testNotNullNotSatisfied() { PreconditionUtil.assertNotNull(null, null); }
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; } Clien...
@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.asse...
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...
@Test(expected = IllegalStateException.class) public void testNullNotSatisfied() { PreconditionUtil.assertNull(null, "not null"); }
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); }
@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")); }
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(S...
@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.asser...
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); stati...
@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.assertEqua...
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(); } priva...
@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)))); } }
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(resourc...
@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: }
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 (NoSuchMethodExce...
@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.a...
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(Json...
@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 onNon...
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 Resu...
@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 ...
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 Resul...
@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 publi...