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); @Override Map<String, Set<String>> serialize(final NumberSizePagingSpec pagingSpec, final String resourceType); @Override NumberSizePagingSpec deserialize(final Map<String, Set<String>> parameters); @Override NumberSizePagingSpec createEmptyPagingSpec(); @Override NumberSizePagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final NumberSizePagingSpec pagingSpec); void setDefaultNumber(int defaultNumber); static Module createModule(); }
@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, null))); } @Test public void testIsNotRequired() { assertFalse(new NumberSizePagingBehavior().isRequired(new NumberSizePagingSpec())); }
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 isNextPageAvailable = isNextPageAvailable(resources); if ((totalCount != null || isNextPageAvailable != null) && !hasPageLinks(linksInformation)) { boolean hasResults = resources.iterator().hasNext(); doEnrichPageLinksInformation(linksInformation, totalCount, isNextPageAvailable, queryAdapter, hasResults, urlBuilder); } } NumberSizePagingBehavior(); @Override boolean supports(Class<? extends PagingSpec> pagingSpecType); @Override Map<String, Set<String>> serialize(final NumberSizePagingSpec pagingSpec, final String resourceType); @Override NumberSizePagingSpec deserialize(final Map<String, Set<String>> parameters); @Override NumberSizePagingSpec createEmptyPagingSpec(); @Override NumberSizePagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final NumberSizePagingSpec pagingSpec); void setDefaultNumber(int defaultNumber); static Module createModule(); }
@Test public void testBuild() { PagingBehavior pagingBehavior = new NumberSizePagingBehavior(); NumberSizePagingSpec pagingSpec = new NumberSizePagingSpec(1, 10); ModuleRegistry moduleRegistry = new ModuleRegistry(); ResourceRegistry resourceRegistry = new ResourceRegistryImpl(new DefaultResourceRegistryPart(), moduleRegistry); QueryContext queryContext = new QueryContext(); queryContext.setBaseUrl("http: QuerySpec spec = new QuerySpec(Task.class); QuerySpecAdapter querySpecAdapter = new QuerySpecAdapter(spec, resourceRegistry, queryContext); querySpecAdapter.setPagingSpec(pagingSpec); PagingSpecUrlBuilder urlBuilder = mock(PagingSpecUrlBuilder.class); when(urlBuilder.build(any(QuerySpecAdapter.class))).thenReturn(queryContext.getBaseUrl()); DefaultPagedMetaInformation pagedMetaInformation = new DefaultPagedMetaInformation(); pagedMetaInformation.setTotalResourceCount(30L); ResourceList resourceList = new DefaultResourceList(pagedMetaInformation, null); for (int i = 0; i < 30; i++) { resourceList.add(new Task()); } PagedLinksInformation pagedLinksInformation = new DefaultPagedLinksInformation(); pagingBehavior.build(pagedLinksInformation, resourceList, querySpecAdapter, urlBuilder); assertThat(pagedLinksInformation.getFirst().getHref(), equalTo("http: assertThat(pagedLinksInformation.getNext().getHref(), equalTo("http: assertNull(pagedLinksInformation.getPrev()); assertThat(pagedLinksInformation.getLast().getHref(), equalTo("http: }
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]", OFFSET_PARAMETER), new HashSet<>(Arrays.asList(Long.toString(pagingSpec.getOffset())))); } if (pagingSpec.getLimit() != null) { values.put(String.format("page[%s]", LIMIT_PARAMETER), new HashSet<>(Arrays.asList(Long.toString(pagingSpec.getLimit())))); } return values; } OffsetLimitPagingBehavior(); @Override Map<String, Set<String>> serialize(final OffsetLimitPagingSpec pagingSpec, final String resourceType); @Override OffsetLimitPagingSpec deserialize(final Map<String, Set<String>> parameters); @Override OffsetLimitPagingSpec createEmptyPagingSpec(); @Override OffsetLimitPagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final OffsetLimitPagingSpec pagingSpec); long getDefaultOffset(); void setDefaultOffset(final long defaultOffset); }
@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]")); assertEquals(0, result.size()); } @Test public void testSerializeOffset() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); Map<String, Set<String>> result = pagingBehavior.serialize(new OffsetLimitPagingSpec(1L, null), "tasks"); assertEquals(ImmutableSet.of("1"), result.get("page[offset]")); assertFalse(result.containsKey("page[limit]")); assertEquals(1, result.size()); } @Test public void testSerializeLimit() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); Map<String, Set<String>> result = pagingBehavior.serialize(new OffsetLimitPagingSpec(0L, 30L), "tasks"); assertFalse(result.containsKey("page[offset]")); assertEquals(ImmutableSet.of("30"), result.get("page[limit]")); assertEquals(1, result.size()); } @Test public void testSerialize() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); Map<String, Set<String>> result = pagingBehavior.serialize(new OffsetLimitPagingSpec(1L, 30L), "tasks"); assertEquals(ImmutableSet.of("1"), result.get("page[offset]")); assertEquals(ImmutableSet.of("30"), result.get("page[limit]")); assertEquals(2, result.size()); }
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getLeafBean() { 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); }
@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_PARAMETER.equalsIgnoreCase(param.getKey())) { result.setOffset(getValue(param.getKey(), param.getValue())); } else if (LIMIT_PARAMETER.equalsIgnoreCase(param.getKey())) { Long limit = getValue(param.getKey(), param.getValue()); if (maxPageLimit != null && limit != null && limit > maxPageLimit) { throw new BadRequestException( String.format("%s value %d is larger than the maximum allowed of %d", LIMIT_PARAMETER, limit, maxPageLimit) ); } result.setLimit(limit); } else { throw new ParametersDeserializationException(param.getKey()); } } return result; } OffsetLimitPagingBehavior(); @Override Map<String, Set<String>> serialize(final OffsetLimitPagingSpec pagingSpec, final String resourceType); @Override OffsetLimitPagingSpec deserialize(final Map<String, Set<String>> parameters); @Override OffsetLimitPagingSpec createEmptyPagingSpec(); @Override OffsetLimitPagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final OffsetLimitPagingSpec pagingSpec); long getDefaultOffset(); void setDefaultOffset(final long defaultOffset); }
@Test public void testDeserializeDefaultWithNoParameters() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec result = pagingBehavior.deserialize(Collections.emptyMap()); assertEquals(new OffsetLimitPagingSpec(0L, null), result); } @Test public void testDeserializeDefaultWithOffset() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec result = pagingBehavior.deserialize(ImmutableMap.of("offset", ImmutableSet.of("1"))); assertEquals(new OffsetLimitPagingSpec(1L, null), result); } @Test public void testDeserializeDefaultWithLimit() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec result = pagingBehavior.deserialize(ImmutableMap.of("limit", ImmutableSet.of("30"))); assertEquals(new OffsetLimitPagingSpec(0L, 30L), result); } @Test public void testDeserializeLimitWithNoParameters() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); pagingBehavior.setDefaultLimit(30L); OffsetLimitPagingSpec result = pagingBehavior.deserialize(Collections.emptyMap()); assertEquals(new OffsetLimitPagingSpec(0L, 30L), result); } @Test public void testDeserializeLimitWithOffset() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); pagingBehavior.setDefaultLimit(30L); OffsetLimitPagingSpec result = pagingBehavior.deserialize(ImmutableMap.of("offset", ImmutableSet.of("1"))); assertEquals(new OffsetLimitPagingSpec(1L, 30L), result); } @Test public void testDeserializeLimitWithLimit() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); pagingBehavior.setDefaultLimit(30L); OffsetLimitPagingSpec result = pagingBehavior.deserialize(ImmutableMap.of("limit", ImmutableSet.of("10"))); assertEquals(new OffsetLimitPagingSpec(0L, 10L), result); } @Test public void testDeserialize() { OffsetLimitPagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec result = pagingBehavior.deserialize(ImmutableMap.of("offset", ImmutableSet.of("1"), "limit", ImmutableSet.of("30"))); assertEquals(new OffsetLimitPagingSpec(1L, 30L), result); }
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object getInvalidValue() { 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); }
@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 OffsetLimitPagingSpec pagingSpec, final String resourceType); @Override OffsetLimitPagingSpec deserialize(final Map<String, Set<String>> parameters); @Override OffsetLimitPagingSpec createEmptyPagingSpec(); @Override OffsetLimitPagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final OffsetLimitPagingSpec pagingSpec); long getDefaultOffset(); void setDefaultOffset(final long defaultOffset); }
@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 OffsetLimitPagingBehavior().isRequired(new OffsetLimitPagingSpec())); }
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 isNextPageAvailable = isNextPageAvailable(resources); if ((totalCount != null || isNextPageAvailable != null) && !hasPageLinks(linksInformation)) { boolean hasResults = resources.iterator().hasNext(); doEnrichPageLinksInformation(linksInformation, totalCount, isNextPageAvailable, queryAdapter, hasResults, urlBuilder); } } OffsetLimitPagingBehavior(); @Override Map<String, Set<String>> serialize(final OffsetLimitPagingSpec pagingSpec, final String resourceType); @Override OffsetLimitPagingSpec deserialize(final Map<String, Set<String>> parameters); @Override OffsetLimitPagingSpec createEmptyPagingSpec(); @Override OffsetLimitPagingSpec createDefaultPagingSpec(); @Override void build(final PagedLinksInformation linksInformation, final ResourceList<?> resources, final QueryAdapter queryAdapter, final PagingSpecUrlBuilder urlBuilder); @Override boolean isRequired(final OffsetLimitPagingSpec pagingSpec); long getDefaultOffset(); void setDefaultOffset(final long defaultOffset); }
@Test public void testBuild() { PagingBehavior pagingBehavior = new OffsetLimitPagingBehavior(); OffsetLimitPagingSpec pagingSpec = new OffsetLimitPagingSpec(0L, 10L); ModuleRegistry moduleRegistry = new ModuleRegistry(); ResourceRegistry resourceRegistry = new ResourceRegistryImpl(new DefaultResourceRegistryPart(), moduleRegistry); QueryContext queryContext = new QueryContext(); queryContext.setBaseUrl("http: QuerySpec spec = new QuerySpec(Task.class); QuerySpecAdapter querySpecAdapter = new QuerySpecAdapter(spec, resourceRegistry, queryContext); querySpecAdapter.setPagingSpec(pagingSpec); PagingSpecUrlBuilder urlBuilder = mock(PagingSpecUrlBuilder.class); when(urlBuilder.build(any(QuerySpecAdapter.class))).thenReturn(queryContext.getBaseUrl()); DefaultPagedMetaInformation pagedMetaInformation = new DefaultPagedMetaInformation(); pagedMetaInformation.setTotalResourceCount(30L); ResourceList resourceList = new DefaultResourceList(pagedMetaInformation, null); for (int i = 0; i < 30; i++) { resourceList.add(new Task()); } PagedLinksInformation pagedLinksInformation = new DefaultPagedLinksInformation(); pagingBehavior.build(pagedLinksInformation, resourceList, querySpecAdapter, urlBuilder); assertThat(pagedLinksInformation.getFirst().getHref(), equalTo("http: assertThat(pagedLinksInformation.getNext().getHref(), equalTo("http: assertNull(pagedLinksInformation.getPrev()); assertThat(pagedLinksInformation.getLast().getHref(), equalTo("http: }
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(QuerySpecVisitor visitor); String getResourceType(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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 : includedRelations) { copy.includedRelations.add(includeRelationSpec.clone()); } for (SortSpec sortSpec : sort) { copy.sort.add(sortSpec.clone()); } for (FilterSpec filterSpec : filters) { copy.filters.add(filterSpec.clone()); } for (Entry<String, QuerySpec> entry : typeRelatedSpecs.entrySet()) { copy.typeRelatedSpecs.put(entry.getKey(), entry.getValue().clone()); } for (Entry<Class<?>, QuerySpec> entry : classRelatedSpecs.entrySet()) { copy.classRelatedSpecs.put(entry.getKey(), entry.getValue().clone()); } return copy; } QuerySpec(Class<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QuerySpecVisitor visitor); String getResourceType(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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(Arrays.asList("includedField")); spec.includeRelation(Arrays.asList("includedRelation")); spec.setLimit(2L); spec.setOffset(1L); QuerySpec duplicate = spec.clone(); Assert.assertNotSame(spec, duplicate); Assert.assertNotSame(spec.getFilters().get(0), duplicate.getFilters().get(0)); Assert.assertNotSame(spec.getFilters().get(0).getPath(), duplicate.getFilters().get(0).getPath()); Assert.assertNotSame(spec.getSort(), duplicate.getSort()); Assert.assertNotSame(spec.getSort().get(0), duplicate.getSort().get(0)); Assert.assertNotSame(spec.getSort().get(0).getPath(), duplicate.getSort().get(0).getPath()); Assert.assertNotSame(spec.getIncludedFields(), duplicate.getIncludedFields()); Assert.assertNotSame(spec.getIncludedRelations(), duplicate.getIncludedRelations()); Assert.assertNotSame(spec.getIncludedRelations().get(0), duplicate.getIncludedRelations().get(0)); Assert.assertNotSame(spec.getPaging(), duplicate.getPaging()); Assert.assertEquals(spec, duplicate); }
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<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QuerySpecVisitor visitor); String getResourceType(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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) && CompareUtils.isEquals(includedRelations, other.includedRelations) && CompareUtils.isEquals(pagingSpec, other.pagingSpec) && CompareUtils.isEquals(typeRelatedSpecs, other.typeRelatedSpecs) && CompareUtils.isEquals(classRelatedSpecs, other.classRelatedSpecs) && CompareUtils.isEquals(sort, other.sort); } QuerySpec(Class<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QuerySpecVisitor visitor); String getResourceType(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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.asList("includedRelation")); Assert.assertEquals(spec1, spec1); QuerySpec spec2 = new QuerySpec(Task.class); spec2.addFilter(new FilterSpec(Arrays.asList("filterAttr"), FilterOperator.EQ, "test")); spec2.addSort(new SortSpec(Arrays.asList("sortAttr"), Direction.ASC)); spec2.includeField(Arrays.asList("includedField")); spec2.includeRelation(Arrays.asList("includedRelation")); Assert.assertEquals(spec2, spec2); Assert.assertEquals(spec1, spec2); spec2.getIncludedRelations().clear(); Assert.assertNotEquals(spec1, spec2); spec2.includeRelation(Arrays.asList("includedRelation")); Assert.assertEquals(spec1, spec2); spec2.getIncludedFields().clear(); Assert.assertNotEquals(spec1, spec2); Assert.assertNotEquals(spec1.hashCode(), spec2.hashCode()); spec2.includeField(Arrays.asList("includedField")); Assert.assertEquals(spec1, spec2); spec2.getFilters().clear(); Assert.assertNotEquals(spec1, spec2); spec2.addFilter(new FilterSpec(Arrays.asList("filterAttr"), FilterOperator.EQ, "test")); Assert.assertEquals(spec1, spec2); spec2.getSort().clear(); Assert.assertNotEquals(spec1, spec2); spec2.addSort(new SortSpec(Arrays.asList("sortAttr"), Direction.ASC)); Assert.assertEquals(spec1, spec2); spec2.setOffset(2); Assert.assertNotEquals(spec1, spec2); spec2.setOffset(0); Assert.assertEquals(spec1, spec2); spec2.setLimit(2L); Assert.assertNotEquals(spec1, spec2); spec2.setLimit(null); Assert.assertEquals(spec1, spec2); Assert.assertNotEquals(spec1, "someOtherType"); }
ConstraintViolationImpl implements ConstraintViolation<Object> { @Override public Object[] getExecutableParameters() { 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); }
@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(spec.getPath()); } } for (IncludeRelationSpec spec : includedRelations) { if (visitor.visitInclude(spec)) { visitor.visitPath(spec.getPath()); } } if (pagingSpec != null) { visitor.visitPaging(pagingSpec); } typeRelatedSpecs.values().forEach(it -> it.accept(visitor)); classRelatedSpecs.values().forEach(it -> it.accept(visitor)); visitor.visitEnd(this); } } QuerySpec(Class<?> resourceClass); QuerySpec(String resourceType); QuerySpec(Class<?> resourceClass, String resourceType); QuerySpec(ResourceInformation resourceInformation); void accept(QuerySpecVisitor visitor); String getResourceType(); Class<?> getResourceClass(); DefaultResourceList<T> apply(Iterable<T> resources); void apply(Iterable<T> resources, ResourceList<T> resultList); @Override int hashCode(); @Override boolean equals(Object obj); Long getLimit(); void setLimit(Long limit); long getOffset(); void setOffset(long offset); PagingSpec getPaging(); T getPaging(Class<T> pagingSpecType); QuerySpec setPaging(final PagingSpec pagingSpec); List<FilterSpec> getFilters(); void setFilters(List<FilterSpec> filters); Optional<FilterSpec> findFilter(final PathSpec pathSpec); Optional<FilterSpec> findFilter(final PathSpec pathSpec, FilterOperator operator); List<SortSpec> getSort(); void setSort(List<SortSpec> sort); List<IncludeFieldSpec> getIncludedFields(); void setIncludedFields(List<IncludeFieldSpec> includedFields); List<IncludeRelationSpec> getIncludedRelations(); void setIncludedRelations(List<IncludeRelationSpec> includedRelations); Collection<QuerySpec> getNestedSpecs(); void setNestedSpecs(Collection<QuerySpec> specs); void addFilter(FilterSpec filterSpec); void addSort(SortSpec sortSpec); void includeField(List<String> attrPath); void includeField(PathSpec path); void includeRelation(List<String> attrPath); void includeRelation(PathSpec path); QuerySpec getQuerySpec(String resourceType); QuerySpec getQuerySpec(Class<?> resourceClass); QuerySpec getQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(String resourceType); QuerySpec getOrCreateQuerySpec(ResourceInformation resourceInformation); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass); QuerySpec getOrCreateQuerySpec(Class<?> targetResourceClass, String targetResourceType); void putRelatedSpec(Class<?> relatedResourceClass, QuerySpec relatedSpec); QuerySpec clone(); @Override String toString(); }
@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))).thenReturn(false); Mockito.when(visitor.visitSort(Mockito.any(SortSpec.class))).thenReturn(true); Mockito.when(visitor.visitField(Mockito.any(IncludeFieldSpec.class))).thenReturn(true); Mockito.when(visitor.visitInclude(Mockito.any(IncludeRelationSpec.class))).thenReturn(true); spec.accept(visitor); Mockito.verify(visitor, Mockito.times(1)).visitStart(Mockito.eq(spec)); Mockito.verify(visitor, Mockito.times(1)).visitEnd(Mockito.eq(spec)); Mockito.verify(visitor, Mockito.times(1)).visitField(Mockito.any(IncludeFieldSpec.class)); Mockito.verify(visitor, Mockito.times(1)).visitFilterStart(Mockito.any(FilterSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitFilterEnd(Mockito.any(FilterSpec.class)); Mockito.verify(visitor, Mockito.times(1)).visitInclude(Mockito.any(IncludeRelationSpec.class)); Mockito.verify(visitor, Mockito.times(1)).visitSort(Mockito.any(SortSpec.class)); Mockito.verify(visitor, Mockito.times(1)).visitPaging(Mockito.any(PagingSpec.class)); Mockito.verify(visitor, Mockito.times(3)).visitPath(Mockito.any(PathSpec.class)); } @Test public void testVisitorWithSortAbort() { 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))).thenReturn(true); Mockito.when(visitor.visitSort(Mockito.any(SortSpec.class))).thenReturn(false); Mockito.when(visitor.visitField(Mockito.any(IncludeFieldSpec.class))).thenReturn(true); Mockito.when(visitor.visitInclude(Mockito.any(IncludeRelationSpec.class))).thenReturn(true); spec.accept(visitor); Mockito.verify(visitor, Mockito.times(3)).visitPath(Mockito.any(PathSpec.class)); } @Test public void testVisitorWithMultipleAbort() { 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))).thenReturn(true); Mockito.when(visitor.visitSort(Mockito.any(SortSpec.class))).thenReturn(false); Mockito.when(visitor.visitField(Mockito.any(IncludeFieldSpec.class))).thenReturn(false); Mockito.when(visitor.visitInclude(Mockito.any(IncludeRelationSpec.class))).thenReturn(false); spec.accept(visitor); Mockito.verify(visitor, Mockito.times(1)).visitPath(Mockito.any(PathSpec.class)); } @Test public void testVisitorWithAbort() { QuerySpec spec = createTestQueySpec(); QuerySpecVisitorBase visitor = Mockito.mock(QuerySpecVisitorBase.class); Mockito.when(visitor.visitStart(Mockito.any(QuerySpec.class))).thenReturn(false); spec.accept(visitor); Mockito.verify(visitor, Mockito.times(1)).visitStart(Mockito.eq(spec)); Mockito.verify(visitor, Mockito.times(0)).visitEnd(Mockito.eq(spec)); Mockito.verify(visitor, Mockito.times(0)).visitField(Mockito.any(IncludeFieldSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitFilterStart(Mockito.any(FilterSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitFilterEnd(Mockito.any(FilterSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitInclude(Mockito.any(IncludeRelationSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitSort(Mockito.any(SortSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitPaging(Mockito.any(PagingSpec.class)); Mockito.verify(visitor, Mockito.times(0)).visitPath(Mockito.any(PathSpec.class)); }
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 getDirection(); SortSpec reverse(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override SortSpec clone(); void setDirection(Direction dir); }
@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); static SortSpec asc(List<String> expression); static SortSpec desc(List<String> attributeName); Direction getDirection(); SortSpec reverse(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override SortSpec clone(); void setDirection(Direction dir); }
@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"), Direction.DESC).toString()); }
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); static SortSpec desc(List<String> attributeName); Direction getDirection(); SortSpec reverse(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override SortSpec clone(); void setDirection(Direction dir); }
@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(PathSpec path, Direction direction); static SortSpec asc(List<String> expression); static SortSpec desc(List<String> attributeName); Direction getDirection(); SortSpec reverse(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override SortSpec clone(); void setDirection(Direction dir); }
@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("name2"), Direction.ASC); SortSpec spec4 = new SortSpec(Arrays.asList("name1"), Direction.DESC); Assert.assertEquals(spec1, spec1); Assert.assertEquals(spec3, spec3); Assert.assertEquals(spec1, spec2); Assert.assertEquals(spec2, spec1); Assert.assertEquals(spec1.hashCode(), spec1.hashCode()); Assert.assertEquals(spec3.hashCode(), spec3.hashCode()); Assert.assertEquals(spec1.hashCode(), spec2.hashCode()); Assert.assertNotEquals(spec2, spec3); Assert.assertNotEquals(spec3, spec2); Assert.assertNotEquals(spec1, spec4); Assert.assertNotEquals(spec3, spec4); Assert.assertEquals(spec1, SortSpec.asc(Arrays.asList("name1"))); Assert.assertEquals(spec4, SortSpec.desc(Arrays.asList("name1"))); Assert.assertNotEquals(spec1, null); Assert.assertNotEquals(spec1, "test"); }
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> attributeName); Direction getDirection(); SortSpec reverse(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override SortSpec clone(); void setDirection(Direction dir); }
@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(), duplicate.getDirection()); }
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); String json = writer.writeValueAsString(metaInformation); Assert.assertEquals("{\"totalResourceCount\":12}", json); }
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); }
@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); 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(); }
@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 resource); @Override final void delete(I id); }
@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 resource); @Override final void delete(I id); }
@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); @Override final void delete(I id); }
@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); @Override S save(S entity); @Override void delete(I id); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); }
@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 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); }
@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 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); }
@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(); @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); }
@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> 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); }
@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 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); }
@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> 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); }
@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, 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); }
@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> 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); }
@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> 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); }
@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.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); }
@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")); }
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); }
@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()); }
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); }
@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(); } }
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); }
@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 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); }
@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.eq(context)); }
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(); }
@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)); }
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); }
@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++; } 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); }
@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); }
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); }
@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); }
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); }
@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<? extends Throwable> getExceptionClass(); ExceptionMapper getExceptionMapper(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override int getPriority(); }
@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()); }
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 resourceMapping = mappingConfig.getResourceMapping(); Document doc = new Document(); doc.setJsonapi(jsonapi); addErrors(doc, response.getErrors()); util.setMeta(doc, response.getMetaInformation()); if (mappingConfig.getResourceMapping().getSerializeLinks()) { LinksInformation linksInformation = enrichSelfLink(response.getLinksInformation(), queryAdapter); util.setLinks(doc, linksInformation, queryAdapter); } addData(doc, response.getEntity(), queryAdapter, resourceMapping); Result<Document> result = addRelationDataAndInclusions(doc, response.getEntity(), queryAdapter, mappingConfig); result.doWork(it -> applyIgnoreEmpty(doc, queryAdapter, requestVersion)); result.doWork(it -> compact(doc, queryAdapter)); return result; } DocumentMapper(ResourceRegistry resourceRegistry, ObjectMapper objectMapper, PropertiesProvider propertiesProvider, ResourceFilterDirectory resourceFilterDirectory, ResultFactory resultFactory, Map<String, String> serverInfo, UrlBuilder urlBuilder); DocumentMapper(ResourceRegistry resourceRegistry, ObjectMapper objectMapper, PropertiesProvider propertiesProvider, ResourceFilterDirectory resourceFilterDirectory, ResultFactory resultFactory, Map<String, String> serverInfo, boolean client, UrlBuilder urlBuilder); ResourceMapper getResourceMapper(); void setClient(boolean client); Result<Document> toDocument(JsonApiResponse response, QueryAdapter queryAdapter, DocumentMappingConfig mappingConfig); }
@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", resource.getType()); Assert.assertEquals("sample task", resource.getAttributes().get("name").asText()); Assert.assertThat(resource.getAttributes().get("writeOnlyValue"), CoreMatchers.nullValue()); } @Test public void testSerializeWithoutLinks() { Task task = createTask(2, "sample task"); mappingConfig.getResourceMapping().setSerializeLinks(false); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertNull(resource.getLinks()); Relationship relationship = resource.getRelationships().get("project"); Assert.assertNull(relationship.getLinks()); } @Test public void testSerializeRootSelfLink() { Task task = createTask(2, "sample task"); QueryAdapter adapter = createAdapter(Task.class); Mockito.when(container.getRequestContextBase().getRequestUri()).thenReturn(URI.create("http: Document document = mapper.toDocument(toResponse(task), adapter, mappingConfig).get(); Assert.assertEquals("http: } @Test public void testCompactMode() { LinksInformation links = new TaskLinks(); Task task = createTask(2, "sample task"); task.setLinksInformation(links); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(new QuerySpec(Task.class)); queryAdapter.setCompactMode(true); Document document = mapper.toDocument(toResponse(task), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertNull(resource.getLinks().get("self")); Assert.assertNotNull(resource.getLinks().get("someLink")); Relationship project = resource.getRelationships().get("project"); Assert.assertNull(project.getLinks()); } @Test public void testCompactModeWithInclusion() { Project project = new Project(); project.setName("someProject"); project.setId(3L); Task task = createTask(2, "sample task"); task.setProject(project); QuerySpec querySpec = new QuerySpec(Task.class); querySpec.includeRelation(Arrays.asList("project")); QueryAdapter queryAdapter = toAdapter(querySpec); DocumentMappingConfig config = mappingConfig.clone(); config.getResourceMapping().setSerializeSelfRelationshipLinks(false); Document document = mapper.toDocument(toResponse(task), queryAdapter, config).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship projectRel = resource.getRelationships().get("project"); ObjectNode links = projectRel.getLinks(); Assert.assertFalse(links.has("self")); Assert.assertTrue(links.has("related")); } @Test public void testOmitSelfRelatedLinks() { Project project = new Project(); project.setName("someProject"); project.setId(3L); LinksInformation links = new TaskLinks(); Task task = createTask(2, "sample task"); task.setLinksInformation(links); task.setProject(project); QuerySpec querySpec = new QuerySpec(Task.class); querySpec.includeRelation(Arrays.asList("project")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); queryAdapter.setCompactMode(true); Document document = mapper.toDocument(toResponse(task), queryAdapter, mappingConfig.clone()).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertNull(resource.getLinks().get("self")); Assert.assertNotNull(resource.getLinks().get("someLink")); Relationship projectRel = resource.getRelationships().get("project"); Assert.assertNull(projectRel.getLinks()); Assert.assertEquals(1, document.getIncluded().size()); Resource projectResource = document.getIncluded().get(0); Assert.assertNull(projectResource.getRelationships().get("tasks")); } @Test public void testCustomSelfLinks() { TaskLinks links = new TaskLinks(); links.self = new DefaultLink("http: Task task = createTask(2, "sample task"); task.setLinksInformation(links); QuerySpec querySpec = new QuerySpec(Task.class); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(task), queryAdapter, mappingConfig.clone()).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertEquals("http: Relationship projectRel = resource.getRelationships().get("project"); Assert.assertEquals("http: } @Test public void testJsonIncludeNonEmptyIgnoresNull() throws JsonProcessingException { Schedule schedule = new Schedule(); schedule.setDesc(null); schedule.setFollowupProject(null); QuerySpec querySpec = new QuerySpec(Project.class); querySpec.includeRelation(PathSpec.of("followupProject")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(schedule), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertFalse(resource.getAttributes().containsKey("description")); Assert.assertFalse(resource.getRelationships().containsKey("followup")); } @Test public void testJsonIncludeNonEmptyIgnoresEmptyList() throws JsonProcessingException { Schedule schedule = new Schedule(); schedule.setKeywords(Collections.emptyList()); schedule.setTasks(new ArrayList<>()); QuerySpec querySpec = new QuerySpec(Project.class); querySpec.includeRelation(PathSpec.of("tasks")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(schedule), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertFalse(resource.getAttributes().containsKey("keywords")); Assert.assertFalse(resource.getRelationships().containsKey("tasks")); } @Test public void testJsonIncludeNonEmptyWritesNonEmpty() throws JsonProcessingException { Project project = new Project(); project.setId(12L); Schedule schedule = new Schedule(); schedule.setDesc("Hello"); schedule.setFollowupProject(project); QuerySpec querySpec = new QuerySpec(Project.class); querySpec.includeRelation(PathSpec.of("followupProject")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(schedule), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertTrue(resource.getAttributes().containsKey("description")); Assert.assertTrue(resource.getRelationships().containsKey("followup")); } @Test public void testOptionalNotSerializedIfEmpty() { Schedule schedule = new Schedule(); schedule.setDueDate(Optional.empty()); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(new QuerySpec(Project.class)); Document document = mapper.toDocument(toResponse(schedule), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertFalse(resource.getAttributes().containsKey("dueDate")); } @Test public void testOptionalSerializedIfSet() { Schedule schedule = new Schedule(); schedule.setDueDate(Optional.of(OffsetDateTime.now())); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(new QuerySpec(Project.class)); Document document = mapper.toDocument(toResponse(schedule), queryAdapter, mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertTrue(resource.getAttributes().containsKey("dueDate")); JsonNode node = resource.getAttributes().get("dueDate"); Assert.assertTrue(node.asText().length() > 0); } @Test public void testCompactModeWithNullData() { QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(new QuerySpec(Task.class)); queryAdapter.setCompactMode(true); Document compactDocument = mapper.toDocument(new JsonApiResponse(), queryAdapter, mappingConfig).get(); queryAdapter.setCompactMode(false); Document standardDocument = mapper.toDocument(new JsonApiResponse(), queryAdapter, mappingConfig).get(); Assert.assertEquals(standardDocument, compactDocument); } @Test public void testDocumentInformation() { Task task = createTask(2, "sample task"); TestLinksInformation links = new TestLinksInformation(); links.value = new DefaultLink("linksValue"); TestMetaInformation meta = new TestMetaInformation(); meta.value = "metaValue"; JsonApiResponse response = toResponse(task); response.setMetaInformation(meta); response.setLinksInformation(links); Document document = mapper.toDocument(response, createAdapter(Task.class), mappingConfig).get(); Assert.assertEquals("linksValue", getLinkText(document.getLinks().get("value"))); Assert.assertEquals("metaValue", document.getMeta().get("value").asText()); } @Test public void testResourceInformation() { TestLinksInformation links = new TestLinksInformation(); links.value = new DefaultLink("linksValue"); TestMetaInformation meta = new TestMetaInformation(); meta.value = "metaValue"; Task task = createTask(2, "sample task"); task.setMetaInformation(meta); task.setLinksInformation(links); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("linksValue", getLinkText(resource.getLinks().get("value"))); Assert.assertEquals("metaValue", resource.getMeta().get("value").asText()); } @Test public void testErrors() { JsonApiResponse response = new JsonApiResponse(); ErrorData error = Mockito.mock(ErrorData.class); response.setErrors(Arrays.asList(error)); Document document = mapper.toDocument(response, createAdapter(Task.class), mappingConfig).get(); List<ErrorData> errors = document.getErrors(); Assert.assertEquals(1, errors.size()); Assert.assertSame(error, errors.get(0)); } @Test public void testRelationshipSingleValuedEager() { LazyTask task = createLazyTask(2); Project project = createProject(3, "sample project"); task.setProject(project); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship relationship = resource.getRelationships().get("project"); Assert.assertNotNull(relationship); ResourceIdentifier relationshipData = relationship.getSingleData().get(); Assert.assertNotNull(relationshipData); Assert.assertEquals("3", relationshipData.getId()); Assert.assertEquals("projects", relationshipData.getType()); Assert.assertTrue(document.getIncluded().isEmpty()); } @Test public void testRelationshipLazyMultiValued() { LazyTask task = createLazyTask(2); Project project1 = createProject(3, "sample project"); Project project2 = createProject(4, "sample project"); task.setProjects(Arrays.asList(project1, project2)); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship relationship = resource.getRelationships().get("projects"); Assert.assertNotNull(relationship); Nullable<List<ResourceIdentifier>> relationshipData = relationship.getCollectionData(); Assert.assertFalse(relationshipData.isPresent()); Assert.assertTrue(document.getIncluded().isEmpty()); } @Test public void testRelationshipIncludeMultiValued() { LazyTask task = createLazyTask(2); Project project1 = createProject(3, "sample project3"); Project project2 = createProject(4, "sample project4"); task.setProjects(Arrays.asList(project1, project2)); QuerySpec querySpec = new QuerySpec(LazyTask.class); querySpec.includeRelation(Arrays.asList("projects")); Document document = mapper.toDocument(toResponse(task), toAdapter(querySpec), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship relationship = resource.getRelationships().get("projects"); Assert.assertNotNull(relationship); List<ResourceIdentifier> relationshipData = relationship.getCollectionData().get(); Assert.assertNotNull(relationshipData); Assert.assertEquals(2, relationshipData.size()); Assert.assertEquals("3", relationshipData.get(0).getId()); Assert.assertEquals("projects", relationshipData.get(0).getType()); Assert.assertEquals("4", relationshipData.get(1).getId()); Assert.assertEquals("projects", relationshipData.get(1).getType()); Assert.assertFalse(document.getIncluded().isEmpty()); List<Resource> included = document.getIncluded(); Assert.assertEquals(2, included.size()); Assert.assertEquals("3", included.get(0).getId()); Assert.assertEquals("projects", included.get(0).getType()); Assert.assertEquals("sample project3", included.get(0).getAttributes().get("name").asText()); Assert.assertEquals("4", included.get(1).getId()); Assert.assertEquals("projects", included.get(1).getType()); Assert.assertEquals("sample project4", included.get(1).getAttributes().get("name").asText()); } @Test public void testRelationshipIncludeRelation() { LazyTask task = createLazyTask(2); Project project = createProject(3, "sample project"); task.setProject(project); QuerySpec querySpec = new QuerySpec(LazyTask.class); querySpec.includeRelation(Arrays.asList("project")); Document document = mapper.toDocument(toResponse(task), toAdapter(querySpec), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship relationship = resource.getRelationships().get("project"); Assert.assertNotNull(relationship); ResourceIdentifier relationshipData = relationship.getSingleData().get(); Assert.assertNotNull(relationshipData); Assert.assertEquals("3", relationshipData.getId()); Assert.assertEquals("projects", relationshipData.getType()); List<Resource> included = document.getIncluded(); Assert.assertEquals(1, included.size()); Assert.assertEquals("3", included.get(0).getId()); Assert.assertEquals("projects", included.get(0).getType()); Assert.assertEquals("sample project", included.get(0).getAttributes().get("name").asText()); } @Test public void testRelationshipCyclicInclusion() { Task task = createTask(2, "sample task"); Project project = createProject(3, "sample project"); task.setProject(project); project.setTask(task); QuerySpec querySpec = new QuerySpec(Task.class); querySpec.includeRelation(Arrays.asList("project")); querySpec.getOrCreateQuerySpec(Project.class).includeRelation(Arrays.asList("task")); Document document = mapper.toDocument(toResponse(task), toAdapter(querySpec), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Relationship relationship = resource.getRelationships().get("project"); Assert.assertNotNull(relationship); ResourceIdentifier relationshipData = relationship.getSingleData().get(); Assert.assertNotNull(relationshipData); Assert.assertEquals("3", relationshipData.getId()); Assert.assertEquals("projects", relationshipData.getType()); List<Resource> included = document.getIncluded(); Assert.assertEquals(1, included.size()); Assert.assertEquals("3", included.get(0).getId()); Assert.assertEquals("projects", included.get(0).getType()); Assert.assertEquals("sample project", included.get(0).getAttributes().get("name").asText()); Assert.assertEquals("2", included.get(0).getRelationships().get("task").getSingleData().get().getId()); } @Test public void testRelationshipSingleValuedIncludeByDefault() { Task task = createTask(2, "sample task"); Project project = createProject(3, "sample project"); task.setProject(project); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertEquals("sample task", resource.getAttributes().get("name").asText()); Relationship relationship = resource.getRelationships().get("project"); Assert.assertNotNull(relationship); Assert.assertEquals("http: getLinkText(relationship.getLinks().get("self"))); Assert.assertEquals("http: ResourceIdentifier relationshipData = relationship.getSingleData().get(); Assert.assertNotNull(relationshipData); Assert.assertEquals("3", relationshipData.getId()); Assert.assertEquals("projects", relationshipData.getType()); List<Resource> included = document.getIncluded(); Assert.assertEquals(1, included.size()); Assert.assertEquals("3", included.get(0).getId()); Assert.assertEquals("projects", included.get(0).getType()); Assert.assertEquals("sample project", included.get(0).getAttributes().get("name").asText()); } @Test public void testMultipleInclusions() { Task task1 = createTask(1, "other task"); Task task2 = createTask(2, "other task"); Task task3 = createTask(3, "sample task"); Project project = new Project(); project.setName("someProject"); project.setId(3L); project.setTask(task1); project.setTasks(Arrays.asList(task2, task3)); QuerySpec querySpec = new QuerySpec(Project.class); querySpec.includeRelation(Arrays.asList("tasks")); querySpec.includeRelation(Arrays.asList("task")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(project), queryAdapter, new DocumentMappingConfig()).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("3", resource.getId()); Assert.assertEquals("projects", resource.getType()); Relationship taskRel = resource.getRelationships().get("task"); Assert.assertNotNull(taskRel.getLinks()); Assert.assertTrue(taskRel.getData().isPresent()); Assert.assertNotNull(taskRel.getData().get()); Relationship tasksRel = resource.getRelationships().get("tasks"); Assert.assertNotNull(tasksRel.getLinks()); Assert.assertTrue(tasksRel.getData().isPresent()); Assert.assertNotNull(tasksRel.getData().get()); Assert.assertEquals(2, tasksRel.getCollectionData().get().size()); Assert.assertEquals(3, document.getIncluded().size()); } @Test public void testConvergingInclusionPaths() { Task task1 = createTask(1, "other task"); Task task2 = createTask(2, "other task"); Project project1 = new Project(); project1.setName("someProject"); project1.setId(3L); project1.setTasks(Arrays.asList(task1, task2)); Project project2 = new Project(); project2.setName("someProject"); project2.setId(2L); task1.setProject(project1); task1.setProjectsInit(Arrays.asList(project2)); task1.setLinksInformation(new DefaultSelfLinksInformation()); project1.setTask(task2); project2.setTask(task2); QuerySpec querySpec = new QuerySpec(Task.class); querySpec.includeRelation(Arrays.asList("project", "task")); querySpec.includeRelation(Arrays.asList("projectsInit", "task")); QuerySpecAdapter queryAdapter = (QuerySpecAdapter) toAdapter(querySpec); Document document = mapper.toDocument(toResponse(task1), queryAdapter, new DocumentMappingConfig()).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("1", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Relationship projectRel = resource.getRelationships().get("project"); Assert.assertNotNull(projectRel.getLinks()); Assert.assertTrue(projectRel.getData().isPresent()); Assert.assertNotNull(projectRel.getData().get()); Relationship projectsRel = resource.getRelationships().get("projectsInit"); Assert.assertNotNull(projectsRel.getLinks()); Assert.assertTrue(projectsRel.getData().isPresent()); Assert.assertNotNull(projectsRel.getData().get()); Assert.assertEquals(1, projectsRel.getCollectionData().get().size()); Assert.assertEquals(3, document.getIncluded().size()); List<Resource> included = document.getIncluded(); Resource projectResource2 = included.get(0); Resource projectResource3 = included.get(1); Assert.assertTrue(projectResource2.getRelationships().get("task").getData().isPresent()); Assert.assertTrue(projectResource3.getRelationships().get("task").getData().isPresent()); } @Test public void testRelationshipSingleValuedLazy() { LazyTask task = createLazyTask(2); Project project = createProject(3, "sample project"); task.setLazyProject(project); Document document = mapper.toDocument(toResponse(task), createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("lazy_tasks", resource.getType()); Relationship relationship = resource.getRelationships().get("lazyProject"); Assert.assertNotNull(relationship); Assert.assertEquals("http: getLinkText(relationship.getLinks().get("self"))); Assert.assertEquals("http: getLinkText(relationship.getLinks().get("related"))); Nullable<ResourceIdentifier> relationshipData = relationship.getSingleData(); Assert.assertFalse(relationshipData.isPresent()); Assert.assertTrue(document.getIncluded().isEmpty()); } @Test public void testAttributesSelection() { Task task = createTask(2, "sample task"); task.setCategory("sample category"); task.setProject(new Project()); JsonApiResponse response = new JsonApiResponse(); response.setEntity(task); QuerySpec querySpec = new QuerySpec(Task.class); querySpec.includeField(Arrays.asList("category")); Document document = mapper.toDocument(response, toAdapter(querySpec), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("2", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertNull(resource.getAttributes().get("name")); Assert.assertNull(resource.getRelationships().get("project")); Assert.assertEquals("sample category", resource.getAttributes().get("category").asText()); } @Test public void testAttributesOrdering() { Task task = createTask(3, "sample task"); task.setCategory("sample category"); task.setName("sample name"); JsonApiResponse response = new JsonApiResponse(); response.setEntity(task); Document document = mapper.toDocument(response, createAdapter(Task.class), mappingConfig).get(); Resource resource = document.getSingleData().get(); Assert.assertEquals("3", resource.getId()); Assert.assertEquals("tasks", resource.getType()); Assert.assertTrue(resource.getAttributes() instanceof LinkedHashMap); Assert.assertEquals(resource.getAttributes().keySet(), Stream.of("category", "completed", "deleted", "name", "otherTasks", "readOnlyValue", "status") .collect(Collectors.toCollection(LinkedHashSet::new))); Assert.assertEquals("sample name", resource.getAttributes().get("name").asText()); Assert.assertEquals("sample category", resource.getAttributes().get("category").asText()); }
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 = moduleFactory.create(); moduleClasses.add(module.getClass()); } Assert.assertEquals(2, moduleClasses.size()); Assert.assertTrue(moduleClasses.contains(ValidationModule.class)); Assert.assertTrue(moduleClasses.contains(MetaModule.class)); }
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(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")); }
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; }
@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)); }
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(); }
@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, 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(); }
@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 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); }
@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.getResourceType()); Assert.assertEquals("tasks", info.getResourcePath()); } @Test public void resource() { InformationBuilder.ResourceInformationBuilder resource = builder.createResource(Task.class, "tasks", null); resource.superResourceType("superTask"); resource.resourceType("changedTasks"); resource.implementationType(Project.class); InformationBuilder.FieldInformationBuilder idField = resource.addField("id", ResourceFieldType.ID, String.class); idField.serializeType(SerializeType.EAGER); idField.access(new ResourceFieldAccess(true, true, true, false, false)); ResourceFieldAccessor accessor = Mockito.mock(ResourceFieldAccessor.class); InformationBuilder.FieldInformationBuilder projectField = resource.addField("project", ResourceFieldType.RELATIONSHIP, Project.class); projectField.serializeType(SerializeType.EAGER); projectField.access(new ResourceFieldAccess(true, false, true, false, false)); projectField.oppositeName("tasks"); projectField.relationshipRepositoryBehavior(RelationshipRepositoryBehavior.FORWARD_OWNER); projectField.lookupIncludeBehavior(LookupIncludeBehavior.AUTOMATICALLY_ALWAYS); projectField.accessor(accessor); ResourceInformation info = resource.build(); Assert.assertEquals("changedTasks", info.getResourceType()); Assert.assertEquals(Project.class, info.getResourceClass()); Assert.assertEquals("superTask", info.getSuperResourceType()); ResourceField idInfo = info.findFieldByName("id"); Assert.assertEquals("id", idInfo.getUnderlyingName()); Assert.assertEquals(String.class, idInfo.getType()); Assert.assertFalse(idInfo.getAccess().isFilterable()); Assert.assertFalse(idInfo.getAccess().isSortable()); Assert.assertTrue(idInfo.getAccess().isPostable()); Assert.assertTrue(idInfo.getAccess().isPatchable()); Assert.assertEquals(SerializeType.EAGER, idInfo.getSerializeType()); Assert.assertFalse(idInfo.isCollection()); ResourceField projectInfo = info.findFieldByName("project"); Assert.assertEquals("project", projectInfo.getUnderlyingName()); Assert.assertEquals("tasks", projectInfo.getOppositeName()); Assert.assertEquals(LookupIncludeBehavior.AUTOMATICALLY_ALWAYS, projectInfo.getLookupIncludeBehavior()); Assert.assertEquals(Project.class, projectInfo.getType()); Assert.assertSame(accessor, projectInfo.getAccessor()); Assert.assertFalse(projectInfo.getAccess().isFilterable()); Assert.assertFalse(projectInfo.getAccess().isSortable()); Assert.assertFalse(projectInfo.getAccess().isPostable()); Assert.assertTrue(projectInfo.getAccess().isPatchable()); Assert.assertEquals(SerializeType.EAGER, projectInfo.getSerializeType()); Assert.assertEquals(RelationshipRepositoryBehavior.FORWARD_OWNER, projectInfo.getRelationshipRepositoryBehavior()); Assert.assertFalse(projectInfo.isCollection()); } @Test public void checkRelationIdFieldCreation() { InformationBuilder.ResourceInformationBuilder resource = builder.createResource(Task.class, "tasks", null); resource.superResourceType("superTask"); resource.resourceType("changedTasks"); resource.implementationType(Project.class); InformationBuilder.FieldInformationBuilder idField = resource.addField("id", ResourceFieldType.ID, String.class); idField.serializeType(SerializeType.EAGER); idField.access(new ResourceFieldAccess(true, true, true, false, false)); ResourceFieldAccessor idAccessor = Mockito.mock(ResourceFieldAccessor.class); ResourceFieldAccessor accessor = Mockito.mock(ResourceFieldAccessor.class); InformationBuilder.FieldInformationBuilder projectField = resource.addField("project", ResourceFieldType.RELATIONSHIP, Project.class); projectField.idName("taskId"); projectField.idAccessor(idAccessor); projectField.idType(Long.class); projectField.serializeType(SerializeType.EAGER); projectField.access(new ResourceFieldAccess(true, false, true, false, false)); projectField.oppositeName("tasks"); projectField.lookupIncludeBehavior(LookupIncludeBehavior.AUTOMATICALLY_ALWAYS); projectField.accessor(accessor); ResourceInformation info = resource.build(); Assert.assertEquals("changedTasks", info.getResourceType()); Assert.assertEquals(Project.class, info.getResourceClass()); Assert.assertEquals("superTask", info.getSuperResourceType()); ResourceField projectInfo = info.findFieldByName("project"); Assert.assertEquals("project", projectInfo.getUnderlyingName()); Assert.assertEquals("tasks", projectInfo.getOppositeName()); Assert.assertEquals(LookupIncludeBehavior.AUTOMATICALLY_ALWAYS, projectInfo.getLookupIncludeBehavior()); Assert.assertEquals(Project.class, projectInfo.getType()); Assert.assertSame(accessor, projectInfo.getAccessor()); Assert.assertFalse(projectInfo.getAccess().isFilterable()); Assert.assertFalse(projectInfo.getAccess().isSortable()); Assert.assertFalse(projectInfo.getAccess().isPostable()); Assert.assertTrue(projectInfo.getAccess().isPatchable()); Assert.assertEquals(SerializeType.EAGER, projectInfo.getSerializeType()); Assert.assertTrue(projectInfo.hasIdField()); Assert.assertEquals("taskId", projectInfo.getIdName()); Assert.assertEquals(Long.class, projectInfo.getIdType()); Assert.assertSame(idAccessor, projectInfo.getIdAccessor()); Assert.assertFalse(projectInfo.isCollection()); } @Test public void checkResourceTypeHolderIngored() { ResourceInformation resourceInformation = builder.createResource(Task.class, "tasks", null).build(); Assert.assertTrue(ResourceTypeHolder.class.isAssignableFrom(ResourceTypeHolder.class)); Assert.assertNull(resourceInformation.findFieldByName("type")); }
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); }
@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); }
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; }
@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<?> resources = (ResourceList<?>) resource; linksInformation = enrichPageLinksInformation(moduleRegistry, linksInformation, resources, requestSpec); } return linksInformation; } static LinksInformation enrichLinksInformation(ModuleRegistry moduleRegistry, LinksInformation linksInformation, Object resource, RepositoryRequestSpec requestSpec); }
@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())); }
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; }
@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))); }
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; }
@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); 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; }
@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); } } 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); }
@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(); }
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(); }
@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)); }
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); }
@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"); }
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); }
@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"); }
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); }
@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); }
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); }
@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"); }
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); }
@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 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(); }
@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)); }
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); }
@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); 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; }
@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()[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; }
@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); }
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; }
@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)) { 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; }
@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(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); }
@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); }
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; }
@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); }
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; }
@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(); }
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; }
@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); }
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; }
@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(); }
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; }
@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); }
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; }
@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 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; }
@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(); }
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); }
@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); }
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); }
@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"); }
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); }
@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); 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); }
@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; } ClientStubBase(CrnkClient client, UrlBuilder urlBuilder, Class<?> resourceClass); static RuntimeException handleError(CrnkClient client, HttpAdapterResponse response, ClientFormat format); }
@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()); }
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); }
@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(String url); static String addLeadingSlash(String url); static String concat(String baseUrl, String... paths); static String appendRelativePath(String baseUrl, String relativePath); }
@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")); }
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); }
@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")); }
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); }
@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(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); }
@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 (NoSuchMethodException e) { method = Optional.empty(); } cache.put(entry, method); } return method; } Optional<Method> find(Class<?> clazz, String name, Class<?>... parameters); }
@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()); }
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); }
@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(); }
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); }
@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); }
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); }
@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); }