From b9957d1a6cbca15c08410d29d87a7707d8d3d367 Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Wed, 1 Mar 2017 12:30:47 +0100 Subject: [PATCH] DATAREST-1008 - Adapt to API changes in Spring Data Commons, Java 8 upgrades and Mockito 2.7. --- spring-data-rest-core/pom.xml | 21 + .../data/rest/core/UriToEntityConverter.java | 15 +- .../data/rest/core/ValidationErrors.java | 27 +- .../config/EntityLookupConfiguration.java | 13 +- .../config/RepositoryRestConfiguration.java | 1 - .../CrudMethodsSupportedHttpMethods.java | 13 +- .../core/mapping/MappingResourceMetadata.java | 5 +- .../PersistentEntitiesResourceMappings.java | 19 +- .../PersistentPropertyResourceMapping.java | 36 +- .../mapping/RepositoryResourceMappings.java | 4 +- .../rest/core/mapping/ResourceMappings.java | 4 +- .../core/support/DefaultSelfLinkProvider.java | 29 +- .../rest/core/support/DomainObjectMerger.java | 34 +- .../data/rest/core/support/EntityLookup.java | 3 +- .../UnwrappingRepositoryInvokerFactory.java | 89 +--- .../data/rest/core/util/Function.java | 26 - .../rest/core/util/Java8PluginRegistry.java | 55 +++ .../data/rest/core/util/MapUtils.java | 2 +- .../data/rest/core/util/Methods.java | 16 +- .../data/rest/core/util/Supplier.java | 28 -- .../rest/core/AbstractIntegrationTests.java | 0 .../data/rest/core/PathUnitTests.java | 21 +- ...toryRestConfigurationIntegrationTests.java | 29 +- .../RepositoryRestConfigurationUnitTests.java | 45 +- .../core/UriToEntityConverterUnitTests.java | 32 +- .../rest/core/ValidationErrorsUnitTests.java | 11 +- ...ctionDefinitionConfigurationUnitTests.java | 38 +- .../core/config/ResourceMappingUnitTests.java | 22 +- .../RepositoryEventIntegrationTests.java | 0 .../context/ValidatorIntegrationTests.java | 2 +- .../rest/core/domain/OrderRepository.java | 5 +- ...AnnotatedEventHandlerInvokerUnitTests.java | 17 +- ...dMethodsSupportedHttpMethodsUnitTests.java | 36 +- .../MappingResourceMetadataUnitTests.java | 23 +- ...stentPropertyResourceMappingUnitTests.java | 43 +- ...oryCollectionResourceMappingUnitTests.java | 37 +- ...epositoryDetectionStrategiesUnitTests.java | 5 +- ...ositoryMethodResourceMappingUnitTests.java | 27 +- ...itoryResourceMappingsIntegrationTests.java | 57 +-- ...sedCollectionResourceMappingUnitTests.java | 29 +- .../DefaultSelfLinkProviderUnitTests.java | 22 +- .../core/support/DomainObjectMergerTests.java | 13 +- .../support/DomainObjectMergerUnitTests.java | 22 +- .../support/ResourceStringUtilsTests.java | 30 +- ...pingRepositoryInvokerFactoryUnitTests.java | 47 +- .../data/rest/core/util/FunctionTests.java | 45 -- .../data/rest/core/util/MethodsUnitTests.java | 18 +- .../HalBrowserIntegrationTests.java | 7 + .../halbrowser/HalBrowserUnitTests.java | 9 +- .../AbstractControllerIntegrationTests.java | 7 + .../tests/AbstractWebIntegrationTests.java | 65 +-- .../data/rest/tests/CommonWebTests.java | 8 +- .../rest/tests/RepositoryTestsConfig.java | 5 +- .../rest/tests/gemfire/GemfireWebTests.java | 0 .../RepositoryControllerIntegrationTests.java | 21 +- ...itoryEntityControllerIntegrationTests.java | 31 +- ...tyReferenceControllerIntegrationTests.java | 0 ...itorySearchControllerIntegrationTests.java | 18 +- ...otResourceInformationIntegrationTests.java | 7 +- .../alps/AlpsControllerIntegrationTests.java | 12 +- .../rest/webmvc/jpa/CorsIntegrationTests.java | 0 .../rest/webmvc/jpa/DataRest262Tests.java | 13 +- .../rest/webmvc/jpa/DataRest363Tests.java | 0 .../jpa/JpaDefaultPageableWebTests.java | 7 +- .../data/rest/webmvc/jpa/JpaWebTests.java | 58 +-- .../webmvc/jpa/ProfileIntegrationTests.java | 20 +- ...ackson2DatatypeHelperIntegrationTests.java | 13 +- .../PersistentEntitySerializationTests.java | 31 +- .../webmvc/json/RepositoryTestsConfig.java | 5 +- ...ethodArgumentResolverIntegrationTests.java | 5 +- ...HandlingCustomizationIntegrationTests.java | 0 ...RepositoryEntityLinksIntegrationTests.java | 62 +-- .../rest/tests/mongodb/UserRepository.java | 4 +- .../rest/tests/mongodb/MongoWebTests.java | 22 +- ...tityResourceAssemblerIntegrationTests.java | 15 +- ...oryRestHandlerMappingIntegrationTests.java | 11 +- ...yRestMvcConfigurationIntegrationTests.java | 0 .../config/JsonPatchHandlerUnitTests.java | 17 +- ...yRepresentationConfigIntegrationTests.java | 0 ...andlerMethodArgumentResolverUnitTests.java | 27 +- .../PersistentEntitySerializationTests.java | 7 +- ...tEntityToJsonSchemaConverterUnitTests.java | 5 +- .../support/RepositoryLinkBuildUnitTests.java | 5 +- .../security/SecurityIntegrationTests.java | 0 .../rest/tests/shop/ShopIntegrationTests.java | 0 .../data/rest/webmvc/solr/SolrWebTests.java | 0 .../data/rest/webmvc/solr/schema.xml | 3 +- .../data/rest/webmvc/ControllerUtils.java | 28 +- .../webmvc/EmbeddedResourcesAssembler.java | 42 +- .../data/rest/webmvc/HttpHeadersPreparer.java | 49 +- .../PersistentEntityResourceAssembler.java | 2 +- .../webmvc/RepositoryEntityController.java | 60 +-- ...RepositoryPropertyReferenceController.java | 396 ++++++++-------- .../webmvc/RepositoryRestHandlerMapping.java | 56 +-- .../webmvc/RepositorySearchController.java | 38 +- .../data/rest/webmvc/ResourceStatus.java | 2 +- ...eInformationToAlpsDescriptorConverter.java | 19 +- ...ResourceHandlerMethodArgumentResolver.java | 45 +- ...ormationHandlerMethodArgumentResolver.java | 28 +- .../RepositoryRestMvcConfiguration.java | 24 +- .../rest/webmvc/json/DomainObjectReader.java | 280 ++++++----- .../JacksonMappingAwareSortTranslator.java | 32 +- .../rest/webmvc/json/MappedProperties.java | 24 +- ...wareDefaultedPageableArgumentResolver.java | 2 +- .../MappingAwarePageableArgumentResolver.java | 2 +- .../MappingAwareSortArgumentResolver.java | 2 +- .../json/PersistentEntityJackson2Module.java | 167 ++++--- ...PersistentEntityToJsonSchemaConverter.java | 445 ++++++++++-------- .../rest/webmvc/json/WrappedProperties.java | 58 +-- .../rest/webmvc/mapping/Associations.java | 13 +- .../rest/webmvc/mapping/LinkCollector.java | 24 +- ...estedLinkCollectingAssociationHandler.java | 11 +- ...ackendIdHandlerMethodArgumentResolver.java | 9 +- .../data/rest/webmvc/support/ETag.java | 68 +-- .../webmvc/support/ETagArgumentResolver.java | 6 +- .../webmvc/support/RepositoryEntityLinks.java | 8 +- .../webmvc/AssociationLinksUnitTests.java | 48 +- .../AugmentingHandlerMappingUnitTests.java | 8 +- .../data/rest/webmvc/BaseUriUnitTests.java | 13 +- ...ceptHeaderHttpServletRequestUnitTests.java | 7 +- .../rest/webmvc/IncomingRequestUnitTests.java | 11 +- .../PersistentEntityResourceUnitTests.java | 9 +- ...oryCorsConfigurationAccessorUnitTests.java | 52 +- ...yPropertyReferenceControllerUnitTests.java | 13 +- ...positoryRestExceptionHandlerUnitTests.java | 11 +- ...RepositoryRestHandlerMappingUnitTests.java | 37 +- .../RepositorySearchesResourceUnitTests.java | 5 +- .../rest/webmvc/ResourceStatusUnitTests.java | 29 +- .../RootResourceInformationUnitTests.java | 2 +- ...gAndSortingTemplateVariablesUnitTests.java | 19 +- ...ryRestMvConfigurationIntegrationTests.java | 47 +- .../json/DomainObjectReaderUnitTests.java | 113 ++--- .../webmvc/json/EnumTranslatorUnitTests.java | 43 +- .../webmvc/json/JacksonMetadataUnitTests.java | 21 +- .../json/JacksonSerializersUnitTests.java | 9 +- .../rest/webmvc/json/JsonSchemaUnitTests.java | 5 +- .../json/MappedPropertiesUnitTests.java | 27 +- ...warePageableArgumentResolverUnitTests.java | 25 +- ...rsistentEntityJackson2ModuleUnitTests.java | 27 +- .../ProjectionJacksonIntegrationTests.java | 7 +- .../webmvc/json/SortTranslatorUnitTests.java | 83 ++-- .../json/UriStringDeserializerUnitTests.java | 11 +- .../json/WrappedPropertiesUnitTests.java | 53 +-- .../webmvc/json/patch/AddOperationTests.java | 4 +- .../webmvc/json/patch/CopyOperationTests.java | 0 .../webmvc/json/patch/JsonPatchTests.java | 0 .../webmvc/json/patch/MoveOperationTests.java | 0 .../webmvc/json/patch/PathToSpelTests.java | 0 .../json/patch/RemoveOperationTests.java | 0 .../json/patch/ReplaceOperationTests.java | 0 .../webmvc/json/patch/TestOperationTests.java | 0 .../data/rest/webmvc/json/patch/Todo.java | 6 +- .../webmvc/mapping/AssociationsUnitTests.java | 36 +- .../DelegatingHandlerMappingUnitTests.java | 9 +- .../ETagDoesntMatchExceptionUnitTests.java | 0 .../rest/webmvc/support/ETagUnitTests.java | 55 ++- .../PersistentEntityProjectorUnitTests.java | 15 +- ...intViolationExceptionMessageUnitTests.java | 7 +- .../rest/webmvc/util/UriUtilsUnitTests.java | 7 +- 159 files changed, 2230 insertions(+), 2220 deletions(-) delete mode 100644 spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Function.java create mode 100644 spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Java8PluginRegistry.java delete mode 100644 spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Supplier.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/AbstractIntegrationTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/RepositoryEventIntegrationTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java delete mode 100644 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/FunctionTests.java mode change 100644 => 100755 spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java mode change 100644 => 100755 spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java mode change 100644 => 100755 spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-gemfire/src/test/java/org/springframework/data/rest/tests/gemfire/GemfireWebTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryEntityControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/alps/AlpsControllerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/CorsIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest363Tests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaDefaultPageableWebTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/ProfileIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelperIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/BackendIdConverterHandlerMethodArgumentResolverIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/ExceptionHandlingCustomizationIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinksIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssemblerIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/AbstractRepositoryRestMvcConfigurationIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/JsonPatchHandlerUnitTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/LegacyRepresentationConfigIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUnitTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverterUnitTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuildUnitTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-security/src/test/java/org/springframework/data/rest/tests/security/SecurityIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-shop/src/test/java/org/springframework/data/rest/tests/shop/ShopIntegrationTests.java mode change 100644 => 100755 spring-data-rest-tests/spring-data-rest-tests-solr/src/test/java/org/springframework/data/rest/webmvc/solr/SolrWebTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AssociationLinksUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AugmentingHandlerMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/BaseUriUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomAcceptHeaderHttpServletRequestUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/IncomingRequestUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryCorsConfigurationAccessorUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandlerUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchesResourceUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceStatusUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/ArgumentResolverPagingAndSortingTemplateVariablesUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/DomainObjectReaderUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/EnumTranslatorUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonMetadataUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonSerializersUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JsonSchemaUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappedPropertiesUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolverUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2ModuleUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/ProjectionJacksonIntegrationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/SortTranslatorUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/UriStringDeserializerUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/WrappedPropertiesUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/CopyOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/JsonPatchTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/MoveOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/PathToSpelTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/RemoveOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/ReplaceOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/TestOperationTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mapping/AssociationsUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/DelegatingHandlerMappingUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagDoesntMatchExceptionUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/PersistentEntityProjectorUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessageUnitTests.java mode change 100644 => 100755 spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/util/UriUtilsUnitTests.java diff --git a/spring-data-rest-core/pom.xml b/spring-data-rest-core/pom.xml index 83423853e..5c3722e93 100644 --- a/spring-data-rest-core/pom.xml +++ b/spring-data-rest-core/pom.xml @@ -57,6 +57,12 @@ ${jackson} + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + ${jackson} + + com.google.guava guava @@ -73,4 +79,19 @@ + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${source.level} + ${source.level} + -parameters + + + + + diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/UriToEntityConverter.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/UriToEntityConverter.java index cdaeea02b..0c50e0415 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/UriToEntityConverter.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/UriToEntityConverter.java @@ -18,6 +18,7 @@ package org.springframework.data.rest.core; import java.net.URI; import java.util.Collections; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import org.springframework.core.convert.ConversionFailedException; @@ -25,6 +26,7 @@ import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.ConditionalGenericConverter; import org.springframework.core.convert.converter.GenericConverter; import org.springframework.data.mapping.PersistentEntity; +import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.repository.support.Repositories; import org.springframework.data.repository.support.RepositoryInvokerFactory; @@ -66,9 +68,9 @@ public class UriToEntityConverter implements ConditionalGenericConverter { for (TypeInformation domainType : entities.getManagedTypes()) { Class rawType = domainType.getType(); - PersistentEntity entity = entities.getPersistentEntity(rawType); + Optional>> entity = entities.getPersistentEntity(rawType); - if (entity != null && entity.hasIdProperty()) { + if (entity.map(it -> it.hasIdProperty()).orElse(false)) { convertiblePairs.add(new ConvertiblePair(URI.class, domainType.getType())); } } @@ -86,7 +88,7 @@ public class UriToEntityConverter implements ConditionalGenericConverter { @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return !sourceType.equals(URI_TYPE) ? false - : repositories.getRepositoryInformationFor(targetType.getType()) != null; + : repositories.getRepositoryInformationFor(targetType.getType()).isPresent(); } /* @@ -105,9 +107,10 @@ public class UriToEntityConverter implements ConditionalGenericConverter { @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - PersistentEntity entity = entities.getPersistentEntity(targetType.getType()); + Optional>> entity = entities + .getPersistentEntity(targetType.getType()); - if (entity == null) { + if (!entity.isPresent()) { throw new ConversionFailedException(sourceType, targetType, source, new IllegalArgumentException("No PersistentEntity information available for " + targetType.getType())); } @@ -120,6 +123,6 @@ public class UriToEntityConverter implements ConditionalGenericConverter { "Cannot resolve URI " + uri + ". Is it local or remote? Only local URIs are resolvable.")); } - return invokerFactory.getInvokerFor(targetType.getType()).invokeFindOne(parts[parts.length - 1]); + return invokerFactory.getInvokerFor(targetType.getType()).invokeFindOne(parts[parts.length - 1]).orElse(null); } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/ValidationErrors.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/ValidationErrors.java index 0875f0231..5a6814056 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/ValidationErrors.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/ValidationErrors.java @@ -18,6 +18,7 @@ package org.springframework.data.rest.core; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import java.util.Optional; import org.springframework.beans.BeansException; import org.springframework.beans.ConfigurablePropertyAccessor; @@ -83,17 +84,11 @@ public class ValidationErrors extends AbstractPropertyBindingResult { do { String segment = iterator.next(); - PersistentEntity entity = entities.getPersistentEntity(value.getClass()); - PersistentProperty property = entity.getPersistentProperty(PropertyAccessorUtils.getPropertyName(segment)); - if (property == null) { - throw new NotReadablePropertyException(source.getClass(), propertyName); - } + Optional> property = entities.getPersistentEntity(value.getClass())// + .flatMap(it -> it.getPersistentProperty(PropertyAccessorUtils.getPropertyName(segment))); - ConfigurablePropertyAccessor accessor = property.usePropertyAccess() - ? PropertyAccessorFactory.forBeanPropertyAccess(value) - : PropertyAccessorFactory.forDirectFieldAccess(value); - value = accessor.getPropertyValue(segment); + value = getValue(value, property, segment, propertyName); } while (iterator.hasNext()); @@ -110,4 +105,18 @@ public class ValidationErrors extends AbstractPropertyBindingResult { public Object getTarget() { return source; } + + private static Object getValue(Object source, Optional> property, String segment, + String name) { + + return property.map(it -> { + + ConfigurablePropertyAccessor accessor = it.usePropertyAccess() + ? PropertyAccessorFactory.forBeanPropertyAccess(source) + : PropertyAccessorFactory.forDirectFieldAccess(source); + + return accessor.getPropertyValue(segment); + + }).orElseThrow(() -> new NotReadablePropertyException(source.getClass(), name)); + } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/EntityLookupConfiguration.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/EntityLookupConfiguration.java index b1e17e3bd..fb8a02e4d 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/EntityLookupConfiguration.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/EntityLookupConfiguration.java @@ -22,6 +22,7 @@ import lombok.Value; import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.springframework.core.convert.converter.Converter; import org.springframework.data.repository.Repository; @@ -188,11 +189,15 @@ class EntityLookupConfiguration implements EntityLookupRegistrar { Assert.notNull(repositories, "Repositories must not be null!"); Assert.notNull(lookupInformation, "LookupInformation must not be null!"); - RepositoryInformation information = repositories.getRepositoryInformation(lookupInformation.repositoryType); + RepositoryInformation information = repositories.getRepositoryInformation(lookupInformation.repositoryType)// + .orElseThrow(() -> new IllegalStateException( + "No repository found for type " + lookupInformation.repositoryType.getName() + "!")); - this.repository = (Repository) repositories.getRepositoryFor(information.getDomainType()); this.domainType = information.getDomainType(); this.lookupInfo = lookupInformation; + this.repository = (Repository) repositories.getRepositoryFor(information.getDomainType())// + .orElseThrow(() -> new IllegalStateException( + "No repository found for type " + information.getDomainType().getName() + "!")); } /* @@ -209,8 +214,8 @@ class EntityLookupConfiguration implements EntityLookupRegistrar { * @see org.springframework.data.rest.core.support.EntityLookup#lookupEntity(java.io.Serializable) */ @Override - public Object lookupEntity(Serializable id) { - return lookupInfo.getLookup().lookup(repository, id); + public Optional lookupEntity(Serializable id) { + return Optional.ofNullable(lookupInfo.getLookup().lookup(repository, id)); } /* diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/RepositoryRestConfiguration.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/RepositoryRestConfiguration.java index 4d8d7de1a..7d16825f3 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/RepositoryRestConfiguration.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/RepositoryRestConfiguration.java @@ -64,7 +64,6 @@ public class RepositoryRestConfiguration { private final ProjectionDefinitionConfiguration projectionConfiguration; private final MetadataConfiguration metadataConfiguration; private final EntityLookupConfiguration entityLookupConfiguration; - private final List> valueTypes = new ArrayList>(); private final EnumTranslationConfiguration enumTranslationConfiguration; private boolean enableEnumTranslation = false; diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethods.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethods.java index fcdf637e6..268a873d6 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethods.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethods.java @@ -24,6 +24,7 @@ import lombok.RequiredArgsConstructor; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import org.springframework.core.annotation.AnnotationUtils; @@ -179,14 +180,14 @@ public class CrudMethodsSupportedHttpMethods implements SupportedHttpMethods { return exposes(crudMethods.getFindAllMethod()); } - private static boolean exposes(Method method) { + private static boolean exposes(Optional method) { - if (method == null) { - return false; - } + return method.map(it -> { - RestResource annotation = AnnotationUtils.findAnnotation(method, RestResource.class); - return annotation == null ? true : annotation.exported(); + RestResource annotation = AnnotationUtils.findAnnotation(it, RestResource.class); + return annotation == null ? true : annotation.exported(); + + }).orElse(false); } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/MappingResourceMetadata.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/MappingResourceMetadata.java index f5e676b14..a1eeb2c02 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/MappingResourceMetadata.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/MappingResourceMetadata.java @@ -18,6 +18,7 @@ package org.springframework.data.rest.core.mapping; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import org.springframework.data.mapping.Association; import org.springframework.data.mapping.PersistentEntity; @@ -55,8 +56,8 @@ class MappingResourceMetadata extends TypeBasedCollectionResourceMapping impleme this.entity.doWithAssociations(propertyMappings); this.entity.doWithProperties(propertyMappings); - RestResource annotation = entity.findAnnotation(RestResource.class); - this.explicitlyExported = annotation != null && annotation.exported(); + Optional annotation = entity.findAnnotation(RestResource.class); + this.explicitlyExported = annotation.map(it -> it.exported()).orElse(false); } /* diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentEntitiesResourceMappings.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentEntitiesResourceMappings.java index 26809184c..e2b40b349 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentEntitiesResourceMappings.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentEntitiesResourceMappings.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.springframework.data.mapping.PersistentEntity; @@ -84,23 +85,23 @@ public class PersistentEntitiesResourceMappings implements ResourceMappings { MappingResourceMetadata getMappingMetadataFor(Class type) { Assert.notNull(type, "Type must not be null!"); - type = ClassUtils.getUserClass(type); + Class userType = ClassUtils.getUserClass(type); - MappingResourceMetadata mappingMetadata = mappingCache.get(type); + MappingResourceMetadata mappingMetadata = mappingCache.get(userType); if (mappingMetadata != null) { return mappingMetadata; } - PersistentEntity entity = entities.getPersistentEntity(type); + Optional>> entity = entities.getPersistentEntity(userType); - if (entity == null) { - return null; - } + return entity.map(it -> { - mappingMetadata = new MappingResourceMetadata(entity, this); - mappingCache.put(type, mappingMetadata); - return mappingMetadata; + MappingResourceMetadata metadata = new MappingResourceMetadata(it, this); + mappingCache.put(userType, metadata); + return metadata; + + }).orElse(null); } /* diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMapping.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMapping.java index 755a58488..8bf279f7a 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMapping.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMapping.java @@ -15,10 +15,13 @@ */ package org.springframework.data.rest.core.mapping; +import java.util.Optional; + import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.rest.core.Path; import org.springframework.data.rest.core.annotation.Description; import org.springframework.data.rest.core.annotation.RestResource; +import org.springframework.data.util.Optionals; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -31,8 +34,8 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping private final PersistentProperty property; private final ResourceMappings mappings; - private final RestResource annotation; - private final Description description; + private final Optional annotation; + private final Optional description; /** * Creates a new {@link RootPropertyResourceMapping}. @@ -46,7 +49,7 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping this.property = property; this.mappings = mappings; - this.annotation = property.isAssociation() ? property.findAnnotation(RestResource.class) : null; + this.annotation = property.isAssociation() ? property.findAnnotation(RestResource.class) : Optional.empty(); this.description = property.findAnnotation(Description.class); } @@ -56,8 +59,10 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping */ @Override public Path getPath() { - return annotation != null && StringUtils.hasText(annotation.path()) ? new Path(annotation.path()) : new Path( - property.getName()); + + return annotation.filter(it -> StringUtils.hasText(it.path()))// + .map(it -> new Path(it.path()))// + .orElseGet(() -> new Path(property.getName())); } /* @@ -66,7 +71,10 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping */ @Override public String getRel() { - return annotation != null && StringUtils.hasText(annotation.rel()) ? annotation.rel() : property.getName(); + + return annotation.filter(it -> StringUtils.hasText(it.rel()))// + .map(it -> it.rel())// + .orElseGet(() -> property.getName()); } /* @@ -81,7 +89,7 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping } ResourceMapping typeMapping = mappings.getMetadataFor(property.getActualType()); - return !typeMapping.isExported() ? false : annotation == null ? true : annotation.exported(); + return !typeMapping.isExported() ? false : annotation.map(it -> it.exported()).orElse(true); } /* @@ -103,15 +111,11 @@ class PersistentPropertyResourceMapping implements PropertyAwareResourceMapping CollectionResourceMapping ownerTypeMapping = mappings.getMetadataFor(property.getOwner().getType()); ResourceDescription fallback = TypedResourceDescription.defaultFor(ownerTypeMapping.getItemResourceRel(), property); - if (description != null) { - return new AnnotationBasedResourceDescription(description, fallback); - } - - if (annotation != null) { - return new AnnotationBasedResourceDescription(annotation.description(), fallback); - } - - return fallback; + return Optionals + . firstNonEmpty(// + () -> description.map(it -> new AnnotationBasedResourceDescription(it, fallback)), // + () -> annotation.map(it -> new AnnotationBasedResourceDescription(it.description(), fallback))) + .orElse(fallback); } /* diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappings.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappings.java index dfd536804..e3d7a7fe5 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappings.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappings.java @@ -81,7 +81,7 @@ public class RepositoryResourceMappings extends PersistentEntitiesResourceMappin for (Class type : repositories) { - RepositoryInformation repositoryInformation = repositories.getRepositoryInformationFor(type); + RepositoryInformation repositoryInformation = repositories.getRequiredRepositoryInformation(type); Class repositoryInterface = repositoryInformation.getRepositoryInterface(); PersistentEntity entity = repositories.getPersistentEntity(type); @@ -111,7 +111,7 @@ public class RepositoryResourceMappings extends PersistentEntitiesResourceMappin return searchCache.get(domainType); } - RepositoryInformation repositoryInformation = repositories.getRepositoryInformationFor(domainType); + RepositoryInformation repositoryInformation = repositories.getRequiredRepositoryInformation(domainType); List mappings = new ArrayList(); ResourceMetadata resourceMapping = getMetadataFor(domainType); diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/ResourceMappings.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/ResourceMappings.java index 814fa72e2..bd34e6133 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/ResourceMappings.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/mapping/ResourceMappings.java @@ -15,10 +15,12 @@ */ package org.springframework.data.rest.core.mapping; +import org.springframework.data.util.Streamable; + /** * @author Oliver Gierke */ -public interface ResourceMappings extends Iterable { +public interface ResourceMappings extends Streamable { /** * Returns a {@link ResourceMetadata} for the given type if available. diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DefaultSelfLinkProvider.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DefaultSelfLinkProvider.java index 50c17b2cf..a29eb6afe 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DefaultSelfLinkProvider.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DefaultSelfLinkProvider.java @@ -17,12 +17,10 @@ package org.springframework.data.rest.core.support; import java.util.List; -import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.context.PersistentEntities; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.hateoas.EntityLinks; import org.springframework.hateoas.Link; -import org.springframework.plugin.core.OrderAwarePluginRegistry; -import org.springframework.plugin.core.PluginRegistry; import org.springframework.util.Assert; /** @@ -37,7 +35,7 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider { private final PersistentEntities entities; private final EntityLinks entityLinks; - private final PluginRegistry, Class> lookups; + private final Java8PluginRegistry, Class> lookups; /** * Creates a new {@link DefaultSelfLinkProvider} from the {@link PersistentEntities}, {@link EntityLinks} and @@ -56,7 +54,7 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider { this.entities = entities; this.entityLinks = entityLinks; - this.lookups = OrderAwarePluginRegistry.create(lookups); + this.lookups = Java8PluginRegistry.of(lookups); } /* @@ -81,19 +79,16 @@ public class DefaultSelfLinkProvider implements SelfLinkProvider { Class instanceType = instance.getClass(); - EntityLookup lookup = (EntityLookup) lookups.getPluginFor(instanceType); + return lookups.getPluginFor(instanceType)// + .map(it -> it.getClass().cast(it))// + .map(it -> (Object) it.getResourceIdentifier(instance))// + .orElseGet(() -> identifierOrNull(instance)); + } - if (lookup != null) { - return lookup.getResourceIdentifier(instance); - } + private Object identifierOrNull(Object instance) { - PersistentEntity entity = entities.getPersistentEntity(instanceType); - - if (entity == null) { - throw new IllegalArgumentException( - String.format("Cannot create self link for %s! No persistent entity found!", instanceType)); - } - - return entity.getIdentifierAccessor(instance).getIdentifier(); + return entities.getRequiredPersistentEntity(instance.getClass())// + .getIdentifierAccessor(instance).getIdentifier()// + .orElse(null); } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DomainObjectMerger.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DomainObjectMerger.java index 095b01855..86acb036e 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DomainObjectMerger.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/DomainObjectMerger.java @@ -17,6 +17,8 @@ package org.springframework.data.rest.core.support; import static org.springframework.data.rest.core.support.DomainObjectMerger.NullHandlingPolicy.*; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.data.mapping.Association; @@ -87,18 +89,18 @@ public class DomainObjectMerger { @Override public void doWithPersistentProperty(PersistentProperty persistentProperty) { - Object sourceValue = sourceWrapper.getProperty(persistentProperty); - Object targetValue = targetWrapper.getProperty(persistentProperty); + Optional sourceValue = sourceWrapper.getProperty(persistentProperty); + Optional targetValue = targetWrapper.getProperty(persistentProperty); if (targetEntity.isIdProperty(persistentProperty)) { return; } - if (ObjectUtils.nullSafeEquals(sourceValue, targetValue)) { + if (sourceValue.equals(targetValue)) { return; } - if (nullPolicy == APPLY_NULLS || sourceValue != null) { + if (nullPolicy == APPLY_NULLS || sourceValue.isPresent()) { targetWrapper.setProperty(persistentProperty, sourceValue); } } @@ -114,7 +116,7 @@ public class DomainObjectMerger { public void doWithAssociation(Association> association) { PersistentProperty persistentProperty = association.getInverse(); - Object fromVal = sourceWrapper.getProperty(persistentProperty); + Optional fromVal = sourceWrapper.getProperty(persistentProperty); if (!isNullOrEmpty(fromVal) && !fromVal.equals(targetWrapper.getProperty(persistentProperty))) { targetWrapper.setProperty(persistentProperty, fromVal); @@ -130,21 +132,21 @@ public class DomainObjectMerger { * @param source can be {@literal null}. * @return */ - static boolean isNullOrEmpty(Object source) { + static boolean isNullOrEmpty(Optional source) { - if (source == null) { - return true; - } + return source.map(it -> { - if (source instanceof Iterable) { - return !((Iterable) source).iterator().hasNext(); - } + if (it instanceof Iterable) { + return !((Iterable) it).iterator().hasNext(); + } - if (ObjectUtils.isArray(source)) { - return ObjectUtils.isEmpty((Object[]) source); - } + if (ObjectUtils.isArray(it)) { + return ObjectUtils.isEmpty((Object[]) it); + } - return false; + return false; + + }).orElse(true); } /** diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/EntityLookup.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/EntityLookup.java index bc3ecfcf2..808bfc785 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/EntityLookup.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/EntityLookup.java @@ -16,6 +16,7 @@ package org.springframework.data.rest.core.support; import java.io.Serializable; +import java.util.Optional; import org.springframework.plugin.core.Plugin; @@ -54,5 +55,5 @@ public interface EntityLookup extends Plugin> { * @param id will never be {@literal null}. * @return can be {@literal null}. */ - Object lookupEntity(Serializable id); + Optional lookupEntity(Serializable id); } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactory.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactory.java index fbe5147d7..bb6f2dc9e 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactory.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactory.java @@ -20,11 +20,7 @@ import lombok.RequiredArgsConstructor; import java.io.Serializable; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; -import java.util.Map; import java.util.Optional; import org.springframework.core.convert.converter.Converter; @@ -32,10 +28,8 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.repository.support.RepositoryInvoker; import org.springframework.data.repository.support.RepositoryInvokerFactory; -import org.springframework.plugin.core.OrderAwarePluginRegistry; -import org.springframework.plugin.core.PluginRegistry; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.util.MultiValueMap; /** @@ -46,42 +40,8 @@ import org.springframework.util.MultiValueMap; */ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFactory { - private static final List> CONVERTERS; - - static { - - List> converters = new ArrayList>(); - ClassLoader classLoader = UnwrappingRepositoryInvokerFactory.class.getClassLoader(); - - // Add unwrapper for Java 8 Optional - - if (ClassUtils.isPresent("java.util.Optional", classLoader)) { - converters.add(new Converter() { - @Override - public Object convert(Object source) { - return source instanceof Optional ? ((Optional) source).orElse(null) : source; - } - }); - } - - // Add unwrapper for Guava Optional - - if (ClassUtils.isPresent("com.google.common.base.Optional", classLoader)) { - - converters.add(new Converter() { - @Override - public Object convert(Object source) { - return source instanceof com.google.common.base.Optional - ? ((com.google.common.base.Optional) source).orNull() : source; - } - }); - } - - CONVERTERS = Collections.unmodifiableList(converters); - } - private final RepositoryInvokerFactory delegate; - private final PluginRegistry, Class> lookups; + private final Java8PluginRegistry, Class> lookups; /** * @param delegate must not be {@literal null}. @@ -94,7 +54,7 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact Assert.notNull(lookups, "EntityLookups must not be null!"); this.delegate = delegate; - this.lookups = OrderAwarePluginRegistry.create(lookups); + this.lookups = Java8PluginRegistry.of(lookups); } /* @@ -104,9 +64,9 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact @Override public RepositoryInvoker getInvokerFor(Class domainType) { - EntityLookup lookup = lookups.getPluginFor(domainType); + Optional> lookup = lookups.getPluginFor(domainType); - return new UnwrappingRepositoryInvoker(delegate.getInvokerFor(domainType), CONVERTERS, lookup); + return new UnwrappingRepositoryInvoker(delegate.getInvokerFor(domainType), lookup); } /** @@ -119,25 +79,18 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact private static class UnwrappingRepositoryInvoker implements RepositoryInvoker { private final @NonNull RepositoryInvoker delegate; - private final @NonNull Collection> converters; - private final EntityLookup lookup; + private final @NonNull Optional> lookup; /* * (non-Javadoc) * @see org.springframework.data.repository.support.RepositoryInvoker#invokeFindOne(java.io.Serializable) */ - public T invokeFindOne(Serializable id) { - return postProcess(lookup != null ? lookup.lookupEntity(id) : delegate.invokeFindOne(id)); - } + @SuppressWarnings("unchecked") + public Optional invokeFindOne(Serializable id) { - /* - * (non-Javadoc) - * @see org.springframework.data.repository.support.RepositoryInvoker#invokeQueryMethod(java.lang.reflect.Method, java.util.Map, org.springframework.data.domain.Pageable, org.springframework.data.domain.Sort) - */ - @Override - @SuppressWarnings("deprecation") - public Object invokeQueryMethod(Method method, Map parameters, Pageable pageable, Sort sort) { - return postProcess(delegate.invokeQueryMethod(method, parameters, pageable, sort)); + return (Optional) lookup// + .map(it -> it.lookupEntity(id).orElse(Optional.empty()))// + .orElseGet(() -> delegate.invokeFindOne(id)); } /* @@ -145,9 +98,9 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact * @see org.springframework.data.repository.support.RepositoryInvoker#invokeQueryMethod(java.lang.reflect.Method, org.springframework.util.MultiValueMap, org.springframework.data.domain.Pageable, org.springframework.data.domain.Sort) */ @Override - public Object invokeQueryMethod(Method method, MultiValueMap parameters, + public Optional invokeQueryMethod(Method method, MultiValueMap parameters, Pageable pageable, Sort sort) { - return postProcess(delegate.invokeQueryMethod(method, parameters, pageable, sort)); + return delegate.invokeQueryMethod(method, parameters, pageable, sort); } /* @@ -221,21 +174,5 @@ public class UnwrappingRepositoryInvokerFactory implements RepositoryInvokerFact public T invokeSave(T object) { return delegate.invokeSave(object); } - - /** - * Invokes the configured converters for the given result. - * - * @param result can be {@literal null}. - * @return - */ - @SuppressWarnings("unchecked") - private T postProcess(Object result) { - - for (Converter converter : converters) { - result = converter.convert(result); - } - - return (T) result; - } } } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Function.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Function.java deleted file mode 100644 index 150d63f12..000000000 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Function.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.rest.core.util; - -/** - * Simple function interface. - * - * @author Oliver Gierke - */ -public interface Function { - - T apply(S input) throws Exception; -} diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Java8PluginRegistry.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Java8PluginRegistry.java new file mode 100644 index 000000000..a6f31bccb --- /dev/null +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Java8PluginRegistry.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.rest.core.util; + +import lombok.RequiredArgsConstructor; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.springframework.plugin.core.OrderAwarePluginRegistry; +import org.springframework.plugin.core.Plugin; +import org.springframework.plugin.core.PluginRegistry; + +/** + * @author Oliver Gierke + */ +@RequiredArgsConstructor +public class Java8PluginRegistry, S> { + + private final PluginRegistry registry; + + public static , S> Java8PluginRegistry of(List plugins) { + return Java8PluginRegistry.of(OrderAwarePluginRegistry.create(plugins)); + } + + public static , S> Java8PluginRegistry of(PluginRegistry plugins) { + return new Java8PluginRegistry<>(plugins); + } + + public static , S> Java8PluginRegistry empty() { + return Java8PluginRegistry.of(Collections.emptyList()); + } + + public Optional getPluginFor(S delimiter) { + return Optional.ofNullable(registry.getPluginFor(delimiter)); + } + + public T getPluginOrDefaultFor(S delimiter, T fallback) { + return getPluginFor(delimiter).orElse(fallback); + } +} diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java index fc85c546a..da186f12d 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/MapUtils.java @@ -29,7 +29,7 @@ import org.springframework.util.MultiValueMap; * * @author Oliver Gierke */ -public abstract class MapUtils { +public interface MapUtils { /** * Turns a {@link MultiValueMap} into its {@link Map} equivalent. diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Methods.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Methods.java index 2bcd086c8..1a1be0731 100644 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Methods.java +++ b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Methods.java @@ -26,11 +26,9 @@ import org.springframework.util.ReflectionUtils; * @author Jon Brisbin * @author Oliver Gierke */ -public abstract class Methods { +public interface Methods { - private Methods() {} - - public static final ReflectionUtils.MethodFilter USER_METHODS = new ReflectionUtils.MethodFilter() { + static final ReflectionUtils.MethodFilter USER_METHODS = new ReflectionUtils.MethodFilter() { /* * (non-Javadoc) @@ -38,12 +36,12 @@ public abstract class Methods { */ @Override public boolean matches(Method method) { - + return !method.isSynthetic() && // - !method.isBridge() && // - !ReflectionUtils.isObjectMethod(method) && // - !ClassUtils.isCglibProxyClass(method.getDeclaringClass()) && // - !ReflectionUtils.isCglibRenamedMethod(method); + !method.isBridge() && // + !ReflectionUtils.isObjectMethod(method) && // + !ClassUtils.isCglibProxyClass(method.getDeclaringClass()) && // + !ReflectionUtils.isCglibRenamedMethod(method); } }; } diff --git a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Supplier.java b/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Supplier.java deleted file mode 100644 index fe506c483..000000000 --- a/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/util/Supplier.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.rest.core.util; - -/** - * Mimics Java 8's Supplier interface to allow deferring a computation. - * - * @author Oliver Gierke - * @since 2.6 - * @soundtrack KRS-One - Sound Of Da Police (Return Of The Boom Bap) - */ -public interface Supplier { - - T get(); -} diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/AbstractIntegrationTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/AbstractIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java old mode 100644 new mode 100755 index 9fb197d63..bfc54acf5 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/PathUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; @@ -31,50 +30,50 @@ public class PathUnitTests { public void combinesSimplePaths() { Path builder = new Path("foo").slash("bar"); - assertThat(builder.toString(), is("/foo/bar")); + assertThat(builder.toString()).isEqualTo("/foo/bar"); } @Test public void removesLeadingAndTrailingSlashes() { Path builder = new Path("foo/").slash("/bar").slash("//foobar///"); - assertThat(builder.toString(), is("/foo/bar/foobar")); + assertThat(builder.toString()).isEqualTo("/foo/bar/foobar"); } @Test public void removesWhitespace() { Path builder = new Path("foo/ ").slash("/ b a r").slash(" //foobar/// "); - assertThat(builder.toString(), is("/foo/bar/foobar")); + assertThat(builder.toString()).isEqualTo("/foo/bar/foobar"); } @Test public void matchesWithLeadingSlash() { - assertThat(new Path("/foobar").matches("/foobar"), is(true)); + assertThat(new Path("/foobar").matches("/foobar")).isTrue(); } @Test public void matchesWithoutLeadingSlash() { - assertThat(new Path("/foobar").matches("foobar"), is(true)); + assertThat(new Path("/foobar").matches("foobar")).isTrue(); } @Test public void doesNotMatchIfDifferent() { - assertThat(new Path("/foobar").matches("barfoo"), is(false)); + assertThat(new Path("/foobar").matches("barfoo")).isFalse(); } @Test public void doesNotPrefixAbsoluteUris() { - assertThat(new Path("http://localhost").toString(), is("http://localhost")); + assertThat(new Path("http://localhost").toString()).isEqualTo("http://localhost"); } @Test // DATAREST-222 public void doesNotMatchIfReferenceContainsReservedCharacters() { - assertThat(new Path("/foobar").matches("barfoo{?foo}"), is(false)); + assertThat(new Path("/foobar").matches("barfoo{?foo}")).isFalse(); } @Test // DATAREST-222 public void doesNotMatchNullReference() { - assertThat(new Path("/foobar").matches(null), is(false)); + assertThat(new Path("/foobar").matches(null)).isFalse(); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java old mode 100644 new mode 100755 index 82aac1f17..32bb4564a --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationIntegrationTests.java @@ -1,7 +1,21 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.data.rest.core; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +27,7 @@ import org.springframework.data.rest.core.domain.ConfiguredPersonRepository; * Tests to check that {@link ResourceMapping}s are handled correctly. * * @author Jon Brisbin + * @author Oliver Gierke */ @SuppressWarnings("deprecation") public class RepositoryRestConfigurationIntegrationTests extends AbstractIntegrationTests { @@ -21,12 +36,12 @@ public class RepositoryRestConfigurationIntegrationTests extends AbstractIntegra @Test public void shouldProvideResourceMappingForConfiguredRepository() throws Exception { + ResourceMapping mapping = config.getResourceMappingForRepository(ConfiguredPersonRepository.class); - assertThat(mapping, notNullValue()); - assertThat(mapping.getRel(), is("people")); - assertThat(mapping.getPath(), is("people")); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping).isNotNull(); + assertThat(mapping.getRel()).isEqualTo("people"); + assertThat(mapping.getPath()).isEqualTo("people"); + assertThat(mapping.isExported()).isFalse(); } - } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java old mode 100644 new mode 100755 index 3f961eb93..ed3ad2a42 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/RepositoryRestConfigurationUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Map; @@ -54,22 +53,22 @@ public class RepositoryRestConfigurationUnitTests { @Test // DATAREST-34 public void returnsBodiesIfAcceptHeaderPresentByDefault() { - assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(true)); - assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(true)); + assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isTrue(); + assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isTrue(); } @Test // DATAREST-34 public void doesNotReturnBodiesIfNoAcceptHeaderPresentByDefault() { - assertThat(configuration.returnBodyOnCreate(null), is(false)); - assertThat(configuration.returnBodyOnUpdate(null), is(false)); + assertThat(configuration.returnBodyOnCreate(null)).isFalse(); + assertThat(configuration.returnBodyOnUpdate(null)).isFalse(); } @Test // DATAREST-34 public void doesNotReturnBodiesIfEmptyAcceptHeaderPresentByDefault() { - assertThat(configuration.returnBodyOnCreate(""), is(false)); - assertThat(configuration.returnBodyOnUpdate(""), is(false)); + assertThat(configuration.returnBodyOnCreate("")).isFalse(); + assertThat(configuration.returnBodyOnUpdate("")).isFalse(); } @Test // DATAREST-34 @@ -77,9 +76,9 @@ public class RepositoryRestConfigurationUnitTests { configuration.setReturnBodyOnUpdate(false); - assertThat(configuration.returnBodyOnUpdate(null), is(false)); - assertThat(configuration.returnBodyOnUpdate(""), is(false)); - assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(false)); + assertThat(configuration.returnBodyOnUpdate(null)).isFalse(); + assertThat(configuration.returnBodyOnUpdate("")).isFalse(); + assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isFalse(); } @Test // DATAREST-34 @@ -87,9 +86,9 @@ public class RepositoryRestConfigurationUnitTests { configuration.setReturnBodyOnCreate(false); - assertThat(configuration.returnBodyOnCreate(null), is(false)); - assertThat(configuration.returnBodyOnCreate(""), is(false)); - assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(false)); + assertThat(configuration.returnBodyOnCreate(null)).isFalse(); + assertThat(configuration.returnBodyOnCreate("")).isFalse(); + assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isFalse(); } @Test // DATAREST-34 @@ -97,9 +96,9 @@ public class RepositoryRestConfigurationUnitTests { configuration.setReturnBodyOnUpdate(true); - assertThat(configuration.returnBodyOnUpdate(null), is(true)); - assertThat(configuration.returnBodyOnUpdate(""), is(true)); - assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE), is(true)); + assertThat(configuration.returnBodyOnUpdate(null)).isTrue(); + assertThat(configuration.returnBodyOnUpdate("")).isTrue(); + assertThat(configuration.returnBodyOnUpdate(MediaType.APPLICATION_JSON_VALUE)).isTrue(); } @Test // DATAREST-34 @@ -107,9 +106,9 @@ public class RepositoryRestConfigurationUnitTests { configuration.setReturnBodyOnCreate(true); - assertThat(configuration.returnBodyOnCreate(null), is(true)); - assertThat(configuration.returnBodyOnCreate(""), is(true)); - assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE), is(true)); + assertThat(configuration.returnBodyOnCreate(null)).isTrue(); + assertThat(configuration.returnBodyOnCreate("")).isTrue(); + assertThat(configuration.returnBodyOnCreate(MediaType.APPLICATION_JSON_VALUE)).isTrue(); } @Test // DATAREST-776 @@ -117,7 +116,7 @@ public class RepositoryRestConfigurationUnitTests { configuration.withEntityLookup().forLookupRepository(ProfileRepository.class); - assertThat(configuration.isLookupType(Profile.class), is(true)); + assertThat(configuration.isLookupType(Profile.class)).isTrue(); } @Test // DATAREST-573 @@ -127,9 +126,9 @@ public class RepositoryRestConfigurationUnitTests { registry.addMapping("/hello").maxAge(1234); Map corsConfigurations = registry.getCorsConfigurations(); - assertThat(corsConfigurations, hasKey("/hello")); + assertThat(corsConfigurations).containsKey("/hello"); CorsConfiguration corsConfiguration = corsConfigurations.get("/hello"); - assertThat(corsConfiguration.getMaxAge(), is(1234L)); + assertThat(corsConfiguration.getMaxAge()).isEqualTo(1234L); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java old mode 100644 new mode 100755 index 2c1de48cc..88d94d16f --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/UriToEntityConverterUnitTests.java @@ -15,20 +15,20 @@ */ package org.springframework.data.rest.core; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.net.URI; import java.util.Arrays; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair; @@ -40,6 +40,7 @@ import org.springframework.data.repository.support.Repositories; import org.springframework.data.repository.support.RepositoryInvoker; import org.springframework.data.repository.support.RepositoryInvokerFactory; import org.springframework.data.util.ClassTypeInformation; +import org.springframework.data.util.Streamable; /** * Unit tests for {@link UriToEntityConverter}. @@ -56,14 +57,13 @@ public class UriToEntityConverterUnitTests { @Mock Repositories repositories; @Mock RepositoryInvokerFactory invokerFactory; - KeyValueMappingContext context; + KeyValueMappingContext context; UriToEntityConverter converter; @Before - @SuppressWarnings("unchecked") public void setUp() { - this.context = new KeyValueMappingContext(); + this.context = new KeyValueMappingContext<>(); this.context.setInitialEntitySet(new HashSet>(Arrays.asList(Entity.class, NonEntity.class))); this.context.afterPropertiesSet(); @@ -76,26 +76,27 @@ public class UriToEntityConverterUnitTests { Set result = converter.getConvertibleTypes(); - assertThat(result, hasItem(new ConvertiblePair(URI.class, Entity.class))); - assertThat(result, not(hasItem(new ConvertiblePair(URI.class, NonEntity.class)))); + assertThat(result).contains(new ConvertiblePair(URI.class, Entity.class)); + assertThat(result).doesNotContain(new ConvertiblePair(URI.class, NonEntity.class)); } @Test // DATAREST-427 public void cannotConvertEntityWithIdPropertyIfStringConversionMissing() { - assertThat(converter.matches(URI_TYPE, ENTITY_TYPE), is(false)); + assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isFalse(); } @Test // DATAREST-427 public void canConvertEntityWithIdPropertyAndFromStringConversionPossible() { - doReturn(mock(RepositoryInformation.class)).when(repositories).getRepositoryInformationFor(ENTITY_TYPE.getType()); + doReturn(Optional.of(mock(RepositoryInformation.class))).when(repositories) + .getRepositoryInformationFor(ENTITY_TYPE.getType()); - assertThat(converter.matches(URI_TYPE, ENTITY_TYPE), is(true)); + assertThat(converter.matches(URI_TYPE, ENTITY_TYPE)).isTrue(); } @Test // DATAREST-427 public void cannotConvertEntityWithoutIdentifier() { - assertThat(converter.matches(URI_TYPE, TypeDescriptor.valueOf(NonEntity.class)), is(false)); + assertThat(converter.matches(URI_TYPE, TypeDescriptor.valueOf(NonEntity.class))).isFalse(); } @Test // DATAREST-427 @@ -104,10 +105,10 @@ public class UriToEntityConverterUnitTests { Entity reference = new Entity(); RepositoryInvoker invoker = mock(RepositoryInvoker.class); - doReturn(reference).when(invoker).invokeFindOne("1"); + doReturn(Optional.of(reference)).when(invoker).invokeFindOne("1"); doReturn(invoker).when(invokerFactory).getInvokerFor(ENTITY_TYPE.getType()); - assertThat(converter.convert(URI.create("/foo/bar/1"), URI_TYPE, ENTITY_TYPE), is((Object) reference)); + assertThat(converter.convert(URI.create("/foo/bar/1"), URI_TYPE, ENTITY_TYPE)).isEqualTo((Object) reference); } @Test(expected = ConversionFailedException.class) // DATAREST-427 @@ -139,11 +140,10 @@ public class UriToEntityConverterUnitTests { * @see DATAREST-1018 */ @Test - @SuppressWarnings("unchecked") public void doesNotRegisterTypeWithUnmanagedRawType() { PersistentEntities entities = mock(PersistentEntities.class); - doReturn(Arrays.asList(ClassTypeInformation.OBJECT)).when(entities).getManagedTypes(); + doReturn(Streamable.of(ClassTypeInformation.OBJECT)).when(entities).getManagedTypes(); new UriToEntityConverter(entities, invokerFactory, repositories); } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java old mode 100644 new mode 100755 index 8cafbfca7..352aaf421 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/ValidationErrorsUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; import java.util.Collections; @@ -41,7 +40,7 @@ public class ValidationErrorsUnitTests { @Before public void setUp() { - KeyValueMappingContext context = new KeyValueMappingContext(); + KeyValueMappingContext context = new KeyValueMappingContext<>(); context.getPersistentEntity(Foo.class); this.entities = new PersistentEntities(Arrays.asList(context)); @@ -56,7 +55,7 @@ public class ValidationErrorsUnitTests { errors.rejectValue("field", "asdf"); errors.popNestedPath(); - assertThat(errors.getFieldError().getField(), is("bars[0].field")); + assertThat(errors.getFieldError().getField()).isEqualTo("bars[0].field"); } @Test // DATAREST-801 @@ -66,7 +65,7 @@ public class ValidationErrorsUnitTests { private static void expectedErrorBehavior(Errors errors) { - assertThat(errors.getFieldValue("bars"), is(notNullValue())); + assertThat(errors.getFieldValue("bars")).isNotNull(); errors.pushNestedPath("bars[0]"); @@ -75,7 +74,7 @@ public class ValidationErrorsUnitTests { fail("Expected NotReadablePropertyException!"); } catch (NotReadablePropertyException e) {} - assertThat(errors.getFieldValue("field"), is((Object) "Hello")); + assertThat(errors.getFieldValue("field")).isEqualTo((Object) "Hello"); } static class Foo { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java old mode 100644 new mode 100755 index b4d6dcb70..8533f524e --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ProjectionDefinitionConfigurationUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.config; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Map; @@ -28,7 +27,6 @@ import org.springframework.data.rest.core.config.ProjectionDefinitionConfigurati * * @author Oliver Gierke */ -@SuppressWarnings("rawtypes") public class ProjectionDefinitionConfigurationUnitTests { @Test(expected = IllegalArgumentException.class) // DATAREST-221 @@ -67,7 +65,7 @@ public class ProjectionDefinitionConfigurationUnitTests { ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration(); configuration.addProjection(Integer.class, "name", String.class); - assertThat(configuration.getProjectionType(String.class, "name"), is(equalTo((Class) Integer.class))); + assertThat(configuration.getProjectionType(String.class, "name")).isEqualTo(Integer.class); } @Test // DATAREST-221 @@ -76,7 +74,7 @@ public class ProjectionDefinitionConfigurationUnitTests { ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration(); configuration.addProjection(SampleProjection.class); - assertThat(configuration.getProjectionType(Integer.class, "name"), is(equalTo((Class) SampleProjection.class))); + assertThat(configuration.getProjectionType(Integer.class, "name")).isEqualTo(SampleProjection.class); } @Test // DATAREST-221 @@ -85,7 +83,7 @@ public class ProjectionDefinitionConfigurationUnitTests { ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration(); configuration.addProjection(Default.class); - assertThat(configuration.getProjectionType(Integer.class, "default"), is(equalTo((Class) Default.class))); + assertThat(configuration.getProjectionType(Integer.class, "default")).isEqualTo(Default.class); } @Test // DATAREST-221 @@ -96,17 +94,17 @@ public class ProjectionDefinitionConfigurationUnitTests { ProjectionDefinition stringName = ProjectionDefinition.of(String.class, Object.class, "name"); ProjectionDefinition objectOtherNameKey = ProjectionDefinition.of(Object.class, Object.class, "otherName"); - assertThat(objectName, is(objectName)); - assertThat(objectName, is(sameObjectName)); - assertThat(sameObjectName, is(objectName)); + assertThat(objectName).isEqualTo(objectName); + assertThat(objectName).isEqualTo(sameObjectName); + assertThat(sameObjectName).isEqualTo(objectName); - assertThat(objectName, is(not(stringName))); - assertThat(stringName, is(not(objectName))); + assertThat(objectName).isNotEqualTo(stringName); + assertThat(stringName).isNotEqualTo(objectName); - assertThat(objectName, is(not(objectOtherNameKey))); - assertThat(objectOtherNameKey, is(not(objectName))); + assertThat(objectName).isNotEqualTo(objectOtherNameKey); + assertThat(objectOtherNameKey).isNotEqualTo(objectName); - assertThat(objectName, is(not(new Object()))); + assertThat(objectName).isNotEqualTo(new Object()); } @Test // DATAREST-385 @@ -115,14 +113,14 @@ public class ProjectionDefinitionConfigurationUnitTests { ProjectionDefinitionConfiguration configuration = new ProjectionDefinitionConfiguration(); configuration.addProjection(ParentProjection.class); - assertThat(configuration.hasProjectionFor(Child.class), is(true)); - assertThat(configuration.getProjectionsFor(Child.class).values(), hasItem(ParentProjection.class)); - assertThat(configuration.getProjectionType(Child.class, "summary"), is(typeCompatibleWith(ParentProjection.class))); + assertThat(configuration.hasProjectionFor(Child.class)).isTrue(); + assertThat(configuration.getProjectionsFor(Child.class).values()).contains(ParentProjection.class); + assertThat(configuration.getProjectionType(Child.class, "summary")).isAssignableFrom(ParentProjection.class); } @Test // DATAREST-221 public void defaultsParamternameToProjection() { - assertThat(new ProjectionDefinitionConfiguration().getParameterName(), is("projection")); + assertThat(new ProjectionDefinitionConfiguration().getParameterName()).isEqualTo("projection"); } @Test // DATAREST-747 @@ -134,8 +132,8 @@ public class ProjectionDefinitionConfigurationUnitTests { Map> projections = configuration.getProjectionsFor(Child.class); - assertThat(projections.values(), hasSize(1)); - assertThat(projections.values(), hasItem(ChildProjection.class)); + assertThat(projections.values()).hasSize(1); + assertThat(projections.values()).contains(ChildProjection.class); } @Projection(name = "name", types = Integer.class) diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java old mode 100644 new mode 100755 index f68f29be6..0dbdbe224 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/config/ResourceMappingUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.config; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.support.ResourceMappingUtils.*; import java.lang.reflect.Method; @@ -43,16 +42,17 @@ public class ResourceMappingUnitTests { @Test public void shouldDetectPathAndRemoveLeadingSlashIfAny() { + org.springframework.data.rest.core.config.ResourceMapping mapping = new org.springframework.data.rest.core.config.ResourceMapping( findRel(AnnotatedWithLeadingSlashPersonRepository.class), findPath(AnnotatedWithLeadingSlashPersonRepository.class), findExported(AnnotatedWithLeadingSlashPersonRepository.class)); // The rel attribute defaults to class name - assertThat(mapping.getRel(), is("annotatedWithLeadingSlashPerson")); - assertThat(mapping.getPath(), is("people")); + assertThat(mapping.getRel()).isEqualTo("annotatedWithLeadingSlashPerson"); + assertThat(mapping.getPath()).isEqualTo("people"); // The exported defaults to true - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.isExported()).isTrue(); } @Test @@ -63,10 +63,10 @@ public class ResourceMappingUnitTests { findRel(method), findPath(method), findExported(method)); // The rel attribute defaults to class name - assertThat(mapping.getRel(), is("findByFirstName")); - assertThat(mapping.getPath(), is("firstname")); + assertThat(mapping.getRel()).isEqualTo("findByFirstName"); + assertThat(mapping.getPath()).isEqualTo("firstname"); // The exported defaults to true - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.isExported()).isTrue(); } @Test @@ -77,11 +77,11 @@ public class ResourceMappingUnitTests { findRel(method), findPath(method), findExported(method)); // The rel defaults to method name - assertThat(mapping.getRel(), is("findByLastName")); + assertThat(mapping.getRel()).isEqualTo("findByLastName"); // The path contains only a leading slash therefore defaults to method name - assertThat(mapping.getPath(), is("findByLastName")); + assertThat(mapping.getPath()).isEqualTo("findByLastName"); // The exported defaults to true - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.isExported()).isTrue(); } @RestResource(path = "/people") diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/RepositoryEventIntegrationTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/RepositoryEventIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java old mode 100644 new mode 100755 index 960f4ad76..e403cb3bc --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/context/ValidatorIntegrationTests.java @@ -60,7 +60,7 @@ public class ValidatorIntegrationTests { } @Autowired ConfigurableApplicationContext context; - @Autowired KeyValueMappingContext mappingContext; + @Autowired KeyValueMappingContext mappingContext; @Test(expected = RepositoryConstraintViolationException.class) public void shouldValidateLastName() throws Exception { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/domain/OrderRepository.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/domain/OrderRepository.java index c2c6856e6..b2080f83b 100644 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/domain/OrderRepository.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/domain/OrderRepository.java @@ -15,6 +15,7 @@ */ package org.springframework.data.rest.core.domain; +import java.util.Optional; import java.util.UUID; import org.springframework.data.repository.CrudRepository; @@ -29,12 +30,12 @@ public interface OrderRepository extends CrudRepository { * @see org.springframework.data.repository.CrudRepository#save(java.lang.Object) */ @Override - public S save(S entity); + S save(S entity); /* * (non-Javadoc) * @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable) */ @Override - public Order findOne(UUID id); + Optional findOne(UUID id); } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java old mode 100644 new mode 100755 index bb671347d..af76d67d7 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/event/AnnotatedEventHandlerInvokerUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.event; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; @@ -51,7 +50,7 @@ public class AnnotatedEventHandlerInvokerUnitTests { MultiValueMap, EventHandlerMethod> methods = (MultiValueMap, EventHandlerMethod>) ReflectionTestUtils .getField(invoker, "handlerMethods"); - assertThat(methods.get(BeforeCreateEvent.class), hasSize(1)); + assertThat(methods.get(BeforeCreateEvent.class)).hasSize(1); } @Test // DATAREST-606 @@ -64,7 +63,7 @@ public class AnnotatedEventHandlerInvokerUnitTests { invoker.onApplicationEvent(new BeforeCreateEvent(new Person("Dave", "Matthews"))); - assertThat(sampleHandler.wasCalled, is(true)); + assertThat(sampleHandler.wasCalled).isTrue(); } @Test // DATAREST-970 @@ -79,10 +78,10 @@ public class AnnotatedEventHandlerInvokerUnitTests { invoker.onApplicationEvent(new BeforeCreateEvent(new Person("Dave", "Matthews"))); - assertThat(orderHandler1.wasCalled, is(true)); - assertThat(orderHandler2.wasCalled, is(true)); + assertThat(orderHandler1.wasCalled).isTrue(); + assertThat(orderHandler2.wasCalled).isTrue(); - assertThat(orderHandler1.timestamp, is(greaterThan(orderHandler2.timestamp))); + assertThat(orderHandler1.timestamp).isGreaterThan(orderHandler2.timestamp); } @Test // DATAREST-983 @@ -98,8 +97,8 @@ public class AnnotatedEventHandlerInvokerUnitTests { invoker.onApplicationEvent(new BeforeCreateEvent(new FirstEntity())); invoker.onApplicationEvent(new BeforeCreateEvent(new SecondEntity())); - assertThat(firstHandler.callCount, is(1)); - assertThat(secondHandler.callCount, is(1)); + assertThat(firstHandler.callCount).isEqualTo(1); + assertThat(secondHandler.callCount).isEqualTo(1); } @RepositoryEventHandler diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java old mode 100644 new mode 100755 index ea022b671..d3d957c61 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/CrudMethodsSupportedHttpMethodsUnitTests.java @@ -15,17 +15,17 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.mapping.ResourceType.*; import static org.springframework.http.HttpMethod.*; import java.util.List; +import java.util.Optional; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.ReadOnlyProperty; import org.springframework.data.annotation.Reference; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; @@ -88,22 +88,24 @@ public class CrudMethodsSupportedHttpMethodsUnitTests { @Test // DATAREST-523 public void exposesMethodsForProperties() { - KeyValueMappingContext context = new KeyValueMappingContext(); - KeyValuePersistentEntity entity = context.getPersistentEntity(Entity.class); + KeyValueMappingContext context = new KeyValueMappingContext<>(); + KeyValuePersistentEntity entity = context.getRequiredPersistentEntity(Entity.class); SupportedHttpMethods methods = getSupportedHttpMethodsFor(EntityRepository.class); - assertThat(methods.getMethodsFor(entity.getPersistentProperty("embedded")), is(empty())); - assertThat(methods.getMethodsFor(entity.getPersistentProperty("embeddedCollection")), is(empty())); + assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embedded"))).isEmpty(); + assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embeddedCollection"))).isEmpty(); - assertThat(methods.getMethodsFor(entity.getPersistentProperty("related")), - allOf(hasItems(GET, DELETE, PATCH, PUT), not(hasItem(POST)))); + assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("related")))// + .contains(GET, DELETE, PATCH, PUT)// + .doesNotContain(POST); - assertThat(methods.getMethodsFor(entity.getPersistentProperty("relatedCollection")), - hasItems(GET, DELETE, PATCH, PUT, POST)); + assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("relatedCollection")))// + .contains(GET, DELETE, PATCH, PUT, POST); - assertThat(methods.getMethodsFor(entity.getPersistentProperty("readOnlyReference")), - allOf(hasItem(GET), not(hasItems(DELETE, PATCH, PUT, POST)))); + assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("readOnlyReference")))// + .contains(GET)// + .doesNotContain(DELETE, PATCH, PUT, POST); } @Test // DATAREST-825 @@ -129,10 +131,10 @@ public class CrudMethodsSupportedHttpMethodsUnitTests { Set result = methods.getMethodsFor(type); - assertThat(result, supported ? hasItems(httpMethods) : not(hasItems(httpMethods))); - if (supported) { - assertThat(result, hasSize(httpMethods.length)); + assertThat(result).containsExactlyInAnyOrder(httpMethods); + } else { + assertThat(result).doesNotContain(httpMethods); } } @@ -150,7 +152,7 @@ public class CrudMethodsSupportedHttpMethodsUnitTests { @Override @RestResource(exported = false) - Object findOne(Long id); + Optional findOne(Long id); } interface NoFindOne extends Repository { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java old mode 100644 new mode 100755 index 31db7caed..7f7209039 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/MappingResourceMetadataUnitTests.java @@ -15,14 +15,13 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Reference; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; @@ -38,9 +37,9 @@ import org.springframework.data.rest.core.annotation.RestResource; @RunWith(MockitoJUnitRunner.class) public class MappingResourceMetadataUnitTests { - KeyValueMappingContext context = new KeyValueMappingContext(); + KeyValueMappingContext context = new KeyValueMappingContext<>(); - KeyValuePersistentEntity entity = context.getPersistentEntity(Entity.class); + KeyValuePersistentEntity entity = context.getRequiredPersistentEntity(Entity.class); ResourceMappings resourceMappings = new PersistentEntitiesResourceMappings( new PersistentEntities(Arrays.asList(context))); MappingResourceMetadata metadata = new MappingResourceMetadata(entity, resourceMappings); @@ -48,27 +47,27 @@ public class MappingResourceMetadataUnitTests { @Test // DATAREST-514 public void allowsLookupOfPropertyByMappedName() { - KeyValuePersistentProperty property = entity.getPersistentProperty("related"); + KeyValuePersistentProperty property = entity.getRequiredPersistentProperty("related"); PropertyAwareResourceMapping propertyMapping = metadata.getProperty("foo"); - assertThat(propertyMapping, is(notNullValue())); - assertThat(propertyMapping.getProperty(), is((Object) property)); - assertThat(metadata.getMappingFor(property).getPath().matches("foo"), is(true)); + assertThat(propertyMapping).isNotNull(); + assertThat(propertyMapping.getProperty()).isEqualTo((Object) property); + assertThat(metadata.getMappingFor(property).getPath().matches("foo")).isTrue(); } @Test // DATAREST-518 public void isNotExportedByDefault() { - assertThat(metadata.isExported(), is(false)); + assertThat(metadata.isExported()).isFalse(); } @Test // DATAREST-518 public void isExportedIfExplicitlyAnnotated() { - MappingResourceMetadata metadata = new MappingResourceMetadata(context.getPersistentEntity(Related.class), + MappingResourceMetadata metadata = new MappingResourceMetadata(context.getRequiredPersistentEntity(Related.class), resourceMappings); - assertThat(metadata.isExported(), is(true)); + assertThat(metadata.isExported()).isTrue(); } static class Entity { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java old mode 100644 new mode 100755 index 98b98b1d7..dd1e31f30 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/PersistentPropertyResourceMappingUnitTests.java @@ -15,15 +15,14 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Reference; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; @@ -41,17 +40,17 @@ import org.springframework.data.rest.core.annotation.RestResource; @RunWith(MockitoJUnitRunner.class) public class PersistentPropertyResourceMappingUnitTests { - KeyValueMappingContext mappingContext = new KeyValueMappingContext(); + KeyValueMappingContext mappingContext = new KeyValueMappingContext<>(); @Test // DATAREST-175 public void usesPropertyNameAsDefaultResourceMappingRelAndPath() { ResourceMapping mapping = getPropertyMappingFor(Entity.class, "first"); - assertThat(mapping, is(notNullValue())); - assertThat(mapping.getPath(), is(new Path("first"))); - assertThat(mapping.getRel(), is("first")); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping).isNotNull(); + assertThat(mapping.getPath()).isEqualTo(new Path("first")); + assertThat(mapping.getRel()).isEqualTo("first"); + assertThat(mapping.isExported()).isFalse(); } @Test // DATAREST-175 @@ -59,10 +58,10 @@ public class PersistentPropertyResourceMappingUnitTests { ResourceMapping mapping = getPropertyMappingFor(Entity.class, "second"); - assertThat(mapping, is(notNullValue())); - assertThat(mapping.getPath(), is(new Path("secPath"))); - assertThat(mapping.getRel(), is("secRel")); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping).isNotNull(); + assertThat(mapping.getPath()).isEqualTo(new Path("secPath")); + assertThat(mapping.getRel()).isEqualTo("secRel"); + assertThat(mapping.isExported()).isFalse(); } @Test // DATAREST-175 @@ -70,10 +69,10 @@ public class PersistentPropertyResourceMappingUnitTests { ResourceMapping mapping = getPropertyMappingFor(Entity.class, "third"); - assertThat(mapping, is(notNullValue())); - assertThat(mapping.getPath(), is(new Path("thirdPath"))); - assertThat(mapping.getRel(), is("thirdRel")); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping).isNotNull(); + assertThat(mapping.getPath()).isEqualTo(new Path("thirdPath")); + assertThat(mapping.getRel()).isEqualTo("thirdRel"); + assertThat(mapping.isExported()).isFalse(); } @Test // DATAREST-233 @@ -83,8 +82,8 @@ public class PersistentPropertyResourceMappingUnitTests { ResourceDescription description = mapping.getDescription(); - assertThat(description.isDefault(), is(true)); - assertThat(description.getMessage(), is("rest.description.entity.second")); + assertThat(description.isDefault()).isTrue(); + assertThat(description.getMessage()).isEqualTo("rest.description.entity.second"); } @Test // DATAREST-233 @@ -93,14 +92,14 @@ public class PersistentPropertyResourceMappingUnitTests { ResourceMapping mapping = getPropertyMappingFor(Entity.class, "fourth"); ResourceDescription description = mapping.getDescription(); - assertThat(description.isDefault(), is(false)); - assertThat(description.getMessage(), is("Some description")); + assertThat(description.isDefault()).isFalse(); + assertThat(description.getMessage()).isEqualTo("Some description"); } private ResourceMapping getPropertyMappingFor(Class entity, String propertyName) { - KeyValuePersistentEntity persistentEntity = mappingContext.getPersistentEntity(entity); - KeyValuePersistentProperty property = persistentEntity.getPersistentProperty(propertyName); + KeyValuePersistentEntity persistentEntity = mappingContext.getRequiredPersistentEntity(entity); + KeyValuePersistentProperty property = persistentEntity.getRequiredPersistentProperty(propertyName); ResourceMappings resourceMappings = new PersistentEntitiesResourceMappings( new PersistentEntities(Arrays.asList(mappingContext))); diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java old mode 100644 new mode 100755 index 3068b67ba..b099e24fa --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryCollectionResourceMappingUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.data.domain.Page; @@ -41,10 +40,10 @@ public class RepositoryCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = getResourceMappingFor(PersonRepository.class); - assertThat(mapping.getPath(), is(new Path("persons"))); - assertThat(mapping.getRel(), is("persons")); - assertThat(mapping.getItemResourceRel(), is("person")); - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.getPath()).isEqualTo(new Path("persons")); + assertThat(mapping.getRel()).isEqualTo("persons"); + assertThat(mapping.getItemResourceRel()).isEqualTo("person"); + assertThat(mapping.isExported()).isTrue(); } @Test @@ -52,10 +51,10 @@ public class RepositoryCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = getResourceMappingFor(AnnotatedPersonRepository.class); - assertThat(mapping.getPath(), is(new Path("bar"))); - assertThat(mapping.getRel(), is("foo")); - assertThat(mapping.getItemResourceRel(), is("annotatedPerson")); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping.getPath()).isEqualTo(new Path("bar")); + assertThat(mapping.getRel()).isEqualTo("foo"); + assertThat(mapping.getItemResourceRel()).isEqualTo("annotatedPerson"); + assertThat(mapping.isExported()).isFalse(); } @Test @@ -63,30 +62,30 @@ public class RepositoryCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = getResourceMappingFor(AnnotatedAnnotatedPersonRepository.class); - assertThat(mapping.getPath(), is(new Path("/trumpsAll"))); - assertThat(mapping.getRel(), is("foo")); - assertThat(mapping.getItemResourceRel(), is("annotatedPerson")); - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.getPath()).isEqualTo(new Path("/trumpsAll")); + assertThat(mapping.getRel()).isEqualTo("foo"); + assertThat(mapping.getItemResourceRel()).isEqualTo("annotatedPerson"); + assertThat(mapping.isExported()).isTrue(); } @Test public void doesNotExposeRepositoryForPublicDomainTypeIfRepoIsPackageProtected() { ResourceMapping mapping = getResourceMappingFor(PackageProtectedRepository.class); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping.isExported()).isFalse(); } @Test // DATAREST-229 public void detectsPagingRepository() { - assertThat(getResourceMappingFor(PersonRepository.class).isPagingResource(), is(true)); + assertThat(getResourceMappingFor(PersonRepository.class).isPagingResource()).isTrue(); } @Test public void discoversCustomizationsUsingRestRepositoryResource() { CollectionResourceMapping mapping = getResourceMappingFor(RepositoryAnnotatedRepository.class); - assertThat(mapping.getRel(), is("foo")); - assertThat(mapping.getItemResourceRel(), is("bar")); + assertThat(mapping.getRel()).isEqualTo("foo"); + assertThat(mapping.getItemResourceRel()).isEqualTo("bar"); } @Test // DATAREST-445 @@ -103,7 +102,7 @@ public class RepositoryCollectionResourceMappingUnitTests { RepositoryCollectionResourceMapping mapping = new RepositoryCollectionResourceMapping(metadata, RepositoryDetectionStrategies.DEFAULT); - assertThat(mapping.getPath(), is(new Path("/objects"))); + assertThat(mapping.getPath()).isEqualTo(new Path("/objects")); } private static CollectionResourceMapping getResourceMappingFor(Class repositoryInterface) { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java old mode 100644 new mode 100755 index 14e2fe1d1..1c41ec313 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryDetectionStrategiesUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies.*; import java.util.HashMap; @@ -93,7 +92,7 @@ public class RepositoryDetectionStrategiesUnitTests { private static void assertExposures(RepositoryDetectionStrategy strategy, Map, Boolean> expected) { for (Entry, Boolean> entry : expected.entrySet()) { - assertThat(strategy.isExported(new DefaultRepositoryMetadata(entry.getKey())), is(entry.getValue())); + assertThat(strategy.isExported(new DefaultRepositoryMetadata(entry.getKey()))).isEqualTo(entry.getValue()); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java old mode 100644 new mode 100755 index e6a6105b5..08c4eedc1 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryMethodResourceMappingUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.lang.reflect.Method; @@ -49,7 +48,7 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByLastname", String.class); ResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getPath(), is(new Path("findByLastname"))); + assertThat(mapping.getPath()).isEqualTo(new Path("findByLastname")); } @Test @@ -58,16 +57,16 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByFirstname", String.class); ResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getPath(), is(new Path("bar"))); + assertThat(mapping.getPath()).isEqualTo(new Path("bar")); } @Test // DATAREST-31 - public void doesNotDiscoverAnyParametersIfNotAnnotated() throws Exception { + public void discoversParametersIfCompiledWithCorrespondingFlag() throws Exception { Method method = PersonRepository.class.getMethod("findByLastname", String.class); MethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getParametersMetadata().getParameterNames(), is(emptyIterable())); + assertThat(mapping.getParametersMetadata().getParameterNames()).contains("lastname"); } @Test // DATAREST-31 @@ -76,8 +75,8 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByFirstname", String.class); MethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getParametersMetadata().getParameterNames(), hasSize(1)); - assertThat(mapping.getParametersMetadata().getParameterNames(), hasItem("firstname")); + assertThat(mapping.getParametersMetadata().getParameterNames()).hasSize(1); + assertThat(mapping.getParametersMetadata().getParameterNames()).contains("firstname"); } @Test // DATAREST-229 @@ -86,7 +85,7 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class); MethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.isPagingResource(), is(true)); + assertThat(mapping.isPagingResource()).isTrue(); } @Test @@ -95,7 +94,7 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class); MethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getRel(), is("findByEmailAddress")); + assertThat(mapping.getRel()).isEqualTo("findByEmailAddress"); } @Test // DATAREST-384 @@ -104,12 +103,12 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Sort.class); RepositoryMethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.isSortableResource(), is(true)); + assertThat(mapping.isSortableResource()).isTrue(); method = PersonRepository.class.getMethod("findByEmailAddress", String.class, Pageable.class); mapping = getMappingFor(method); - assertThat(mapping.isSortableResource(), is(false)); + assertThat(mapping.isSortableResource()).isFalse(); } @Test // DATAREST-467 @@ -119,7 +118,7 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByLastname", String.class); MethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getReturnedDomainType(), is(equalTo((Class) Person.class))); + assertThat(mapping.getReturnedDomainType()).isEqualTo((Class) Person.class); } @Test // DATAREST-699 @@ -128,7 +127,7 @@ public class RepositoryMethodResourceMappingUnitTests { Method method = PersonRepository.class.getMethod("findByLastname", String.class, Pageable.class); RepositoryMethodResourceMapping mapping = getMappingFor(method); - assertThat(mapping.getParametersMetadata().getParameterNames(), not(hasItem("pageable"))); + assertThat(mapping.getParametersMetadata().getParameterNames()).doesNotContain("pageable"); } private RepositoryMethodResourceMapping getMappingFor(Method method) { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java old mode 100644 new mode 100755 index dfce4e52c..5935ce7e2 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java @@ -15,14 +15,12 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,6 +36,7 @@ import org.springframework.data.rest.core.domain.Author; import org.springframework.data.rest.core.domain.CreditCard; import org.springframework.data.rest.core.domain.JpaRepositoryConfig; import org.springframework.data.rest.core.domain.Person; +import org.springframework.data.rest.core.domain.Profile; import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy.RepositoryDetectionStrategies; import org.springframework.hateoas.core.EvoInflectorRelProvider; import org.springframework.test.context.ContextConfiguration; @@ -54,13 +53,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class RepositoryResourceMappingsIntegrationTests { @Autowired ListableBeanFactory factory; - @Autowired KeyValueMappingContext mappingContext; + @Autowired KeyValueMappingContext mappingContext; ResourceMappings mappings; @Before public void setUp() { + mappingContext.getPersistentEntity(Profile.class); + Repositories repositories = new Repositories(factory); this.mappings = new RepositoryResourceMappings(repositories, new PersistentEntities(Arrays.asList(mappingContext)), new EvoInflectorRelProvider(), RepositoryDetectionStrategies.DEFAULT); @@ -68,7 +69,7 @@ public class RepositoryResourceMappingsIntegrationTests { @Test public void detectsAllMappings() { - assertThat(mappings, is(Matchers. iterableWithSize(5))); + assertThat(mappings).hasSize(5); } @Test @@ -76,8 +77,8 @@ public class RepositoryResourceMappingsIntegrationTests { ResourceMetadata personMappings = mappings.getMetadataFor(Person.class); - assertThat(personMappings.isExported(), is(true)); - assertThat(personMappings.getSearchResourceMappings().isExported(), is(true)); + assertThat(personMappings.isExported()).isTrue(); + assertThat(personMappings.getSearchResourceMappings().isExported()).isTrue(); } @Test @@ -85,8 +86,8 @@ public class RepositoryResourceMappingsIntegrationTests { ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class); - assertThat(creditCardMapping.isExported(), is(false)); - assertThat(creditCardMapping.getSearchResourceMappings().isExported(), is(false)); + assertThat(creditCardMapping.isExported()).isFalse(); + assertThat(creditCardMapping.getSearchResourceMappings().isExported()).isFalse(); } @Test // DATAREST-112 @@ -94,27 +95,27 @@ public class RepositoryResourceMappingsIntegrationTests { Repositories repositories = new Repositories(factory); PersistentEntity entity = repositories.getPersistentEntity(Person.class); - PersistentProperty property = entity.getPersistentProperty("siblings"); + PersistentProperty property = entity.getRequiredPersistentProperty("siblings"); ResourceMetadata metadata = mappings.getMetadataFor(Person.class); ResourceMapping mapping = metadata.getMappingFor(property); - assertThat(mapping.getRel(), is("siblings")); - assertThat(mapping.getPath(), is(new Path("siblings"))); - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.getRel()).isEqualTo("siblings"); + assertThat(mapping.getPath()).isEqualTo(new Path("siblings")); + assertThat(mapping.isExported()).isTrue(); } @Test // DATAREST-111 public void exposesResourceByPath() { - assertThat(mappings.exportsTopLevelResourceFor("people"), is(true)); - assertThat(mappings.exportsTopLevelResourceFor("orders"), is(true)); + assertThat(mappings.exportsTopLevelResourceFor("people")).isTrue(); + assertThat(mappings.exportsTopLevelResourceFor("orders")).isTrue(); ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class); - assertThat(creditCardMapping, is(notNullValue())); - assertThat(creditCardMapping.getPath(), is(new Path("creditCards"))); - assertThat(creditCardMapping.isExported(), is(false)); - assertThat(mappings.exportsTopLevelResourceFor("creditCards"), is(false)); + assertThat(creditCardMapping).isNotNull(); + assertThat(creditCardMapping.getPath()).isEqualTo(new Path("creditCards")); + assertThat(creditCardMapping.isExported()).isFalse(); + assertThat(mappings.exportsTopLevelResourceFor("creditCards")).isFalse(); } @Test // DATAREST-107 @@ -123,7 +124,7 @@ public class RepositoryResourceMappingsIntegrationTests { ResourceMetadata creditCardMetadata = mappings.getMetadataFor(CreditCard.class); SearchResourceMappings searchResourceMappings = creditCardMetadata.getSearchResourceMappings(); - assertThat(searchResourceMappings, is(Matchers. iterableWithSize(0))); + assertThat(searchResourceMappings).isEmpty(); ResourceMetadata personMetadata = mappings.getMetadataFor(Person.class); List methodNames = new ArrayList(); @@ -132,25 +133,25 @@ public class RepositoryResourceMappingsIntegrationTests { methodNames.add(method.getMethod().getName()); } - assertThat(methodNames, hasSize(2)); - assertThat(methodNames, hasItems("findByFirstName", "findByCreatedGreaterThan")); + assertThat(methodNames).hasSize(2); + assertThat(methodNames).contains("findByFirstName", "findByCreatedGreaterThan"); } @Test // DATAREST-325 public void exposesMethodResourceMappingInPackageProtectedButExportedRepo() { ResourceMetadata metadata = mappings.getMetadataFor(Author.class); - assertThat(metadata.isExported(), is(true)); + assertThat(metadata.isExported()).isTrue(); SearchResourceMappings searchMappings = metadata.getSearchResourceMappings(); - assertThat(searchMappings.isExported(), is(true)); - assertThat(searchMappings.getMappedMethod("findByFirstnameContaining"), is(notNullValue())); + assertThat(searchMappings.isExported()).isTrue(); + assertThat(searchMappings.getMappedMethod("findByFirstnameContaining")).isNotNull(); for (MethodResourceMapping methodMapping : searchMappings) { System.out.println(methodMapping.getMethod().getName()); - assertThat(methodMapping.isExported(), is(true)); + assertThat(methodMapping.isExported()).isTrue(); } } @@ -161,7 +162,7 @@ public class RepositoryResourceMappingsIntegrationTests { PropertyAwareResourceMapping propertyMapping = metadata.getProperty("father-mapped"); - assertThat(propertyMapping.getRel(), is("father")); - assertThat(propertyMapping.getPath(), is(new Path("father-mapped"))); + assertThat(propertyMapping.getRel()).isEqualTo("father"); + assertThat(propertyMapping.getPath()).isEqualTo(new Path("father-mapped")); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java old mode 100644 new mode 100755 index 79ce90fa5..12d37d9d9 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/TypeBasedCollectionResourceMappingUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.mapping; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.data.rest.core.Path; @@ -34,10 +33,10 @@ public class TypeBasedCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(Sample.class); - assertThat(mapping.getPath(), is(new Path("sample"))); - assertThat(mapping.getRel(), is("samples")); - assertThat(mapping.getItemResourceRel(), is("sample")); - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.getPath()).isEqualTo(new Path("sample")); + assertThat(mapping.getRel()).isEqualTo("samples"); + assertThat(mapping.getItemResourceRel()).isEqualTo("sample"); + assertThat(mapping.isExported()).isTrue(); } @Test @@ -45,10 +44,10 @@ public class TypeBasedCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(CustomizedSample.class); - assertThat(mapping.getPath(), is(new Path("customizedSample"))); - assertThat(mapping.getRel(), is("myRel")); - assertThat(mapping.getItemResourceRel(), is("customizedSample")); - assertThat(mapping.isExported(), is(true)); + assertThat(mapping.getPath()).isEqualTo(new Path("customizedSample")); + assertThat(mapping.getRel()).isEqualTo("myRel"); + assertThat(mapping.getItemResourceRel()).isEqualTo("customizedSample"); + assertThat(mapping.isExported()).isTrue(); } @Test // DATAREST-99 @@ -56,7 +55,7 @@ public class TypeBasedCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(HiddenSample.class); - assertThat(mapping.isExported(), is(false)); + assertThat(mapping.isExported()).isFalse(); } /** @@ -68,13 +67,13 @@ public class TypeBasedCollectionResourceMappingUnitTests { CollectionResourceMapping mapping = new TypeBasedCollectionResourceMapping(Sample.class); ResourceDescription description = mapping.getDescription(); - assertThat(description.isDefault(), is(true)); - assertThat(description.getMessage(), is("rest.description.samples")); + assertThat(description.isDefault()).isTrue(); + assertThat(description.getMessage()).isEqualTo("rest.description.samples"); ResourceDescription itemDescription = mapping.getItemResourceDescription(); - assertThat(itemDescription.isDefault(), is(true)); - assertThat(itemDescription.getMessage(), is("rest.description.sample")); + assertThat(itemDescription.isDefault()).isTrue(); + assertThat(itemDescription.getMessage()).isEqualTo("rest.description.sample"); } public interface Sample {} diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java old mode 100644 new mode 100755 index d4a51c125..7cf009323 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DefaultSelfLinkProviderUnitTests.java @@ -16,7 +16,7 @@ package org.springframework.data.rest.core.support; import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.Serializable; @@ -31,9 +31,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.rest.core.domain.Profile; @@ -60,19 +58,15 @@ public class DefaultSelfLinkProviderUnitTests { @Before public void setUp() { - when(entityLinks.linkToSingleResource((Class) any(), any())).then(new Answer() { + when(entityLinks.linkToSingleResource((Class) any(), any())).then(invocation -> { - @Override - public Link answer(InvocationOnMock invocation) throws Throwable { + Class type = invocation.getArgument(0); + Serializable id = invocation.getArgument(1); - Class type = invocation.getArgumentAt(0, Class.class); - Serializable id = invocation.getArgumentAt(1, Serializable.class); - - return new Link("/".concat(type.getName()).concat("/").concat(id.toString())); - } + return new Link("/".concat(type.getName()).concat("/").concat(id.toString())); }); - KeyValueMappingContext context = new KeyValueMappingContext(); + KeyValueMappingContext context = new KeyValueMappingContext<>(); context.getPersistentEntity(Profile.class); context.afterPropertiesSet(); @@ -125,7 +119,7 @@ public class DefaultSelfLinkProviderUnitTests { exception.expect(IllegalArgumentException.class); exception.expectMessage(Object.class.getName()); - exception.expectMessage("No persistent entity found!"); + exception.expectMessage("Couldn't find PersistentEntity for"); provider.createSelfLinkFor(new Object()); } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java old mode 100644 new mode 100755 index 9844e6374..d2e237dca --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.support; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.support.DomainObjectMerger.NullHandlingPolicy.*; import java.util.Arrays; @@ -60,8 +59,8 @@ public class DomainObjectMergerTests { merger.merge(incoming, existingDomainObject, APPLY_NULLS); - assertThat(existingDomainObject.getFirstName(), is(incoming.getFirstName())); - assertThat(existingDomainObject.getLastName(), is(incoming.getLastName())); + assertThat(existingDomainObject.getFirstName()).isEqualTo(incoming.getFirstName()); + assertThat(existingDomainObject.getLastName()).isEqualTo(incoming.getLastName()); } @Test // DATAREST-130 @@ -72,8 +71,8 @@ public class DomainObjectMergerTests { merger.merge(incoming, existingDomainObject, APPLY_NULLS); - assertThat(existingDomainObject.getFirstName(), is(incoming.getFirstName())); - assertThat(existingDomainObject.getLastName(), is(incoming.getLastName())); + assertThat(existingDomainObject.getFirstName()).isEqualTo(incoming.getFirstName()); + assertThat(existingDomainObject.getLastName()).isEqualTo(incoming.getLastName()); } @Test // DATAREST-327 @@ -86,6 +85,6 @@ public class DomainObjectMergerTests { merger.merge(new Person("Sam", null), frodo, IGNORE_NULLS); - assertThat(frodo.getSiblings(), is(not(emptyIterable()))); + assertThat(frodo.getSiblings()).isNotEmpty(); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java old mode 100644 new mode 100755 index a0285d43d..e83f613b5 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/DomainObjectMergerUnitTests.java @@ -15,12 +15,12 @@ */ package org.springframework.data.rest.core.support; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.support.DomainObjectMerger.*; import java.util.Collections; import java.util.Iterator; +import java.util.Optional; import org.junit.Test; @@ -34,16 +34,16 @@ public class DomainObjectMergerUnitTests { @Test // DATAREST-327 public void considersEmptyObjectsEmpty() { - assertThat(isNullOrEmpty(null), is(true)); - assertThat(isNullOrEmpty(Collections.emptyList()), is(true)); - assertThat(isNullOrEmpty(new Object[0]), is(true)); - assertThat(isNullOrEmpty(new String[0]), is(true)); - assertThat(isNullOrEmpty(new MyIterable()), is(true)); + assertThat(isNullOrEmpty(Optional.empty())).isTrue(); + assertThat(isNullOrEmpty(Optional.of(Collections.emptyList()))).isTrue(); + assertThat(isNullOrEmpty(Optional.of(new Object[0]))).isTrue(); + assertThat(isNullOrEmpty(Optional.of(new String[0]))).isTrue(); + assertThat(isNullOrEmpty(Optional.of(new MyIterable()))).isTrue(); - assertThat(isNullOrEmpty(new Object()), is(false)); - assertThat(isNullOrEmpty(Collections.singleton(new Object())), is(false)); - assertThat(isNullOrEmpty(new Object[] { "1" }), is(false)); - assertThat(isNullOrEmpty(new String[] { "1" }), is(false)); + assertThat(isNullOrEmpty(Optional.of(new Object()))).isFalse(); + assertThat(isNullOrEmpty(Optional.of(Collections.singleton(new Object())))).isFalse(); + assertThat(isNullOrEmpty(Optional.of(new Object[] { "1" }))).isFalse(); + assertThat(isNullOrEmpty(Optional.of(new String[] { "1" }))).isFalse(); } class MyIterable implements Iterable { diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java old mode 100644 new mode 100755 index 8cebacd63..056a3c740 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/ResourceStringUtilsTests.java @@ -15,17 +15,15 @@ */ package org.springframework.data.rest.core.support; +import static org.assertj.core.api.Assertions.*; + import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.springframework.data.rest.core.support.ResourceStringUtils; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.runners.Parameterized.Parameters; +import org.junit.runners.Parameterized.Parameters; /** * Ensures proper detection and removal of leading slash in strings. @@ -48,23 +46,25 @@ public class ResourceStringUtilsTests { @Parameters(name = "{0}") public static Collection parameters() { - return Arrays.asList(new Object[][] { - { "empty string has no text and should remain empty", "", "", false }, - { "blank string has no text and should remain as is", " ", " ", false }, - { "string made of only a leading slash has no text and should be returned empty", "/", "", false }, - { "blank string with only slashes has no text and should be returned as is", " / ", " / ", false }, - { "normal string has text and should be returned as such", "hello", "hello", true }, - { "normal string with leading slash has text and should be returned without leading slash", "/hello", "hello", - true }, }); + return Arrays + .asList( + new Object[][] { { "empty string has no text and should remain empty", "", "", false }, + { "blank string has no text and should remain as is", " ", " ", false }, + { "string made of only a leading slash has no text and should be returned empty", "/", "", false }, + { "blank string with only slashes has no text and should be returned as is", " / ", " / ", + false }, + { "normal string has text and should be returned as such", "hello", "hello", true }, + { "normal string with leading slash has text and should be returned without leading slash", "/hello", + "hello", true }, }); } @Test public void shouldDetectTextPresence() { - assertThat(ResourceStringUtils.hasTextExceptSlash(actual), is(hasText)); + assertThat(ResourceStringUtils.hasTextExceptSlash(actual)).isEqualTo(hasText); } @Test public void shouldRemoveLeadingSlashIfAny() { - assertThat(ResourceStringUtils.removeLeadingSlash(actual), is(expected)); + assertThat(ResourceStringUtils.removeLeadingSlash(actual)).isEqualTo(expected); } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java old mode 100644 new mode 100755 index 43b803d1e..ab8c1226e --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/support/UnwrappingRepositoryInvokerFactoryUnitTests.java @@ -15,9 +15,7 @@ */ package org.springframework.data.rest.core.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.lang.reflect.Method; @@ -25,8 +23,9 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Optional; +import java.util.function.Consumer; -import org.hamcrest.Matcher; +import org.assertj.core.api.AbstractOptionalAssert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,7 +35,6 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.data.repository.support.RepositoryInvoker; import org.springframework.data.repository.support.RepositoryInvokerFactory; import org.springframework.data.rest.core.domain.Profile; -import org.springframework.util.LinkedMultiValueMap; /** * Unit tests for {@link UnwrappingRepositoryInvokerFactory}. @@ -54,8 +52,8 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests { RepositoryInvokerFactory factory; Method method; - public @Parameter(value = 0) Object source; - public @Parameter(value = 1) Matcher value; + public @Parameter(0) Object source; + public @Parameter(1) Consumer> value; @Before public void setUp() throws Exception { @@ -68,31 +66,23 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests { @Parameters public static Collection data() { + return Arrays.asList(new Object[][] { // - { Optional.empty(), is(nullValue()) }, // - { Optional.of(REFERENCE), is(REFERENCE) }, // - { com.google.common.base.Optional.absent(), is(nullValue()) }, // - { com.google.common.base.Optional.of(REFERENCE), is(REFERENCE) } // + { null, $(it -> it.isEmpty()) }, // + { Optional.empty(), $(it -> it.isEmpty()) }, // + { Optional.of(REFERENCE), $(it -> it.hasValue(REFERENCE)) }, // + { com.google.common.base.Optional.absent(), $(it -> it.isEmpty()) }, // + { com.google.common.base.Optional.of(REFERENCE), $(it -> it.hasValue(REFERENCE)) } // }); } - @Test // DATAREST-511 - public void unwrapsValuesForFindOne() { - assertFindOneValueForSource(source, value); - } - - @Test // DATAREST-511 - public void unwrapsValuesForQuery() { - assertQueryValueForSource(source, value); - } - @Test // DATAREST-724 @SuppressWarnings("unchecked") public void usesRegisteredEntityLookup() { EntityLookup lookup = mock(EntityLookup.class); - when(lookup.supports(Profile.class)).thenReturn(true); + when(lookup.supports(Profile.class)).thenReturn(true); when(delegate.getInvokerFor(Profile.class)).thenReturn(invoker); factory = new UnwrappingRepositoryInvokerFactory(delegate, Arrays.asList(lookup)); @@ -101,16 +91,7 @@ public class UnwrappingRepositoryInvokerFactoryUnitTests { verify(lookup, times(1)).lookupEntity(eq(1L)); } - private void assertFindOneValueForSource(Object source, Matcher value) { - - when(invoker.invokeFindOne(1L)).thenReturn(source); - assertThat(factory.getInvokerFor(Object.class).invokeFindOne(1L), value); - } - - private void assertQueryValueForSource(Object source, Matcher value) { - - when(invoker.invokeQueryMethod(method, new LinkedMultiValueMap(), null, null)).thenReturn(source); - assertThat(factory.getInvokerFor(Object.class).invokeQueryMethod(method, new LinkedMultiValueMap(), - null, null), value); + private static Consumer> $(Consumer> consumer) { + return consumer; } } diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/FunctionTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/FunctionTests.java deleted file mode 100644 index ee80d0116..000000000 --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/FunctionTests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.rest.core.util; - -import org.junit.Test; - -/** - * @author Oliver Gierke - */ -public class FunctionTests { - - @Test - public void foo() { - - Foo foo = new Foo(); - - foo.apply(new Function() { - - @Override - public Integer apply(String input) { - return null; - } - }); - } - - static class Foo { - - public Integer apply(Function function) { - return null; - } - } -} diff --git a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java old mode 100644 new mode 100755 index b2df5b89e..c84028e0a --- a/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java +++ b/spring-data-rest-core/src/test/java/org/springframework/data/rest/core/util/MethodsUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.core.util; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.lang.reflect.Method; import java.util.HashSet; @@ -25,7 +24,6 @@ import java.util.Set; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; /** * Unit tests for {@link Methods}. @@ -41,18 +39,12 @@ public class MethodsUnitTests { factory.setTarget(new Sample()); factory.setProxyTargetClass(true); - final Set methods = new HashSet(); + Set methods = new HashSet(); - ReflectionUtils.doWithMethods(factory.getProxy().getClass(), new MethodCallback() { + ReflectionUtils.doWithMethods(factory.getProxy().getClass(), method -> methods.add(method), Methods.USER_METHODS); - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - methods.add(method); - } - }, Methods.USER_METHODS); - - assertThat(methods, hasSize(1)); - assertThat(methods, contains(Sample.class.getMethod("method"))); + assertThat(methods).hasSize(1); + assertThat(methods).contains(Sample.class.getMethod("method")); } static class Sample { diff --git a/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java b/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java old mode 100644 new mode 100755 index 8ac807093..446588d45 --- a/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java +++ b/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserIntegrationTests.java @@ -22,9 +22,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.ConversionService; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; @@ -58,6 +61,10 @@ public class HalBrowserIntegrationTests { @EnableWebMvc static class TestConfiguration extends RepositoryRestMvcConfiguration { + public TestConfiguration(ApplicationContext context, ObjectFactory conversionService) { + super(context, conversionService); + } + @Bean RepositoryRestConfigurerAdapter configExtension() { diff --git a/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java b/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java old mode 100644 new mode 100755 index 47093d272..796d6d9d3 --- a/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java +++ b/spring-data-rest-hal-browser/src/test/java/org/springframework/data/rest/webmvc/halbrowser/HalBrowserUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc.halbrowser; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import java.util.Collections; @@ -48,14 +49,14 @@ public class HalBrowserUnitTests { View view = new HalBrowser().browser(request); - assertThat(view, is(instanceOf(RedirectView.class))); + assertThat(view).isInstanceOf(RedirectView.class); ((AbstractView) view).render(Collections. emptyMap(), request, response); UriComponents components = UriComponentsBuilder.fromUriString(response.getHeader(HttpHeaders.LOCATION)).build(); assertThat(components.getPath(), startsWith("/context")); - assertThat(components.getFragment(), is("/context")); + assertThat(components.getFragment()).isEqualTo("/context"); } @Test @@ -69,7 +70,7 @@ public class HalBrowserUnitTests { View view = new HalBrowser().browser(request); - assertThat(view, is(instanceOf(RedirectView.class))); + assertThat(view).isInstanceOf(RedirectView.class); String url = ((RedirectView) view).getUrl(); diff --git a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractControllerIntegrationTests.java old mode 100644 new mode 100755 index b48179d6e..342ca02cc --- a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractControllerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractControllerIntegrationTests.java @@ -19,9 +19,12 @@ import java.util.Collections; import org.junit.Before; import org.junit.runner.RunWith; +import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.ConversionService; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.repository.support.Repositories; import org.springframework.data.repository.support.RepositoryInvokerFactory; @@ -58,6 +61,10 @@ public abstract class AbstractControllerIntegrationTests { @Configuration public static class TestConfiguration extends RepositoryRestMvcConfiguration { + public TestConfiguration(ApplicationContext context, ObjectFactory conversionService) { + super(context, conversionService); + } + @Bean public PersistentEntityResourceAssembler persistentEntityResourceAssembler() { diff --git a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java old mode 100644 new mode 100755 index 27ed9089d..c4aa7c430 --- a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/AbstractWebIntegrationTests.java @@ -1,6 +1,5 @@ -package org.springframework.data.rest.tests; /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +13,11 @@ package org.springframework.data.rest.tests; * See the License for the specific language governing permissions and * limitations under the License. */ +package org.springframework.data.rest.tests; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.fail; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -80,18 +81,18 @@ public abstract class AbstractWebIntegrationTests { } protected void setupMockMvc() { - this.mvc = MockMvcBuilders.webAppContextSetup(context).// - defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).build(); + this.mvc = MockMvcBuilders.webAppContextSetup(context)// + .defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).build(); } protected MockHttpServletResponse postAndGet(Link link, Object payload, MediaType mediaType) throws Exception { String href = link.isTemplated() ? link.expand().getHref() : link.getHref(); - MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType)).// - andExpect(status().isCreated()).// - andExpect(header().string("Location", is(notNullValue()))).// - andReturn().getResponse(); + MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType))// + .andExpect(status().isCreated())// + .andExpect(header().string("Location", is(notNullValue())))// + .andReturn().getResponse(); String content = response.getContentAsString(); @@ -106,9 +107,9 @@ public abstract class AbstractWebIntegrationTests { String href = link.isTemplated() ? link.expand().getHref() : link.getHref(); - MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType)).// - andExpect(status().is2xxSuccessful()).// - andReturn().getResponse(); + MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))// + .andExpect(status().is2xxSuccessful())// + .andReturn().getResponse(); return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link); } @@ -120,9 +121,8 @@ public abstract class AbstractWebIntegrationTests { MockHttpServletResponse response = mvc .perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).// content(payload.toString()).contentType(mediaType)) - .// - andExpect(status().is2xxSuccessful()).// - andReturn().getResponse(); + .andExpect(status().is2xxSuccessful())// + .andReturn().getResponse(); return StringUtils.hasText(response.getContentAsString()) ? response : client.request(href); } @@ -131,13 +131,13 @@ public abstract class AbstractWebIntegrationTests { String href = link.isTemplated() ? link.expand().getHref() : link.getHref(); - mvc.perform(delete(href)).// - andExpect(status().isNoContent()).// - andReturn().getResponse(); + mvc.perform(delete(href))// + .andExpect(status().isNoContent())// + .andReturn().getResponse(); // Check that the resource is unavailable after a DELETE - mvc.perform(get(href)).// - andExpect(status().isNotFound()); + mvc.perform(get(href))// + .andExpect(status().isNotFound()); } protected Link assertHasContentLinkWithRel(String rel, MockHttpServletResponse response) throws Exception { @@ -157,8 +157,13 @@ public abstract class AbstractWebIntegrationTests { String href = JsonPath. read(content, String.format(CONTENT_LINK_JSONPATH, rel)).get(0).toString(); - assertThat("Expected to find a link with rel" + rel + " in the content section of the response!", href, - is(expected ? notNullValue() : nullValue())); + String message = "Expected to%s find a link with rel %s in the content section of the response!"; + + if (expected) { + assertThat(href).as(message, "", rel).isNotNull(); + } else { + assertThat(href).as(message, " not", rel).isNull(); + } return new Link(href, rel); @@ -177,7 +182,7 @@ public abstract class AbstractWebIntegrationTests { String content = response.getContentAsString(); Link link = client.getDiscoverer(response).findLinkWithRel(rel, content); - assertThat("Expected not to find link with rel " + rel + " but found " + link + "!", link, is(nullValue())); + assertThat(link).as("Expected not to find link with rel %s but found %s!", rel, link).isNull(); } @SuppressWarnings("unchecked") @@ -186,12 +191,11 @@ public abstract class AbstractWebIntegrationTests { String content = response.getContentAsString(); Object jsonPathResult = JsonPath.read(content, path); - assertThat(String.format("JSONPath lookup for %s did return null in %s.", path, content), jsonPathResult, - is(notNullValue())); + assertThat(jsonPathResult).as("JSONPath lookup for %s did return null in %s.", path, content).isNotNull(); if (jsonPathResult instanceof JSONArray) { JSONArray array = (JSONArray) jsonPathResult; - assertThat(array, hasSize(greaterThan(0))); + assertThat(array.size()).isGreaterThan(0); } return (T) jsonPathResult; @@ -223,7 +227,7 @@ public abstract class AbstractWebIntegrationTests { jsonString = jsonQueryResults != null ? jsonQueryResults.toString() : null; } - assertThat(jsonString, is(expected)); + assertThat(jsonString).isEqualTo(expected); return jsonString; } @@ -237,8 +241,9 @@ public abstract class AbstractWebIntegrationTests { MockHttpServletResponse response = result.getResponse(); String s = response.getContentAsString(); - assertThat("Expected not to find link with rel " + rel + " but found one in " + s, // - client.getDiscoverer(response).findLinkWithRel(rel, s), nullValue()); + assertThat(client.getDiscoverer(response).findLinkWithRel(rel, s))// + .as("Expected not to find link with rel %s but found one in %s!", rel, s)// + .isNull(); } }; } diff --git a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java old mode 100644 new mode 100755 index 7a0aaa84a..f3404b16c --- a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/CommonWebTests.java @@ -1,4 +1,3 @@ -package org.springframework.data.rest.tests; /* * Copyright 2013-2017 the original author or authors. * @@ -14,9 +13,10 @@ package org.springframework.data.rest.tests; * See the License for the specific language governing permissions and * limitations under the License. */ +package org.springframework.data.rest.tests; +import static org.assertj.core.api.Assertions.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; import static org.junit.Assume.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -215,8 +215,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests { Links links = Links.valueOf(response.getHeader("Link")); - assertThat(links.hasLink(Link.REL_SELF), is(true)); - assertThat(links.hasLink("profile"), is(true)); + assertThat(links.hasLink(Link.REL_SELF)).isTrue(); + assertThat(links.hasLink("profile")).isTrue(); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/RepositoryTestsConfig.java b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/RepositoryTestsConfig.java index d26397033..5586e1f5a 100644 --- a/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/RepositoryTestsConfig.java +++ b/spring-data-rest-tests/spring-data-rest-tests-core/src/test/java/org/springframework/data/rest/tests/RepositoryTestsConfig.java @@ -39,12 +39,12 @@ import org.springframework.data.rest.core.mapping.RepositoryResourceMappings; import org.springframework.data.rest.core.support.DefaultSelfLinkProvider; import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.SelfLinkProvider; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler; import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module; import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.LookupObjectSerializer; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.rest.webmvc.mapping.LinkCollector; -import org.springframework.data.rest.webmvc.spi.BackendIdConverter; import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter; import org.springframework.data.rest.webmvc.support.ExcerptProjector; import org.springframework.data.rest.webmvc.support.PagingAndSortingTemplateVariables; @@ -57,7 +57,6 @@ import org.springframework.hateoas.ResourceProcessor; import org.springframework.hateoas.core.EvoInflectorRelProvider; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.hateoas.mvc.ResourceProcessorInvoker; -import org.springframework.plugin.core.OrderAwarePluginRegistry; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -111,7 +110,7 @@ public class RepositoryTestsConfig { config().getRepositoryDetectionStrategy()); EntityLinks entityLinks = new RepositoryEntityLinks(repositories(), mappings, config(), mock(PagingAndSortingTemplateVariables.class), - OrderAwarePluginRegistry., BackendIdConverter> create(Arrays.asList(DefaultIdConverter.INSTANCE))); + Java8PluginRegistry.of(Arrays.asList(DefaultIdConverter.INSTANCE))); SelfLinkProvider selfLinkProvider = new DefaultSelfLinkProvider(persistentEntities(), entityLinks, Collections.> emptyList()); diff --git a/spring-data-rest-tests/spring-data-rest-tests-gemfire/src/test/java/org/springframework/data/rest/tests/gemfire/GemfireWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-gemfire/src/test/java/org/springframework/data/rest/tests/gemfire/GemfireWebTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryControllerIntegrationTests.java old mode 100644 new mode 100755 index 4ecda1594..956ca7ebd --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryControllerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryControllerIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.tests.TestMvcClient.*; import org.junit.Test; @@ -50,7 +49,7 @@ public class RepositoryControllerIntegrationTests extends AbstractControllerInte @Test // DATAREST-333, DATAREST-330 public void headRequestReturnsNoContent() { - assertThat(controller.headForRepositories().getStatusCode(), is(HttpStatus.NO_CONTENT)); + assertThat(controller.headForRepositories().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); } @Test // DATAREST-160, DATAREST-333, DATAREST-463 @@ -58,14 +57,14 @@ public class RepositoryControllerIntegrationTests extends AbstractControllerInte RepositoryLinksResource resource = controller.listRepositories().getBody(); - assertThat(resource.getLinks(), hasSize(8)); + assertThat(resource.getLinks()).hasSize(8); - assertThat(resource.hasLink("people"), is(true)); - assertThat(resource.hasLink("orders"), is(true)); - assertThat(resource.hasLink("addresses"), is(true)); - assertThat(resource.hasLink("books"), is(true)); - assertThat(resource.hasLink("authors"), is(true)); - assertThat(resource.hasLink("receipts"), is(true)); - assertThat(resource.hasLink("items"), is(true)); + assertThat(resource.hasLink("people")).isTrue(); + assertThat(resource.hasLink("orders")).isTrue(); + assertThat(resource.hasLink("addresses")).isTrue(); + assertThat(resource.hasLink("books")).isTrue(); + assertThat(resource.hasLink("authors")).isTrue(); + assertThat(resource.hasLink("receipts")).isTrue(); + assertThat(resource.hasLink("items")).isTrue(); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryEntityControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryEntityControllerIntegrationTests.java old mode 100644 new mode 100755 index 5779b1302..49feed000 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryEntityControllerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryEntityControllerIntegrationTests.java @@ -15,13 +15,16 @@ */ package org.springframework.data.rest.webmvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import static org.springframework.data.rest.tests.TestMvcClient.*; import static org.springframework.http.HttpMethod.*; import java.util.List; +import java.util.Optional; import org.hamcrest.Matchers; import org.junit.Test; @@ -89,7 +92,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll RootResourceInformation information = getResourceInformation(Order.class); PersistentEntityResource persistentEntityResource = PersistentEntityResource - .build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build(); + .build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build(); ResponseEntity entity = controller.putItemResource(information, persistentEntityResource, 1L, assembler, ETag.NO_ETAG, MediaType.APPLICATION_JSON_VALUE); @@ -101,7 +104,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll public void exposesHeadForCollectionResourceIfExported() throws Exception { ResponseEntity entity = controller.headCollectionResource(getResourceInformation(Person.class), new DefaultedPageable(null, false)); - assertThat(entity.getStatusCode(), is(HttpStatus.NO_CONTENT)); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); } @Test(expected = ResourceNotFoundException.class) // DATAREST-330 @@ -117,7 +120,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll ResponseEntity entity = controller.headForItemResource(getResourceInformation(Address.class), address.id, assembler); - assertThat(entity.getStatusCode(), is(HttpStatus.NO_CONTENT)); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); } @Test(expected = ResourceNotFoundException.class) // DATAREST-330 @@ -153,7 +156,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll List value = entity.getHeaders().get("Accept-Patch"); - assertThat(value, hasSize(3)); + assertThat(value).hasSize(3); assertThat(value, hasItems(// RestMediaTypes.JSON_PATCH_JSON.toString(), // @@ -168,7 +171,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll Order order = request.getInvoker().invokeSave(new Order(new Person())); PersistentEntityResource persistentEntityResource = PersistentEntityResource - .build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build(); + .build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build(); assertThat(controller.putItemResource(request, persistentEntityResource, order.getId(), assembler, ETag.NO_ETAG, MediaType.APPLICATION_JSON_VALUE).hasBody(), is(true)); @@ -179,7 +182,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll RootResourceInformation request = getResourceInformation(Order.class); PersistentEntityResource persistentEntityResource = PersistentEntityResource - .build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build(); + .build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build(); assertThat(controller.putItemResource(request, persistentEntityResource, 1L, assembler, ETag.NO_ETAG, MediaType.APPLICATION_JSON_VALUE).hasBody(), is(true)); @@ -190,7 +193,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll RootResourceInformation request = getResourceInformation(Order.class); PersistentEntityResource persistentEntityResource = PersistentEntityResource - .build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build(); + .build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build(); assertThat(controller .postCollectionResource(request, persistentEntityResource, assembler, MediaType.APPLICATION_JSON_VALUE) @@ -202,7 +205,7 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll RootResourceInformation request = getResourceInformation(Order.class); PersistentEntityResource persistentEntityResource = PersistentEntityResource - .build(new Order(new Person()), entities.getPersistentEntity(Order.class)).build(); + .build(new Order(new Person()), entities.getRequiredPersistentEntity(Order.class)).build(); assertThat(controller.postCollectionResource(request, persistentEntityResource, assembler, null).hasBody(), is(false)); @@ -220,32 +223,32 @@ public class RepositoryEntityControllerIntegrationTests extends AbstractControll .createProjection(AddressProjection.class); PersistentEntityResource resource = PersistentEntityResource - .build(addressProjection, entities.getPersistentEntity(Address.class)).build(); + .build(addressProjection, entities.getRequiredPersistentEntity(Address.class)).build(); Mockito.when(assembler.toFullResource(Mockito.any(Object.class))).thenReturn(resource); ResponseEntity> entity = controller.getItemResource(getResourceInformation(Address.class), address.id, assembler, new HttpHeaders()); - assertThat(entity.getHeaders().getETag(), is(notNullValue())); + assertThat(entity.getHeaders().getETag()).isNotNull(); } @Test // DATAREST-724 public void deletesEntityWithCustomLookupCorrectly() throws Exception { Address address = repository.save(new Address()); - assertThat(repository.findOne(address.id), is(notNullValue())); + assertThat(repository.findOne(address.id)).isNotNull(); RootResourceInformation resourceInformation = getResourceInformation(Address.class); RepositoryInvoker invoker = spy(resourceInformation.getInvoker()); - doReturn(address).when(invoker).invokeFindOne("foo"); + doReturn(Optional.of(address)).when(invoker).invokeFindOne("foo"); RootResourceInformation informationSpy = Mockito.spy(resourceInformation); doReturn(invoker).when(informationSpy).getInvoker(); controller.deleteItemResource(informationSpy, "foo", ETag.from("0")); - assertThat(repository.findOne(address.id), is(nullValue())); + assertThat(repository.findOne(address.id)).isEmpty(); } interface AddressProjection {} diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchControllerIntegrationTests.java old mode 100644 new mode 100755 index d67ef3641..292f9e8eb --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchControllerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchControllerIntegrationTests.java @@ -15,14 +15,14 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.tests.TestMvcClient.*; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.tests.AbstractControllerIntegrationTests; import org.springframework.data.rest.tests.ResourceTester; @@ -56,7 +56,7 @@ import org.springframework.util.MultiValueMap; @Transactional public class RepositorySearchControllerIntegrationTests extends AbstractControllerIntegrationTests { - static final DefaultedPageable PAGEABLE = new DefaultedPageable(new PageRequest(0, 10), true); + static final DefaultedPageable PAGEABLE = new DefaultedPageable(PageRequest.of(0, 10), true); @Autowired TestDataPopulator loader; @Autowired RepositorySearchController controller; @@ -101,12 +101,12 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll MultiValueMap parameters = new LinkedMultiValueMap(1); parameters.add("firstname", "John"); - ResponseEntity response = controller.executeSearch(resourceInformation, parameters, "firstname", PAGEABLE, null, - assembler, new HttpHeaders()); + ResponseEntity response = controller.executeSearch(resourceInformation, parameters, "firstname", PAGEABLE, + Sort.unsorted(), assembler, new HttpHeaders()); ResourceTester tester = ResourceTester.of(response.getBody()); PagedResources pagedResources = tester.assertIsPage(); - assertThat(pagedResources.getContent().size(), is(1)); + assertThat(pagedResources.getContent()).hasSize(1); ResourceMetadata metadata = getMetadata(Person.class); tester.withContentResource(new HasSelfLink(BASE.slash(metadata.getPath()).slash("{id}"))); @@ -165,9 +165,9 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll RootResourceInformation resourceInformation = getResourceInformation(Book.class); ResponseEntity result = controller.executeSearch(resourceInformation, parameters, "findByAuthorsContains", - PAGEABLE, null, assembler, new HttpHeaders()); + PAGEABLE, Sort.unsorted(), assembler, new HttpHeaders()); - assertThat(result.getBody(), is(instanceOf(Resources.class))); + assertThat(result.getBody()).isInstanceOf(Resources.class); } @Test // DATAREST-515 @@ -175,6 +175,6 @@ public class RepositorySearchControllerIntegrationTests extends AbstractControll RepositorySearchesResource searches = controller.listSearches(getResourceInformation(Person.class)); - assertThat(searches.getDomainType(), is(typeCompatibleWith(Person.class))); + assertThat(searches.getDomainType()).isAssignableFrom(Person.class); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationIntegrationTests.java old mode 100644 new mode 100755 index 9e6b8e153..57b04f1dd --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.data.rest.core.mapping.ResourceType.*; import static org.springframework.http.HttpMethod.*; @@ -44,13 +43,13 @@ public class RootResourceInformationIntegrationTests extends AbstractControllerI public void getIsNotSupportedIfFindAllIsNotExported() { SupportedHttpMethods supportedMethods = getResourceInformation(Address.class).getSupportedMethods(); - assertThat(supportedMethods.getMethodsFor(COLLECTION), not(hasItem(GET))); + assertThat(supportedMethods.getMethodsFor(COLLECTION)).doesNotContain(GET); } @Test // DATAREST-217 public void postIsNotSupportedIfSaveIsNotExported() { SupportedHttpMethods supportedMethods = getResourceInformation(Address.class).getSupportedMethods(); - assertThat(supportedMethods.getMethodsFor(COLLECTION), not(hasItem(POST))); + assertThat(supportedMethods.getMethodsFor(COLLECTION)).doesNotContain(POST); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/alps/AlpsControllerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/alps/AlpsControllerIntegrationTests.java old mode 100644 new mode 100755 index 632b5372b..3472e8740 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/alps/AlpsControllerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/alps/AlpsControllerIntegrationTests.java @@ -15,8 +15,10 @@ */ package org.springframework.data.rest.webmvc.alps; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import net.minidev.json.JSONArray; @@ -135,7 +137,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio Link profileLink = client.discoverUnique("profile"); Link itemsLink = client.discoverUnique(profileLink, "items", MediaType.ALL); - assertThat(itemsLink, is(notNullValue())); + assertThat(itemsLink).isNotNull(); String result = client.follow(itemsLink, RestMediaTypes.ALPS_JSON).andReturn().getResponse().getContentAsString(); String href = JsonPath. read(result, "$.alps.descriptors[?(@.id == 'item-representation')].href").get(0) @@ -158,7 +160,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio String result = client.follow(usersLink, RestMediaTypes.ALPS_JSON).andReturn().getResponse().getContentAsString(); String rt = JsonPath. read(result, jsonPath).get(0).toString(); - assertThat(rt, allOf(containsString(ProfileController.PROFILE_ROOT_MAPPING), endsWith("-representation"))); + assertThat(rt).contains(ProfileController.PROFILE_ROOT_MAPPING).endsWith("-representation"); } @Test // DATAREST-630 @@ -187,7 +189,7 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio "$.alps.descriptors[?(@.id == 'person-representation')].descriptors[?(@.name == 'gender')].doc.value") .get(0).toString(); - assertThat(value, is("Male, Female, Undefined")); + assertThat(value).isEqualTo("Male, Female, Undefined"); } @Test // DATAREST-753 @@ -203,6 +205,6 @@ public class AlpsControllerIntegrationTests extends AbstractControllerIntegratio "$.alps.descriptors[?(@.id == 'simulatedGroovyDomainClass-representation')].descriptors[0].name") .get(0).toString(); - assertThat(name, is("name")); + assertThat(name).isEqualTo("name"); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/CorsIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/CorsIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java old mode 100644 new mode 100755 index 5dc799967..497ab601a --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest262Tests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.jpa; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import javax.persistence.Embeddable; import javax.persistence.Embedded; @@ -84,7 +83,7 @@ public class DataRest262Tests { String payload = "{\"orgOrDstFlightPart\":{\"airport\":\"/api/airports/" + airport.id + "\"}}"; AircraftMovement result = mapper.readValue(payload, AircraftMovement.class); - assertThat(result.orgOrDstFlightPart.airport.id, is(airport.id)); + assertThat(result.orgOrDstFlightPart.airport.id).isEqualTo(airport.id); } @Test // DATAREST-262 @@ -105,7 +104,7 @@ public class DataRest262Tests { movement.originOrDestinationAirport = first; movement.orgOrDstFlightPart = part; - JpaPersistentEntity persistentEntity = mappingContext.getPersistentEntity(AircraftMovement.class); + JpaPersistentEntity persistentEntity = mappingContext.getRequiredPersistentEntity(AircraftMovement.class); Resource resource = PersistentEntityResource.build(movement, persistentEntity).// withLink(new Link("/api/airports/" + movement.id)).// @@ -113,9 +112,9 @@ public class DataRest262Tests { String result = mapper.writeValueAsString(resource); - assertThat(JsonPath.read(result, "$_links.self"), is(notNullValue())); - assertThat(JsonPath.read(result, "$_links.airport"), is(notNullValue())); - assertThat(JsonPath.read(result, "$_links.originOrDestinationAirport"), is(notNullValue())); + assertThat(JsonPath. read(result, "$_links.self")).isNotNull(); + assertThat(JsonPath. read(result, "$_links.airport")).isNotNull(); + assertThat(JsonPath. read(result, "$_links.originOrDestinationAirport")).isNotNull(); } public interface AircraftMovementRepository extends CrudRepository { diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest363Tests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/DataRest363Tests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaDefaultPageableWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaDefaultPageableWebTests.java old mode 100644 new mode 100755 index d5f5f5aa3..25c55755f --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaDefaultPageableWebTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaDefaultPageableWebTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.jpa; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -96,8 +95,8 @@ public class JpaDefaultPageableWebTests extends AbstractWebIntegrationTests { Link findBySortedLink = client.discoverUnique("books", "search", "find-spring-books-sorted"); // Assert sort options advertised - assertThat(findBySortedLink.isTemplated(), is(true)); - assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection")); + assertThat(findBySortedLink.isTemplated()).isTrue(); + assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection"); // Assert results returned as specified client.follow(findBySortedLink.expand()).// diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java old mode 100644 new mode 100755 index b8a952f7f..0fcda0a64 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/JpaWebTests.java @@ -15,8 +15,10 @@ */ package org.springframework.data.rest.webmvc.jpa; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import static org.springframework.data.rest.webmvc.util.TestUtils.*; import static org.springframework.http.HttpHeaders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -149,7 +151,7 @@ public class JpaWebTests extends CommonWebTests { MockHttpServletResponse orders = client.request(ordersLink); Link creatorLink = assertHasContentLinkWithRel("creator", orders); - assertThat(client.request(creatorLink), is(notNullValue())); + assertThat(client.request(creatorLink)).isNotNull(); } @Test // DATAREST-200 @@ -201,18 +203,18 @@ public class JpaWebTests extends CommonWebTests { Link bilboLink = client.assertHasLinkWithRel("self", bilbo); - assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName"), is("Bilbo")); - assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName"), is("Baggins")); + assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName")).isEqualTo("Bilbo"); + assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName")).isEqualTo("Baggins"); MockHttpServletResponse frodo = patchAndGet(bilboLink, "{ \"firstName\" : \"Frodo\" }", MediaType.APPLICATION_JSON); - assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is("Frodo")); - assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins")); + assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isEqualTo("Frodo"); + assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins"); frodo = patchAndGet(bilboLink, "{ \"firstName\" : null }", MediaType.APPLICATION_JSON); - assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is(nullValue())); - assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins")); + assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName")).isNull(); + assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName")).isEqualTo("Baggins"); } @Test // DATAREST-150 @@ -411,17 +413,17 @@ public class JpaWebTests extends CommonWebTests { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(orderLink.getHref()); String uri = builder.queryParam("projection", "summary").build().toUriString(); - response = mvc.perform(get(uri)). // - andExpect(status().isOk()). // - andExpect(jsonPath("$.price", is(2.5))).// - andReturn().getResponse(); + response = mvc.perform(get(uri))// + .andExpect(status().isOk())// + .andExpect(jsonPath("$.price", is(2.5)))// + .andReturn().getResponse(); assertJsonPathDoesntExist("$.lineItems", response); } @Test // DATAREST-261 public void relProviderDetectsCustomizedMapping() { - assertThat(relProvider.getCollectionResourceRelFor(Person.class), is("people")); + assertThat(relProvider.getCollectionResourceRelFor(Person.class)).isEqualTo("people"); } @Test // DATAREST-311 @@ -445,9 +447,9 @@ public class JpaWebTests extends CommonWebTests { JSONArray personLinks = JsonPath. read(responseBody, "$.links[?(@.rel=='person')].href"); - assertThat(personLinks, hasSize(1)); - assertThat(personLinks.get(0), is((Object) daenerysLink.getHref())); - assertThat(JsonPath. read(responseBody, "$.content"), hasSize(0)); + assertThat(personLinks).hasSize(1); + assertThat(personLinks.get(0)).isEqualTo((Object) daenerysLink.getHref()); + assertThat(JsonPath. read(responseBody, "$.content")).hasSize(0); } @Test // DATAREST-317 @@ -490,8 +492,8 @@ public class JpaWebTests extends CommonWebTests { Link findBySortedLink = client.discoverUnique(searchLink, "find-by-sorted"); // Assert sort options advertised - assertThat(findBySortedLink.isTemplated(), is(true)); - assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection")); + assertThat(findBySortedLink.isTemplated()).isTrue(); + assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection"); // Assert results returned as specified client.follow(findBySortedLink.expand("title,desc")).// @@ -575,8 +577,8 @@ public class JpaWebTests extends CommonWebTests { .andReturn().getResponse(); Links links = Links.valueOf(response.getHeader("Link")); - assertThat(links.hasLink("self"), is(true)); - assertThat(links.hasLink("person"), is(true)); + assertThat(links.hasLink("self")).isTrue(); + assertThat(links.hasLink("person")).isTrue(); } @Test // DATAREST-883 @@ -585,8 +587,8 @@ public class JpaWebTests extends CommonWebTests { Link findBySortedLink = client.discoverUnique("books", "search", "find-by-sorted"); // Assert sort options advertised - assertThat(findBySortedLink.isTemplated(), is(true)); - assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection")); + assertThat(findBySortedLink.isTemplated()).isTrue(); + assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection"); // Assert results returned as specified client.follow(findBySortedLink.expand("sales,desc")).// @@ -606,7 +608,7 @@ public class JpaWebTests extends CommonWebTests { Link findByLink = client.discoverUnique("books", "search", "find-spring-books-sorted"); // Assert sort options advertised - assertThat(findByLink.isTemplated(), is(true)); + assertThat(findByLink.isTemplated()).isTrue(); // Assert results returned as specified client.follow(findByLink.expand("0", "10", "sales,desc")).// @@ -635,8 +637,8 @@ public class JpaWebTests extends CommonWebTests { Link findBySortedLink = client.discoverUnique(searchLink, "find-by-sorted"); // Assert sort options advertised - assertThat(findBySortedLink.isTemplated(), is(true)); - assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection")); + assertThat(findBySortedLink.isTemplated()).isTrue(); + assertThat(findBySortedLink.getVariableNames()).contains("sort", "projection"); // Assert results returned as specified client.follow(findBySortedLink.expand("offer.price,desc")).// @@ -682,8 +684,8 @@ public class JpaWebTests extends CommonWebTests { String responseBody = client.request(link).getContentAsString(); List persons = JsonPath.read(responseBody, "$._embedded.people[*].firstName"); - assertThat(persons, hasSize(siblingNames.length)); - assertThat(persons, hasItems(siblingNames)); + assertThat(persons).hasSize(siblingNames.length); + assertThat(persons).contains(siblingNames); } private void assertPersonWithNameAndSiblingLink(String name) throws Exception { @@ -694,8 +696,8 @@ public class JpaWebTests extends CommonWebTests { // Assert content inlined Object john = JsonPath. read(response.getContentAsString(), jsonPath).get(0); - assertThat(john, is(notNullValue())); - assertThat(JsonPath.read(john, "$.firstName"), is(notNullValue())); + assertThat(john).isNotNull(); + assertThat(JsonPath. read(john, "$.firstName")).isNotNull(); // Assert sibling link exposed in resource pointed to Link selfLink = new Link(JsonPath. read(john, "$._links.self.href")); diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/ProfileIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/ProfileIntegrationTests.java old mode 100644 new mode 100755 index ed335b3fb..dc5aa5769 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/ProfileIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/jpa/ProfileIntegrationTests.java @@ -15,8 +15,8 @@ */ package org.springframework.data.rest.webmvc.jpa; +import static org.assertj.core.api.Assertions.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import org.junit.Before; @@ -81,19 +81,19 @@ public class ProfileIntegrationTests extends AbstractControllerIntegrationTests .andExpect(jsonPath("$._links.profile.href", endsWith(ProfileController.PROFILE_ROOT_MAPPING))); } - @Test // DATAREST-230, DATAREST-638 + @Test // DATAREST-230, DATAREST-638 public void profileRootLinkContainsMetadataForEachRepo() throws Exception { Link profileLink = client.discoverUnique(new Link(ROOT_URI), ProfileResourceProcessor.PROFILE_REL); - assertThat(client.discoverUnique(profileLink, "self", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "people", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "items", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "authors", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "books", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "orders", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "receipts", MediaType.ALL), is(notNullValue())); - assertThat(client.discoverUnique(profileLink, "addresses", MediaType.ALL), is(notNullValue())); + assertThat(client.discoverUnique(profileLink, "self", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "people", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "items", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "authors", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "books", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "orders", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "receipts", MediaType.ALL)).isNotNull(); + assertThat(client.discoverUnique(profileLink, "addresses", MediaType.ALL)).isNotNull(); } @Test // DATAREST-638 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelperIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelperIntegrationTests.java old mode 100644 new mode 100755 index 44c9eaa9b..c6f362457 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelperIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/Jackson2DatatypeHelperIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import javax.persistence.EntityManager; @@ -70,12 +69,12 @@ public class Jackson2DatatypeHelperIntegrationTests { } @Test // DATAREST-500 - public void configuresHIbernate4ModuleToLoadLazyLoadingProxies() throws Exception { + public void configuresHibernate4ModuleToLoadLazyLoadingProxies() throws Exception { - PersistentEntity entity = entities.getPersistentEntity(Order.class); - PersistentProperty property = entity.getPersistentProperty("creator"); - PersistentPropertyAccessor accessor = entity.getPropertyAccessor(orders.findOne(this.order.getId())); + PersistentEntity entity = entities.getRequiredPersistentEntity(Order.class); + PersistentProperty property = entity.getRequiredPersistentProperty("creator"); + PersistentPropertyAccessor accessor = entity.getPropertyAccessor(orders.findOne(this.order.getId()).orElse(null)); - assertThat(objectMapper.writeValueAsString(accessor.getProperty(property)), is(not("null"))); + assertThat(objectMapper.writeValueAsString(accessor.getProperty(property))).isNotEqualTo("null"); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java old mode 100644 new mode 100755 index 595a73580..c6f98e340 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java @@ -15,7 +15,8 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.MatcherAssert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.io.IOException; @@ -121,9 +122,9 @@ public class PersistentEntitySerializationTests { Person p = mapper.readValue(PERSON_JSON_IN, Person.class); - assertThat(p.getFirstName(), is("John")); - assertThat(p.getLastName(), is("Doe")); - assertThat(p.getSiblings(), is(Collections.EMPTY_LIST)); + assertThat(p.getFirstName()).isEqualTo("John"); + assertThat(p.getLastName()).isEqualTo("Doe"); + assertThat(p.getSiblings()).isEqualTo(Collections.EMPTY_LIST); } @Test // DATAREST-238 @@ -170,7 +171,7 @@ public class PersistentEntitySerializationTests { String child = String.format("{ \"firstName\" : \"Bilbo\", \"father\" : \"/persons/%s\"}", father.getId()); Person result = mapper.readValue(child, Person.class); - assertThat(result.getFather(), is(father)); + assertThat(result.getFather()).isEqualTo(father); } @Test // DATAREST-248 @@ -183,7 +184,7 @@ public class PersistentEntitySerializationTests { firstSibling.getId(), secondSibling.getId()); Person result = mapper.readValue(child, Person.class); - assertThat(result.getSiblings(), hasItems(firstSibling, secondSibling)); + assertThat(result.getSiblings()).contains(firstSibling, secondSibling); } @Test // DATAREST-248 @@ -192,7 +193,7 @@ public class PersistentEntitySerializationTests { String content = TestUtils.readFileFromClasspath("order.json"); Order order = mapper.readValue(content, Order.class); - assertThat(order.getLineItems(), hasSize(2)); + assertThat(order.getLineItems()).hasSize(2); } @Test // DATAREST-250 @@ -214,7 +215,7 @@ public class PersistentEntitySerializationTests { String result = mapper.writeValueAsString(persistentEntityResource); - assertThat(JsonPath.read(result, "$._embedded.orders[*].lineItems"), is(notNullValue())); + assertThat(JsonPath. read(result, "$._embedded.orders[*].lineItems")).isNotNull(); } @Test // DATAREST-521 @@ -237,7 +238,7 @@ public class PersistentEntitySerializationTests { String result = mapper.writeValueAsString(resource); - assertThat(JsonPath.read(result, "$._embedded.father[*]._links.self"), is(notNullValue())); + assertThat(JsonPath. read(result, "$._embedded.father[*]._links.self")).isNotNull(); } @Test // DATAREST-521 @@ -253,7 +254,7 @@ public class PersistentEntitySerializationTests { String result = mapper.writeValueAsString(resource); - assertThat(JsonPath.read(result, "$._links.processed"), is(notNullValue())); + assertThat(JsonPath. read(result, "$._links.processed")).isNotNull(); } @Test // DATAREST-697 @@ -267,7 +268,7 @@ public class PersistentEntitySerializationTests { String result = mapper.writeValueAsString(new Resource(projection)); - assertThat(JsonPath.read(result, "$._links.self"), is(notNullValue())); + assertThat(JsonPath. read(result, "$._links.self")).isNotNull(); } @Test // DATAREST-880 @@ -275,7 +276,7 @@ public class PersistentEntitySerializationTests { CreditCard creditCard = new CreditCard(new CreditCard.CCN("1234123412341234")); - assertThat(JsonPath.read(mapper.writeValueAsString(creditCard), "$.ccn"), is("1234123412341234")); + assertThat(JsonPath. read(mapper.writeValueAsString(creditCard), "$.ccn")).isEqualTo("1234123412341234"); } @Test // DATAREST-872 @@ -292,12 +293,12 @@ public class PersistentEntitySerializationTests { guest.addMeal(dinner); PersistentEntityResource resource = PersistentEntityResource// - .build(guest, context.getPersistentEntity(Guest.class))// + .build(guest, context.getRequiredPersistentEntity(Guest.class))// .withLink(new Link("/guests/1")).build(); String result = mapper.writeValueAsString(resource); - assertThat(JsonPath.read(result, "$.room.type"), equalTo("suite")); - assertThat(JsonPath.read(result, "$.meals[0].type"), equalTo("dinner")); + assertThat(JsonPath. read(result, "$.room.type")).isEqualTo("suite"); + assertThat(JsonPath. read(result, "$.meals[0].type")).isEqualTo("dinner"); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java index f430462fc..2f8a13e1f 100644 --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/json/RepositoryTestsConfig.java @@ -39,13 +39,13 @@ import org.springframework.data.rest.core.mapping.RepositoryResourceMappings; import org.springframework.data.rest.core.support.DefaultSelfLinkProvider; import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.SelfLinkProvider; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler; import org.springframework.data.rest.webmvc.jpa.Person; import org.springframework.data.rest.webmvc.jpa.PersonRepository; import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.LookupObjectSerializer; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.rest.webmvc.mapping.LinkCollector; -import org.springframework.data.rest.webmvc.spi.BackendIdConverter; import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter; import org.springframework.data.rest.webmvc.support.ExcerptProjector; import org.springframework.data.rest.webmvc.support.PagingAndSortingTemplateVariables; @@ -58,7 +58,6 @@ import org.springframework.hateoas.ResourceProcessor; import org.springframework.hateoas.core.EvoInflectorRelProvider; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.hateoas.mvc.ResourceProcessorInvoker; -import org.springframework.plugin.core.OrderAwarePluginRegistry; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -119,7 +118,7 @@ public class RepositoryTestsConfig { config().getRepositoryDetectionStrategy()); EntityLinks entityLinks = new RepositoryEntityLinks(repositories(), mappings, config(), mock(PagingAndSortingTemplateVariables.class), - OrderAwarePluginRegistry., BackendIdConverter> create(Arrays.asList(DefaultIdConverter.INSTANCE))); + Java8PluginRegistry.of(Arrays.asList(DefaultIdConverter.INSTANCE))); SelfLinkProvider selfLinkProvider = new DefaultSelfLinkProvider(persistentEntities(), entityLinks, Collections.> emptyList()); diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/BackendIdConverterHandlerMethodArgumentResolverIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/BackendIdConverterHandlerMethodArgumentResolverIntegrationTests.java old mode 100644 new mode 100755 index 7df77e7ca..82b93642a --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/BackendIdConverterHandlerMethodArgumentResolverIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/BackendIdConverterHandlerMethodArgumentResolverIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.io.Serializable; import java.lang.reflect.Method; @@ -53,7 +52,7 @@ public class BackendIdConverterHandlerMethodArgumentResolverIntegrationTests Object resolvedId = resolver.resolveArgument(parameter, null, request, null); - assertThat(resolvedId, is((Object) 5L)); + assertThat(resolvedId).isEqualTo(5L); } static class SampleController { diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/ExceptionHandlingCustomizationIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/ExceptionHandlingCustomizationIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinksIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinksIntegrationTests.java old mode 100644 new mode 100755 index 04da7898a..c24365eef --- a/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinksIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinksIntegrationTests.java @@ -15,8 +15,10 @@ */ package org.springframework.data.rest.webmvc.support; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.allOf; +import static org.junit.Assert.assertThat; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -51,7 +53,7 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Link link = entityLinks.linkToSingleResource(Person.class, 1); assertThat(link.getHref(), endsWith("/people/1{?projection}")); - assertThat(link.getRel(), is("person")); + assertThat(link.getRel()).isEqualTo("person"); } @Test @@ -59,9 +61,9 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Link link = entityLinks.linkToCollectionResource(Person.class); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItems("page", "size", "sort")); - assertThat(link.getRel(), is("people")); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains("page", "size", "sort"); + assertThat(link.getRel()).isEqualTo("people"); } @Test // DATAREST-221 @@ -69,8 +71,8 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Link link = entityLinks.linkToSingleResource(Order.class, 1); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItem(configuration.getProjectionConfiguration().getParameterName())); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains(configuration.getProjectionConfiguration().getParameterName()); } @Test // DATAREST-155 @@ -83,11 +85,11 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt @Test // DATAREST-317 public void adaptsToExistingPageable() { - Link link = entityLinks.linkToPagedResource(Person.class, new PageRequest(0, 10)); + Link link = entityLinks.linkToPagedResource(Person.class, PageRequest.of(0, 10)); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasSize(2)); - assertThat(link.getVariableNames(), hasItems("sort", "projection")); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).hasSize(2); + assertThat(link.getVariableNames()).contains("sort", "projection"); } @Test // DATAREST-467 @@ -95,11 +97,11 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Links links = entityLinks.linksToSearchResources(Person.class); - assertThat(links.hasLink("firstname"), is(true)); + assertThat(links.hasLink("firstname")).isTrue(); Link firstnameLink = links.getLink("firstname"); - assertThat(firstnameLink.isTemplated(), is(true)); - assertThat(firstnameLink.getVariableNames(), hasItems("page", "size")); + assertThat(firstnameLink.isTemplated()).isTrue(); + assertThat(firstnameLink.getVariableNames()).contains("page", "size"); } @Test // DATAREST-467 @@ -107,20 +109,20 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Link link = entityLinks.linkToSearchResource(Person.class, "firstname"); - assertThat(link, is(notNullValue())); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItems("firstname", "page", "size")); + assertThat(link).isNotNull(); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains("firstname", "page", "size"); } @Test // DATAREST-467, DATAREST-519 public void prepopulatesPaginationInformationForSearchResourceLink() { - Link link = entityLinks.linkToSearchResource(Person.class, "firstname", new PageRequest(0, 10)); + Link link = entityLinks.linkToSearchResource(Person.class, "firstname", PageRequest.of(0, 10)); - assertThat(link, is(notNullValue())); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItem("firstname")); - assertThat(link.getVariableNames(), not(hasItems("page", "size"))); + assertThat(link).isNotNull(); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains("firstname"); + assertThat(link.getVariableNames()).doesNotContain("page", "size"); UriComponents components = UriComponentsBuilder.fromUriString(link.getHref()).build(); assertThat(components.getQueryParams(), allOf(hasKey("page"), hasKey("size"))); @@ -131,19 +133,19 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt Link link = entityLinks.linkToSearchResource(Person.class, "lastname"); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItems("lastname", "sort")); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains("lastname", "sort"); } @Test // DATAREST-467, DATAREST-519 public void prepopulatesSortInformationForSearchResourceLink() { - Link link = entityLinks.linkToSearchResource(Person.class, "lastname", new Sort("firstname")); + Link link = entityLinks.linkToSearchResource(Person.class, "lastname", Sort.by("firstname")); - assertThat(link, is(notNullValue())); - assertThat(link.isTemplated(), is(true)); - assertThat(link.getVariableNames(), hasItem("lastname")); - assertThat(link.getVariableNames(), not(hasItems("sort"))); + assertThat(link).isNotNull(); + assertThat(link.isTemplated()).isTrue(); + assertThat(link.getVariableNames()).contains("lastname"); + assertThat(link.getVariableNames()).doesNotContain("sort"); UriComponents components = UriComponentsBuilder.fromUriString(link.getHref()).build(); assertThat(components.getQueryParams(), hasKey("sort")); @@ -153,7 +155,7 @@ public class RepositoryEntityLinksIntegrationTests extends AbstractControllerInt public void addsProjectVariableToSearchResourceIfAvailable() { for (Link link : entityLinks.linksToSearchResources(Book.class)) { - assertThat(link.getVariableNames(), hasItem("projection")); + assertThat(link.getVariableNames()).contains("projection"); } } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/main/java/org/springframework/data/rest/tests/mongodb/UserRepository.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/main/java/org/springframework/data/rest/tests/mongodb/UserRepository.java index 8d81a0063..39cf5c666 100644 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/main/java/org/springframework/data/rest/tests/mongodb/UserRepository.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/main/java/org/springframework/data/rest/tests/mongodb/UserRepository.java @@ -18,14 +18,14 @@ package org.springframework.data.rest.tests.mongodb; import java.math.BigInteger; import java.util.List; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; /** * @author Oliver Gierke */ -public interface UserRepository extends CrudRepository, QueryDslPredicateExecutor { +public interface UserRepository extends CrudRepository, QuerydslPredicateExecutor { List findByFirstname(String firstname); diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java old mode 100644 new mode 100755 index 223405a61..6c511346b --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/tests/mongodb/MongoWebTests.java @@ -15,8 +15,8 @@ */ package org.springframework.data.rest.tests.mongodb; +import static org.assertj.core.api.Assertions.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; import static org.springframework.http.HttpHeaders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -25,6 +25,7 @@ import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; +import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -133,11 +134,11 @@ public class MongoWebTests extends CommonWebTests { Link profileSearches = client.discoverUnique(profiles, "search"); Link countByTypeLink = client.discoverUnique(profileSearches, "countByType"); - assertThat(countByTypeLink.isTemplated(), is(true)); - assertThat(countByTypeLink.getVariableNames(), hasItem("type")); + assertThat(countByTypeLink.isTemplated()).isTrue(); + assertThat(countByTypeLink.getVariableNames()).contains("type"); MockHttpServletResponse response = client.request(countByTypeLink.expand("Twitter")); - assertThat(response.getContentAsString(), is("1")); + assertThat(response.getContentAsString()).isEqualTo("1"); } @Test @@ -147,10 +148,11 @@ public class MongoWebTests extends CommonWebTests { Link userLink = assertHasContentLinkWithRel("self", client.request(usersLink)); MockHttpServletResponse response = patchAndGet(userLink, - "{\"lastname\" : null, \"address\" : { \"zipCode\" : \"ZIP\"}}", MediaType.APPLICATION_JSON); + "{\"lastname\" : null, \"address\" : { \"zipCode\" : \"ZIP\"}}", + org.springframework.http.MediaType.APPLICATION_JSON); - assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue())); - assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP")); + assertThat(JsonPath. read(response.getContentAsString(), "$.lastname")).isNull(); + assertThat(JsonPath. read(response.getContentAsString(), "$.address.zipCode")).isEqualTo("ZIP"); } @Test @@ -165,8 +167,8 @@ public class MongoWebTests extends CommonWebTests { + "{ \"op\": \"remove\", \"path\": \"/lastname\" }]", // RestMediaTypes.JSON_PATCH_JSON); - assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue())); - assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP")); + assertThat(JsonPath. read(response.getContentAsString(), "$.lastname")).isNull(); + assertThat(JsonPath. read(response.getContentAsString(), "$.address.zipCode")).isEqualTo("ZIP"); } @Test // DATAREST-160 @@ -204,7 +206,7 @@ public class MongoWebTests extends CommonWebTests { String header = mvc.perform(get("/profiles/{id}", profile.getId())).// andReturn().getResponse().getHeader("Last-Modified"); - assertThat(header, not(isEmptyOrNullString())); + assertThat(header).isNot(new Condition(it -> it == null || it.isEmpty(), "Foo")); } @Test // DATAREST-482 diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssemblerIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssemblerIntegrationTests.java old mode 100644 new mode 100755 index 02ad92283..983fe8040 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssemblerIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssemblerIntegrationTests.java @@ -15,15 +15,13 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.math.BigInteger; import java.util.Collections; -import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.internal.stubbing.answers.ReturnsArgumentAt; import org.springframework.beans.factory.annotation.Autowired; @@ -38,7 +36,6 @@ import org.springframework.data.rest.tests.mongodb.User; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.rest.webmvc.support.Projector; import org.springframework.hateoas.EntityLinks; -import org.springframework.hateoas.Link; import org.springframework.hateoas.Links; import org.springframework.test.context.ContextConfiguration; @@ -62,7 +59,7 @@ public class PersistentEntityResourceAssemblerIntegrationTests extends AbstractC Projector projector = mock(Projector.class); - when(projector.projectExcerpt(anyObject())).thenAnswer(new ReturnsArgumentAt(0)); + when(projector.projectExcerpt(any())).thenAnswer(new ReturnsArgumentAt(0)); PersistentEntityResourceAssembler assembler = new PersistentEntityResourceAssembler(entities, projector, associations, new DefaultSelfLinkProvider(entities, entityLinks, Collections.> emptyList())); @@ -74,8 +71,8 @@ public class PersistentEntityResourceAssemblerIntegrationTests extends AbstractC Links links = new Links(resource.getLinks()); - assertThat(links, is(Matchers. iterableWithSize(2))); - assertThat(links.getLink("self").getVariables(), is(Matchers.empty())); - assertThat(links.getLink("user").getVariableNames(), is(hasItem("projection"))); + assertThat(links).hasSize(2); + assertThat(links.getLink("self").getVariables()).isEmpty(); + assertThat(links.getLink("user").getVariableNames()).contains("projection"); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingIntegrationTests.java old mode 100644 new mode 100755 index fc9fee496..994b41dcb --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingIntegrationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -47,13 +46,13 @@ public class RepositoryRestHandlerMappingIntegrationTests extends AbstractContro HandlerExecutionChain chain = mapping.getHandler(mockRequest); - assertThat(chain, is(notNullValue())); + assertThat(chain).isNotNull(); Object handler = chain.getHandler(); - assertThat(handler, is(instanceOf(HandlerMethod.class))); + assertThat(handler).isInstanceOf(HandlerMethod.class); HandlerMethod method = (HandlerMethod) handler; - assertThat(method.getMethod().getDeclaringClass(), is(typeCompatibleWith(RepositoryEntityController.class))); - assertThat(method.getMethod().getName(), is("getCollectionResource")); + assertThat(method.getMethod().getDeclaringClass()).isAssignableFrom(RepositoryEntityController.class); + assertThat(method.getMethod().getName()).isEqualTo("getCollectionResource"); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/AbstractRepositoryRestMvcConfigurationIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/AbstractRepositoryRestMvcConfigurationIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/JsonPatchHandlerUnitTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/JsonPatchHandlerUnitTests.java old mode 100644 new mode 100755 index 65f4bda48..154798d0f --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/JsonPatchHandlerUnitTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/JsonPatchHandlerUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.config; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import static org.springframework.data.rest.tests.mongodb.TestUtils.*; @@ -29,7 +28,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; @@ -87,8 +86,8 @@ public class JsonPatchHandlerUnitTests { User result = handler.applyPatch(asStream(input), user); - assertThat(result.lastname, is(nullValue())); - assertThat(result.address.zipCode, is("ZIP")); + assertThat(result.lastname).isNull(); + assertThat(result.address.zipCode).isEqualTo("ZIP"); } @Test // DATAREST-348 @@ -98,8 +97,8 @@ public class JsonPatchHandlerUnitTests { User result = handler.applyMergePatch(asStream(input), user); - assertThat(result.lastname, is(nullValue())); - assertThat(result.address.zipCode, is("ZIP")); + assertThat(result.lastname).isNull(); + assertThat(result.address.zipCode).isEqualTo("ZIP"); } /** @@ -120,8 +119,8 @@ public class JsonPatchHandlerUnitTests { handler.applyPatch(asStream(input), user); - assertThat(user.colleagues, hasSize(1)); - assertThat(user.colleagues.get(0).firstname, is(christoph.firstname)); + assertThat(user.colleagues).hasSize(1); + assertThat(user.colleagues.get(0).firstname).isEqualTo(christoph.firstname); } @Test // DATAREST-609 diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/LegacyRepresentationConfigIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/LegacyRepresentationConfigIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUnitTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUnitTests.java old mode 100644 new mode 100755 index b06223eec..d99704042 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUnitTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUnitTests.java @@ -15,22 +15,22 @@ */ package org.springframework.data.rest.webmvc.config; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Collections; import java.util.Map; +import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.MethodParameter; import org.springframework.core.convert.support.DefaultConversionService; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.QuerydslRepositoryInvokerAdapter; import org.springframework.data.querydsl.SimpleEntityPathResolver; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; @@ -70,7 +70,7 @@ public class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUn public void setUp() { QuerydslBindingsFactory factory = new QuerydslBindingsFactory(SimpleEntityPathResolver.INSTANCE); - ReflectionTestUtils.setField(factory, "repositories", repositories); + ReflectionTestUtils.setField(factory, "repositories", Optional.of(repositories)); QuerydslPredicateBuilder builder = new QuerydslPredicateBuilder(new DefaultConversionService(), factory.getEntityPathResolver()); @@ -84,39 +84,38 @@ public class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolverUn public void returnsInvokerIfRepositoryIsNotQuerydslAware() { ReceiptRepository repository = mock(ReceiptRepository.class); - when(repositories.getRepositoryFor(Receipt.class)).thenReturn(repository); + when(repositories.getRepositoryFor(Receipt.class)).thenReturn(Optional.of(repository)); RepositoryInvoker result = resolver.postProcess(parameter, invoker, Receipt.class, NO_PARAMETERS); - assertThat(result, is(invoker)); + assertThat(result).isEqualTo(invoker); } @Test // DATAREST-616 public void wrapsInvokerInQuerydslAdapter() { Object repository = mock(QuerydslUserRepository.class); - when(repositories.getRepositoryFor(User.class)).thenReturn(repository); + when(repositories.getRepositoryFor(User.class)).thenReturn(Optional.of(repository)); RepositoryInvoker result = resolver.postProcess(parameter, invoker, User.class, NO_PARAMETERS); - assertThat(result, is(instanceOf(QuerydslRepositoryInvokerAdapter.class))); + assertThat(result).isInstanceOf(QuerydslRepositoryInvokerAdapter.class); } @Test // DATAREST-616 public void invokesCustomizationOnRepositoryIfItImplementsCustomizer() { QuerydslCustomizingUserRepository repository = mock(QuerydslCustomizingUserRepository.class); - when(repositories.hasRepositoryFor(User.class)).thenReturn(true); - when(repositories.getRepositoryFor(User.class)).thenReturn(repository); + when(repositories.getRepositoryFor(User.class)).thenReturn(Optional.of(repository)); RepositoryInvoker result = resolver.postProcess(parameter, invoker, User.class, NO_PARAMETERS); - assertThat(result, is(instanceOf(QuerydslRepositoryInvokerAdapter.class))); + assertThat(result).isInstanceOf(QuerydslRepositoryInvokerAdapter.class); verify(repository, times(1)).customize(Mockito.any(QuerydslBindings.class), Mockito.any(QUser.class)); } - interface QuerydslUserRepository extends QueryDslPredicateExecutor {} + interface QuerydslUserRepository extends QuerydslPredicateExecutor {} interface QuerydslCustomizingUserRepository - extends QueryDslPredicateExecutor, QuerydslBinderCustomizer {} + extends QuerydslPredicateExecutor, QuerydslBinderCustomizer {} } diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java old mode 100644 new mode 100755 index 495ee4386..5e198bc06 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntitySerializationTests.java @@ -15,7 +15,8 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.MatcherAssert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.util.Arrays; @@ -113,12 +114,12 @@ public class PersistentEntitySerializationTests { String result = mapper.writeValueAsString(persistentEntityResource); - assertThat(JsonPath.read(result, "$._embedded.users[*].address"), is(notNullValue())); + assertThat(JsonPath. read(result, "$._embedded.users[*].address")).isNotNull(); } @Test // DATAREST-654 public void deserializesTranslatedEnumProperty() throws Exception { - assertThat(mapper.readValue("{ \"gender\" : \"Male\" }", User.class).gender, is(Gender.MALE)); + assertThat(mapper.readValue("{ \"gender\" : \"Male\" }", User.class).gender).isEqualTo(Gender.MALE); } @Test // DATAREST-864 diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverterUnitTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverterUnitTests.java old mode 100644 new mode 100755 index 815f01727..8ca23faf6 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverterUnitTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverterUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc.json; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.ArrayList; @@ -179,7 +180,7 @@ public class PersistentEntityToJsonSchemaConverterUnitTests { try { assertThat(constraint.description, JsonPath.read(writeSchemaFor, constraint.selector), constraint.matcher); } catch (PathNotFoundException e) { - assertThat(constraint.matcher.matches(null), is(true)); + assertThat(constraint.matcher.matches(null)).isTrue(); } catch (RuntimeException e) { assertThat(e, constraint.matcher); } diff --git a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuildUnitTests.java b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuildUnitTests.java old mode 100644 new mode 100755 index 3e0e38638..1f68fa878 --- a/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuildUnitTests.java +++ b/spring-data-rest-tests/spring-data-rest-tests-mongodb/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryLinkBuildUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; @@ -61,6 +60,6 @@ public class RepositoryLinkBuildUnitTests { new BaseUri(baseUri)); Link link = builder.withSelfRel(); - assertThat(link.getHref(), is(expectedUri)); + assertThat(link.getHref()).isEqualTo(expectedUri); } } diff --git a/spring-data-rest-tests/spring-data-rest-tests-security/src/test/java/org/springframework/data/rest/tests/security/SecurityIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-security/src/test/java/org/springframework/data/rest/tests/security/SecurityIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-shop/src/test/java/org/springframework/data/rest/tests/shop/ShopIntegrationTests.java b/spring-data-rest-tests/spring-data-rest-tests-shop/src/test/java/org/springframework/data/rest/tests/shop/ShopIntegrationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/java/org/springframework/data/rest/webmvc/solr/SolrWebTests.java b/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/java/org/springframework/data/rest/webmvc/solr/SolrWebTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/resources/org/springframework/data/rest/webmvc/solr/schema.xml b/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/resources/org/springframework/data/rest/webmvc/solr/schema.xml index d4422dae5..fee19bad9 100644 --- a/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/resources/org/springframework/data/rest/webmvc/solr/schema.xml +++ b/spring-data-rest-tests/spring-data-rest-tests-solr/src/test/resources/org/springframework/data/rest/webmvc/solr/schema.xml @@ -4,8 +4,7 @@ - + diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java index c93b928c3..eef470fc6 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ControllerUtils.java @@ -16,12 +16,14 @@ package org.springframework.data.rest.webmvc; import java.util.Collections; +import java.util.Optional; import org.springframework.hateoas.Resource; import org.springframework.hateoas.ResourceSupport; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.util.Assert; /** * @author Oliver Gierke @@ -31,6 +33,18 @@ public class ControllerUtils { public static final Iterable> EMPTY_RESOURCE_LIST = Collections.emptyList(); + public static ResponseEntity toResponseEntity(HttpStatus status, + HttpHeaders headers, Optional resource) { + + HttpHeaders hdrs = new HttpHeaders(); + + if (headers != null) { + hdrs.putAll(headers); + } + + return new ResponseEntity(resource.orElse(null), hdrs, status); + } + /** * Wrap a resource as a {@link ResourceEntity} and attach given headers and status. * @@ -43,13 +57,11 @@ public class ControllerUtils { public static ResponseEntity toResponseEntity(HttpStatus status, HttpHeaders headers, R resource) { - HttpHeaders hdrs = new HttpHeaders(); + Assert.notNull(status, "Http status must not be null!"); + Assert.notNull(headers, "Http headers must not be null!"); + Assert.notNull(resource, "Payload must not be null!"); - if (headers != null) { - hdrs.putAll(headers); - } - - return new ResponseEntity(resource, hdrs, status); + return toResponseEntity(status, headers, Optional.of(resource)); } /** @@ -59,7 +71,7 @@ public class ControllerUtils { * @return */ public static ResponseEntity toEmptyResponse(HttpStatus status) { - return toEmptyResponse(status, null); + return toEmptyResponse(status, new HttpHeaders()); } /** @@ -70,6 +82,6 @@ public class ControllerUtils { * @return */ public static ResponseEntity toEmptyResponse(HttpStatus status, HttpHeaders headers) { - return toResponseEntity(status, headers, null); + return toResponseEntity(status, headers, Optional.empty()); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/EmbeddedResourcesAssembler.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/EmbeddedResourcesAssembler.java index 66dd15657..72413300f 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/EmbeddedResourcesAssembler.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/EmbeddedResourcesAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.springframework.data.mapping.Association; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.PersistentPropertyAccessor; @@ -57,42 +56,31 @@ public class EmbeddedResourcesAssembler { Assert.notNull(instance, "Entity instance must not be null!"); - PersistentEntity entity = entities.getPersistentEntity(instance.getClass()); + PersistentEntity entity = entities.getRequiredPersistentEntity(instance.getClass()); final List associationProjections = new ArrayList(); final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance); final ResourceMetadata metadata = associations.getMetadataFor(entity.getType()); - entity.doWithAssociations(new SimpleAssociationHandler() { + entity.doWithAssociations((SimpleAssociationHandler) association -> { - /* - * (non-Javadoc) - * @see org.springframework.data.mapping.SimpleAssociationHandler#doWithAssociation(org.springframework.data.mapping.Association) - */ - @Override - public void doWithAssociation(Association> association) { + PersistentProperty property = association.getInverse(); - PersistentProperty property = association.getInverse(); + if (!associations.isLinkableAssociation(property)) { + return; + } - if (!associations.isLinkableAssociation(property)) { - return; - } + if (!projector.hasExcerptProjection(property.getActualType())) { + return; + } - if (!projector.hasExcerptProjection(property.getActualType())) { - return; - } - - Object value = accessor.getProperty(association.getInverse()); - - if (value == null) { - return; - } + accessor.getProperty(association.getInverse()).ifPresent(it -> { String rel = metadata.getMappingFor(property).getRel(); - if (value instanceof Collection) { + if (it instanceof Collection) { - Collection collection = (Collection) value; + Collection collection = (Collection) it; if (collection.isEmpty()) { return; @@ -109,9 +97,9 @@ public class EmbeddedResourcesAssembler { associationProjections.add(wrappers.wrap(nestedCollection, rel)); } else { - associationProjections.add(wrappers.wrap(projector.projectExcerpt(value), rel)); + associationProjections.add(wrappers.wrap(projector.projectExcerpt(it), rel)); } - } + }); }); return associationProjections; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/HttpHeadersPreparer.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/HttpHeadersPreparer.java index afbab75c0..f1c6d0ceb 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/HttpHeadersPreparer.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/HttpHeadersPreparer.java @@ -18,10 +18,15 @@ package org.springframework.data.rest.webmvc; import lombok.NonNull; import lombok.RequiredArgsConstructor; -import java.util.Calendar; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; +import org.springframework.core.convert.support.ConfigurableConversionService; +import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.auditing.AuditableBeanWrapper; import org.springframework.data.auditing.AuditableBeanWrapperFactory; +import org.springframework.data.convert.Jsr310Converters; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.rest.webmvc.support.ETag; import org.springframework.http.HttpHeaders; @@ -38,6 +43,11 @@ import org.springframework.util.Assert; public class HttpHeadersPreparer { private final @NonNull AuditableBeanWrapperFactory auditableBeanWrapperFactory; + private final ConfigurableConversionService conversionService = new DefaultConversionService(); + + { + Jsr310Converters.getConvertersToRegister().forEach(conversionService::addConverter); + } /** * Returns the default headers to be returned for the given {@link PersistentEntityResource}. Will set {@link ETag} @@ -46,8 +56,11 @@ public class HttpHeadersPreparer { * @param resource can be {@literal null}. * @return */ - public HttpHeaders prepareHeaders(PersistentEntityResource resource) { - return resource == null ? new HttpHeaders() : prepareHeaders(resource.getPersistentEntity(), resource.getContent()); + public HttpHeaders prepareHeaders(Optional resource) { + + return resource// + .map(it -> prepareHeaders(it.getPersistentEntity(), it.getContent()))// + .orElseGet(() -> new HttpHeaders()); } /** @@ -64,17 +77,7 @@ public class HttpHeadersPreparer { HttpHeaders headers = ETag.from(entity, value).addTo(new HttpHeaders()); // Add Last-Modified - AuditableBeanWrapper wrapper = getAuditableBeanWrapper(value); - - if (wrapper == null) { - return headers; - } - - Calendar lastModifiedDate = wrapper.getLastModifiedDate(); - - if (lastModifiedDate != null) { - headers.setLastModified(lastModifiedDate.getTimeInMillis()); - } + getLastModifiedInMilliseconds(value).ifPresent(it -> headers.setLastModified(it)); return headers; } @@ -95,10 +98,9 @@ public class HttpHeadersPreparer { return false; } - AuditableBeanWrapper wrapper = auditableBeanWrapperFactory.getBeanWrapperFor(source); - long current = wrapper.getLastModifiedDate().getTimeInMillis() / 1000 * 1000; - - return current <= headers.getIfModifiedSince(); + return getLastModifiedInMilliseconds(source)// + .map(it -> it / 1000 * 1000 <= headers.getIfModifiedSince())// + .orElse(true); } /** @@ -107,7 +109,16 @@ public class HttpHeadersPreparer { * @param source can be {@literal null}. * @return */ - private AuditableBeanWrapper getAuditableBeanWrapper(Object source) { + private Optional getAuditableBeanWrapper(Object source) { return auditableBeanWrapperFactory.getBeanWrapperFor(source); } + + private Optional getLastModifiedInMilliseconds(Object object) { + + return getAuditableBeanWrapper(object)// + .flatMap(it -> it.getLastModifiedDate())// + .map(it -> conversionService.convert(it, Date.class))// + .map(it -> conversionService.convert(it, Instant.class))// + .map(it -> it.toEpochMilli()); + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java index e4ee8474e..12fd2a8e7 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/PersistentEntityResourceAssembler.java @@ -69,7 +69,7 @@ public class PersistentEntityResourceAssembler implements ResourceAssembler entity = entities.getPersistentEntity(source.getClass()); + PersistentEntity entity = entities.getRequiredPersistentEntity(source.getClass()); return PersistentEntityResource.build(instance, entity).// withEmbedded(getEmbeddedResources(source)).// diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java index 982fca5ee..d821d2011 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryEntityController.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; @@ -44,7 +45,6 @@ import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.core.mapping.ResourceType; import org.springframework.data.rest.core.mapping.SearchResourceMappings; import org.springframework.data.rest.core.mapping.SupportedHttpMethods; -import org.springframework.data.rest.core.util.Supplier; import org.springframework.data.rest.webmvc.support.BackendId; import org.springframework.data.rest.webmvc.support.DefaultedPageable; import org.springframework.data.rest.webmvc.support.ETag; @@ -305,18 +305,16 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem public ResponseEntity headForItemResource(RootResourceInformation resourceInformation, @BackendId Serializable id, PersistentEntityResourceAssembler assembler) throws HttpRequestMethodNotSupportedException { - Object domainObject = getItemResource(resourceInformation, id); + return getItemResource(resourceInformation, id).map(it -> { - if (domainObject == null) { - throw new ResourceNotFoundException(); - } + Links links = new Links(assembler.toResource(it).getLinks()); - Links links = new Links(assembler.toResource(domainObject).getLinks()); + HttpHeaders headers = headersPreparer.prepareHeaders(resourceInformation.getPersistentEntity(), it); + headers.add(LINK_HEADER, links.toString()); - HttpHeaders headers = headersPreparer.prepareHeaders(resourceInformation.getPersistentEntity(), domainObject); - headers.add(LINK_HEADER, links.toString()); + return new ResponseEntity(headers, HttpStatus.NO_CONTENT); - return new ResponseEntity(headers, HttpStatus.NO_CONTENT); + }).orElseThrow(() -> new ResourceNotFoundException()); } /** @@ -332,21 +330,14 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem @BackendId Serializable id, final PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers) throws HttpRequestMethodNotSupportedException { - final Object domainObj = getItemResource(resourceInformation, id); + return getItemResource(resourceInformation, id).map(it -> { - if (domainObj == null) { - return new ResponseEntity>(HttpStatus.NOT_FOUND); - } + PersistentEntity entity = resourceInformation.getPersistentEntity(); - PersistentEntity entity = resourceInformation.getPersistentEntity(); + return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(// + () -> assembler.toFullResource(it)); - return resourceStatus.getStatusAndHeaders(headers, domainObj, entity).toResponseEntity(// - new Supplier() { - @Override - public PersistentEntityResource get() { - return assembler.toFullResource(domainObj); - } - }); + }).orElseGet(() -> new ResponseEntity>(HttpStatus.NOT_FOUND)); } /** @@ -425,21 +416,21 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem resourceInformation.verifySupportedMethod(HttpMethod.DELETE, ResourceType.ITEM); RepositoryInvoker invoker = resourceInformation.getInvoker(); - Object domainObj = invoker.invokeFindOne(id); + Optional domainObj = invoker.invokeFindOne(id); - if (domainObj == null) { - throw new ResourceNotFoundException(); - } + return domainObj.map(it -> { - PersistentEntity entity = resourceInformation.getPersistentEntity(); + PersistentEntity entity = resourceInformation.getPersistentEntity(); - eTag.verify(entity, domainObj); + eTag.verify(entity, it); - publisher.publishEvent(new BeforeDeleteEvent(domainObj)); - invoker.invokeDelete((Serializable) entity.getIdentifierAccessor(domainObj).getIdentifier()); - publisher.publishEvent(new AfterDeleteEvent(domainObj)); + publisher.publishEvent(new BeforeDeleteEvent(it)); + invoker.invokeDelete((Serializable) entity.getIdentifierAccessor(it).getIdentifier().orElse(null)); + publisher.publishEvent(new AfterDeleteEvent(it)); - return new ResponseEntity(HttpStatus.NO_CONTENT); + return new ResponseEntity(HttpStatus.NO_CONTENT); + + }).orElseThrow(() -> new ResourceNotFoundException()); } /** @@ -458,7 +449,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem publisher.publishEvent(new AfterSaveEvent(obj)); PersistentEntityResource resource = assembler.toFullResource(obj); - HttpHeaders headers = headersPreparer.prepareHeaders(resource); + HttpHeaders headers = headersPreparer.prepareHeaders(Optional.of(resource)); if (PUT.equals(httpMethod)) { addLocationHeader(headers, assembler, obj); @@ -485,7 +476,8 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem Object savedObject = invoker.invokeSave(domainObject); publisher.publishEvent(new AfterCreateEvent(savedObject)); - PersistentEntityResource resource = returnBody ? assembler.toFullResource(savedObject) : null; + Optional resource = Optional + .ofNullable(returnBody ? assembler.toFullResource(savedObject) : null); HttpHeaders headers = headersPreparer.prepareHeaders(resource); addLocationHeader(headers, assembler, savedObject); @@ -516,7 +508,7 @@ class RepositoryEntityController extends AbstractRepositoryRestController implem * @throws HttpRequestMethodNotSupportedException * @throws {@link ResourceNotFoundException} */ - private Object getItemResource(RootResourceInformation resourceInformation, Serializable id) + private Optional getItemResource(RootResourceInformation resourceInformation, Serializable id) throws HttpRequestMethodNotSupportedException, ResourceNotFoundException { resourceInformation.verifySupportedMethod(HttpMethod.GET, ResourceType.ITEM); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java index d5a879d29..55d84c0a0 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java @@ -20,6 +20,9 @@ import static org.springframework.data.rest.webmvc.RestMediaTypes.*; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*; import static org.springframework.web.bind.annotation.RequestMethod.*; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; + import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; @@ -30,6 +33,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.function.Function; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; @@ -49,7 +54,6 @@ import org.springframework.data.rest.core.event.BeforeLinkSaveEvent; import org.springframework.data.rest.core.mapping.PropertyAwareResourceMapping; import org.springframework.data.rest.core.mapping.ResourceMapping; import org.springframework.data.rest.core.mapping.ResourceMetadata; -import org.springframework.data.rest.core.util.Function; import org.springframework.data.rest.webmvc.support.BackendId; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.Link; @@ -62,7 +66,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -111,72 +115,55 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro final HttpHeaders headers = new HttpHeaders(); - Function handler = new Function() { + Function handler = prop -> prop.propertyValue.map(it -> { - @Override - public ResourceSupport apply(ReferencedProperty prop) { + if (prop.property.isCollectionLike()) { - if (null == prop.propertyValue) { - throw new ResourceNotFoundException(); + return toResources((Iterable) it, assembler, prop.propertyType, null); + + } else if (prop.property.isMap()) { + + Map> resources = new HashMap>(); + + for (Map.Entry entry : ((Map) it).entrySet()) { + resources.put(entry.getKey(), assembler.toResource(entry.getValue())); } - if (prop.property.isCollectionLike()) { + return new Resource(resources); - return toResources((Iterable) prop.propertyValue, assembler, prop.propertyType, null); + } else { - } else if (prop.property.isMap()) { - - Map> resources = new HashMap>(); - - for (Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { - resources.put(entry.getKey(), assembler.toResource(entry.getValue())); - } - - return new Resource(resources); - - } else { - - PersistentEntityResource resource = assembler.toResource(prop.propertyValue); - headers.set("Content-Location", resource.getId().getHref()); - return resource; - } + PersistentEntityResource resource = assembler.toResource(it); + headers.set("Content-Location", resource.getId().getHref()); + return resource; } - }; - ResourceSupport responseResource = doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET); - return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, responseResource); + }).orElseThrow(() -> new ResourceNotFoundException()); + + return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, // + doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET)); } @RequestMapping(value = BASE_MAPPING, method = DELETE) public ResponseEntity deletePropertyReference(final RootResourceInformation repoRequest, @BackendId Serializable id, @PathVariable String property) throws Exception { - final RepositoryInvoker repoMethodInvoker = repoRequest.getInvoker(); + Function handler = prop -> prop.propertyValue.map(it -> { - Function handler = new Function() { - - @Override - public Resource apply(ReferencedProperty prop) throws HttpRequestMethodNotSupportedException { - - if (null == prop.propertyValue) { - return null; - } - - if (prop.property.isCollectionLike()) { - throw new HttpRequestMethodNotSupportedException("DELETE"); - } else if (prop.property.isMap()) { - throw new HttpRequestMethodNotSupportedException("DELETE"); - } else { - prop.accessor.setProperty(prop.property, null); - } - - publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue)); - Object result = repoMethodInvoker.invokeSave(prop.accessor.getBean()); - publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue)); - - return null; + if (prop.property.isCollectionLike() || prop.property.isMap()) { + throw HttpRequestMethodNotSupportedException.forRejectedMethod(HttpMethod.DELETE) + .withAllowedMethods(HttpMethod.GET, HttpMethod.HEAD); + } else { + prop.wipeValue(); } - }; + + publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue)); + Object result = repoRequest.getInvoker().invokeSave(prop.accessor.getBean()); + publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue)); + + return (ResourceSupport) null; + + }).orElse(null); doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.DELETE); @@ -190,53 +177,51 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro final HttpHeaders headers = new HttpHeaders(); - Function handler = new Function() { + Function handler = prop -> prop.propertyValue.map(it -> { - @Override - public ResourceSupport apply(ReferencedProperty prop) { + if (prop.property.isCollectionLike()) { - if (null == prop.propertyValue) { - throw new ResourceNotFoundException(); - } - if (prop.property.isCollectionLike()) { - for (Object obj : (Iterable) prop.propertyValue) { + for (Object obj : (Iterable) it) { - IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(obj); - if (propertyId.equals(accessor.getIdentifier().toString())) { + IdentifierAccessor accessor1 = prop.entity.getIdentifierAccessor(obj); + if (propertyId.equals(accessor1.getIdentifier().toString())) { - PersistentEntityResource resource = assembler.toResource(obj); - headers.set("Content-Location", resource.getId().getHref()); - return resource; - } + PersistentEntityResource resource1 = assembler.toResource(obj); + headers.set("Content-Location", resource1.getId().getHref()); + return resource1; } - } else if (prop.property.isMap()) { - for (Map.Entry entry : ((Map) prop.propertyValue).entrySet()) { - - IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(entry.getValue()); - if (propertyId.equals(accessor.getIdentifier().toString())) { - - PersistentEntityResource resource = assembler.toResource(entry.getValue()); - headers.set("Content-Location", resource.getId().getHref()); - return resource; - } - } - } else { - return new Resource(prop.propertyValue); } - throw new ResourceNotFoundException(); + } else if (prop.property.isMap()) { + + for (Map.Entry entry : ((Map) it).entrySet()) { + + IdentifierAccessor accessor2 = prop.entity.getIdentifierAccessor(entry.getValue()); + if (propertyId.equals(accessor2.getIdentifier().toString())) { + + PersistentEntityResource resource2 = assembler.toResource(entry.getValue()); + headers.set("Content-Location", resource2.getId().getHref()); + return resource2; + } + } + + } else { + return new Resource(prop.propertyValue); } - }; - ResourceSupport responseResource = doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET); - return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, responseResource); + throw new ResourceNotFoundException(); + + }).orElseThrow(() -> new ResourceNotFoundException()); + + return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, // + doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET)); } @RequestMapping(value = BASE_MAPPING, method = GET, produces = { SPRING_DATA_COMPACT_JSON_VALUE, TEXT_URI_LIST_VALUE }) public ResponseEntity followPropertyReferenceCompact(RootResourceInformation repoRequest, @BackendId Serializable id, @PathVariable String property, PersistentEntityResourceAssembler assembler) - throws Exception { + throws Exception { ResponseEntity response = followPropertyReference(repoRequest, id, property, assembler); @@ -245,7 +230,7 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro } ResourceMetadata repoMapping = repoRequest.getResourceMetadata(); - PersistentProperty persistentProp = repoRequest.getPersistentEntity().getPersistentProperty(property); + PersistentProperty persistentProp = repoRequest.getPersistentEntity().getRequiredPersistentProperty(property); ResourceMapping propertyMapping = repoMapping.getMappingFor(persistentProp); ResourceSupport resource = response.getBody(); @@ -291,60 +276,59 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro final Resources source = incoming == null ? new Resources(Collections.emptyList()) : incoming; final RepositoryInvoker invoker = resourceInformation.getInvoker(); - Function handler = new Function() { + Function handler = prop -> { - @Override - public ResourceSupport apply(ReferencedProperty prop) throws HttpRequestMethodNotSupportedException { + Class propertyType = prop.property.getType(); - Class propertyType = prop.property.getType(); + if (prop.property.isCollectionLike()) { - if (prop.property.isCollectionLike()) { + Collection collection = AUGMENTING_METHODS.contains(requestMethod) + ? (Collection) prop.propertyValue.orElse(null) + : CollectionFactory.createCollection(propertyType, 0); - Collection collection = AUGMENTING_METHODS.contains(requestMethod) - ? (Collection) prop.propertyValue : CollectionFactory.createCollection(propertyType, 0); - - // Add to the existing collection - for (Link l : source.getLinks()) { - collection.add(loadPropertyValue(prop.propertyType, l)); - } - - prop.accessor.setProperty(prop.property, collection); - - } else if (prop.property.isMap()) { - - Map map = AUGMENTING_METHODS.contains(requestMethod) - ? (Map) prop.propertyValue - : CollectionFactory. createMap(propertyType, 0); - - // Add to the existing collection - for (Link l : source.getLinks()) { - map.put(l.getRel(), loadPropertyValue(prop.propertyType, l)); - } - - prop.accessor.setProperty(prop.property, map); - - } else { - - if (HttpMethod.PATCH.equals(requestMethod)) { - throw new HttpRequestMethodNotSupportedException(HttpMethod.PATCH.name(), new String[] { "PATCH" }, - "Cannot PATCH a reference to this singular property since the property type is not a List or a Map."); - } - - if (source.getLinks().size() != 1) { - throw new IllegalArgumentException( - "Must send only 1 link to update a property reference that isn't a List or a Map."); - } - - Object propVal = loadPropertyValue(prop.propertyType, source.getLinks().get(0)); - prop.accessor.setProperty(prop.property, propVal); + // Add to the existing collection + for (Link l1 : source.getLinks()) { + collection.add(loadPropertyValue(prop.propertyType, l1).orElse(null)); } - publisher.publishEvent(new BeforeLinkSaveEvent(prop.accessor.getBean(), prop.propertyValue)); - Object result = invoker.invokeSave(prop.accessor.getBean()); - publisher.publishEvent(new AfterLinkSaveEvent(result, prop.propertyValue)); + prop.accessor.setProperty(prop.property, Optional.of(collection)); - return null; + } else if (prop.property.isMap()) { + + Map map = AUGMENTING_METHODS.contains(requestMethod) + ? (Map) prop.propertyValue.orElse(null) + : CollectionFactory. createMap(propertyType, 0); + + // Add to the existing collection + for (Link l2 : source.getLinks()) { + map.put(l2.getRel(), loadPropertyValue(prop.propertyType, l2).orElse(null)); + } + + prop.accessor.setProperty(prop.property, Optional.of(map)); + + } else { + + if (HttpMethod.PATCH.equals(requestMethod)) { + throw HttpRequestMethodNotSupportedException.forRejectedMethod(HttpMethod.PATCH)// + .withAllowedMethods(HttpMethod.PATCH)// + .withMessage( + "Cannot PATCH a reference to this singular property since the property type is not a List or a Map."); + } + + if (source.getLinks().size() != 1) { + throw new IllegalArgumentException( + "Must send only 1 link to update a property reference that isn't a List or a Map."); + } + + Optional propVal = loadPropertyValue(prop.propertyType, source.getLinks().get(0)); + prop.accessor.setProperty(prop.property, propVal); } + + publisher.publishEvent(new BeforeLinkSaveEvent(prop.accessor.getBean(), prop.propertyValue)); + Object result = invoker.invokeSave(prop.accessor.getBean()); + publisher.publishEvent(new AfterLinkSaveEvent(result, prop.propertyValue)); + + return null; }; doWithReferencedProperty(resourceInformation, id, property, handler, requestMethod); @@ -354,68 +338,59 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro @RequestMapping(value = BASE_MAPPING + "/{propertyId}", method = DELETE) public ResponseEntity deletePropertyReferenceId(final RootResourceInformation repoRequest, - @BackendId Serializable id, @PathVariable String property, final @PathVariable String propertyId) - throws Exception { + @BackendId Serializable backendId, @PathVariable String property, final @PathVariable String propertyId) + throws Exception { - final RepositoryInvoker invoker = repoRequest.getInvoker(); + Function handler = prop -> prop.propertyValue.map(it -> { - Function handler = new Function() { + if (prop.property.isCollectionLike()) { - @Override - public ResourceSupport apply(ReferencedProperty prop) { + Collection coll = (Collection) it; + Iterator iterator = coll.iterator(); - if (null == prop.propertyValue) { - return null; + while (iterator.hasNext()) { + + Object obj = iterator.next(); + + prop.entity.getIdentifierAccessor(obj).getIdentifier()// + .map(Object::toString)// + .filter(id -> propertyId.equals(id))// + .ifPresent(__ -> iterator.remove()); } - if (prop.property.isCollectionLike()) { - Collection coll = (Collection) prop.propertyValue; - Iterator itr = coll.iterator(); - while (itr.hasNext()) { - Object obj = itr.next(); + } else if (prop.property.isMap()) { - IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(obj); - String s = accessor.getIdentifier().toString(); + Map m = (Map) it; + Iterator> iterator = m.entrySet().iterator(); - if (propertyId.equals(s)) { - itr.remove(); - } - } - } else if (prop.property.isMap()) { + while (iterator.hasNext()) { - Map m = (Map) prop.propertyValue; - Iterator> itr = m.entrySet().iterator(); + Object key = iterator.next().getKey(); - while (itr.hasNext()) { - - Object key = itr.next().getKey(); - - IdentifierAccessor accessor = prop.entity.getIdentifierAccessor(m.get(key)); - String s = accessor.getIdentifier().toString(); - - if (propertyId.equals(s)) { - itr.remove(); - } - } - - } else { - prop.accessor.setProperty(prop.property, null); + prop.entity.getIdentifierAccessor(m.get(key)).getIdentifier()// + .map(Object::toString)// + .filter(id -> propertyId.equals(id))// + .ifPresent(__ -> iterator.remove()); } - publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), prop.propertyValue)); - Object result = invoker.invokeSave(prop.accessor.getBean()); - publisher.publishEvent(new AfterLinkDeleteEvent(result, prop.propertyValue)); - - return null; + } else { + prop.wipeValue(); } - }; - doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.DELETE); + publisher.publishEvent(new BeforeLinkDeleteEvent(prop.accessor.getBean(), it)); + Object result = repoRequest.getInvoker().invokeSave(prop.accessor.getBean()); + publisher.publishEvent(new AfterLinkDeleteEvent(result, it)); + + return (ResourceSupport) null; + + }).orElse(null); + + doWithReferencedProperty(repoRequest, backendId, property, handler, HttpMethod.DELETE); return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT); } - private Object loadPropertyValue(Class type, Link link) { + private Optional loadPropertyValue(Class type, Link link) { String href = link.expand().getHref(); String id = href.substring(href.lastIndexOf('/') + 1); @@ -425,8 +400,9 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro return invoker.invokeFindOne(id); } - private ResourceSupport doWithReferencedProperty(RootResourceInformation resourceInformation, Serializable id, - String propertyPath, Function handler, HttpMethod method) throws Exception { + private Optional doWithReferencedProperty(RootResourceInformation resourceInformation, + Serializable id, String propertyPath, Function handler, HttpMethod method) + throws Exception { ResourceMetadata metadata = resourceInformation.getResourceMetadata(); PropertyAwareResourceMapping mapping = metadata.getProperty(propertyPath); @@ -439,14 +415,15 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro resourceInformation.verifySupportedMethod(method, property); RepositoryInvoker invoker = resourceInformation.getInvoker(); - Object domainObj = invoker.invokeFindOne(id); + Optional domainObj = invoker.invokeFindOne(id); - if (null == domainObj) { - throw new ResourceNotFoundException(); - } + domainObj.orElseThrow(() -> new ResourceNotFoundException()); - PersistentPropertyAccessor accessor = property.getOwner().getPropertyAccessor(domainObj); - return handler.apply(new ReferencedProperty(property, accessor.getProperty(property), accessor)); + return domainObj.map(it -> { + + PersistentPropertyAccessor accessor = property.getOwner().getPropertyAccessor(it); + return handler.apply(new ReferencedProperty(property, accessor.getProperty(property), accessor)); + }); } private class ReferencedProperty { @@ -454,10 +431,10 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro final PersistentEntity entity; final PersistentProperty property; final Class propertyType; - final Object propertyValue; + final Optional propertyValue; final PersistentPropertyAccessor accessor; - private ReferencedProperty(PersistentProperty property, Object propertyValue, + private ReferencedProperty(PersistentProperty property, Optional propertyValue, PersistentPropertyAccessor wrapper) { this.property = property; @@ -466,5 +443,54 @@ class RepositoryPropertyReferenceController extends AbstractRepositoryRestContro this.propertyType = property.getActualType(); this.entity = repositories.getPersistentEntity(propertyType); } + + public void writeValue() { + accessor.setProperty(property, propertyValue); + } + + public void wipeValue() { + accessor.setProperty(property, Optional.empty()); + } + } + + @ExceptionHandler + public ResponseEntity handle(HttpRequestMethodNotSupportedException exception) { + return exception.toResponse(); + } + + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + static class HttpRequestMethodNotSupportedException extends RuntimeException { + + private static final long serialVersionUID = 3704212056962845475L; + + private final HttpMethod rejectedMethod; + private final HttpMethod[] allowedMethods; + private final String message; + + public static HttpRequestMethodNotSupportedException forRejectedMethod(HttpMethod method) { + return new HttpRequestMethodNotSupportedException(method, new HttpMethod[0], null); + } + + public HttpRequestMethodNotSupportedException withAllowedMethods(HttpMethod... methods) { + return new HttpRequestMethodNotSupportedException(this.rejectedMethod, methods.clone(), null); + } + + public HttpRequestMethodNotSupportedException withMessage(String message, Object... parameters) { + return new HttpRequestMethodNotSupportedException(this.rejectedMethod, this.allowedMethods, + String.format(message, parameters)); + } + + /* + * (non-Javadoc) + * @see java.lang.Throwable#getMessage() + */ + @Override + public String getMessage() { + return message; + } + + public ResponseEntity toResponse() { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).allow(allowedMethods).build(); + } } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java index 87d1fce7d..cd831fabf 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import javax.servlet.ServletException; @@ -63,7 +64,7 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping { private final ResourceMappings mappings; private final RepositoryRestConfiguration configuration; - private final Repositories repositories; + private final Optional repositories; private RepositoryCorsConfigurationAccessor corsConfigurationAccessor; private JpaHelper jpaHelper; @@ -76,7 +77,7 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping { * @param config must not be {@literal null}. */ public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config) { - this(mappings, config, null); + this(mappings, config, Optional.empty()); } /** @@ -85,15 +86,22 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping { * * @param mappings must not be {@literal null}. * @param config must not be {@literal null}. - * @param repositories can be {@literal null} if {@link CrossOrigin} resolution is not required. + * @param repositories must not be {@literal null}. */ public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config, Repositories repositories) { + this(mappings, config, Optional.of(repositories)); + } + + private RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config, + Optional repositories) { + super(config); Assert.notNull(mappings, "ResourceMappings must not be null!"); Assert.notNull(config, "RepositoryRestConfiguration must not be null!"); + Assert.notNull(repositories, "Repositories must not be null!"); this.mappings = mappings; this.configuration = config; @@ -201,19 +209,14 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping { @Override protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { - CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request); String lookupPath = getUrlPathHelper().getLookupPathForRequest(request); - String repositoryLookupPath = new BaseUri(configuration.getBaseUri()).getRepositoryLookupPath(lookupPath); + CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request); - if (!StringUtils.hasText(repositoryLookupPath) || repositories == null) { - return corsConfiguration; - } - - CorsConfiguration repositoryCorsConfiguration = corsConfigurationAccessor.findCorsConfiguration(lookupPath); - - return corsConfiguration == null ? repositoryCorsConfiguration - : corsConfiguration.combine(repositoryCorsConfiguration); + return repositories.filter(it -> StringUtils.hasText(repositoryLookupPath))// + .flatMap(it -> corsConfigurationAccessor.findCorsConfiguration(lookupPath)) + .map(it -> it.combine(corsConfiguration))// + .orElse(corsConfiguration); } /** @@ -262,28 +265,25 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping { private final @NonNull ResourceMappings mappings; private final @NonNull StringValueResolver embeddedValueResolver; - private final Repositories repositories; + private final @NonNull Optional repositories; - CorsConfiguration findCorsConfiguration(String lookupPath) { + Optional findCorsConfiguration(String lookupPath) { - ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath)); - - return resource != null && repositories != null ? createConfiguration( - repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()) : null; + return getResourceMetadata(getRepositoryBasePath(lookupPath))// + .flatMap(it -> repositories.flatMap(foo -> foo.getRepositoryInformationFor(it.getDomainType())))// + .map(it -> it.getRepositoryInterface())// + .map(it -> createConfiguration(it)); } - private ResourceMetadata getResourceMetadata(String basePath) { + private Optional getResourceMetadata(String basePath) { - if (mappings.exportsTopLevelResourceFor(basePath)) { - - for (ResourceMetadata metadata : mappings) { - if (metadata.getPath().matches(basePath) && metadata.isExported()) { - return metadata; - } - } + if (!mappings.exportsTopLevelResourceFor(basePath)) { + return Optional.empty(); } - return null; + return mappings.stream()// + .filter(it -> it.getPath().matches(basePath) && it.isExported())// + .findFirst(); } /** diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java index ee5a41963..339b72e90 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; +import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; @@ -35,7 +36,6 @@ import org.springframework.data.rest.core.mapping.MethodResourceMapping; import org.springframework.data.rest.core.mapping.ResourceMappings; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.core.mapping.SearchResourceMappings; -import org.springframework.data.rest.core.util.Supplier; import org.springframework.data.rest.webmvc.support.DefaultedPageable; import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks; import org.springframework.data.util.ClassTypeInformation; @@ -180,7 +180,8 @@ class RepositorySearchController extends AbstractRepositoryRestController { Sort sort, PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers) { Method method = checkExecutability(resourceInformation, search); - Object result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, assembler); + Optional result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, + assembler); SearchResourceMappings searchMappings = resourceInformation.getSearchMappings(); MethodResourceMapping methodMapping = searchMappings.getExportedMethodMappingForPath(search); @@ -199,27 +200,23 @@ class RepositorySearchController extends AbstractRepositoryRestController { * @param baseLink can be {@literal null}. * @return */ - protected ResponseEntity toResource(final Object source, final PersistentEntityResourceAssembler assembler, + protected ResponseEntity toResource(Optional source, final PersistentEntityResourceAssembler assembler, Class domainType, Link baseLink, HttpHeaders headers, RootResourceInformation information) { - if (source instanceof Iterable) { - return ResponseEntity.ok(toResources((Iterable) source, assembler, domainType, baseLink)); - } else if (source == null) { - throw new ResourceNotFoundException(); - } else if (ClassUtils.isPrimitiveOrWrapper(source.getClass())) { - return ResponseEntity.ok(source); - } + return source.map(it -> { - PersistentEntity entity = information.getPersistentEntity(); + if (it instanceof Iterable) { + return ResponseEntity.ok(toResources((Iterable) it, assembler, domainType, baseLink)); + } else if (ClassUtils.isPrimitiveOrWrapper(it.getClass())) { + return ResponseEntity.ok(it); + } - return resourceStatus.getStatusAndHeaders(headers, source, entity).toResponseEntity(// - new Supplier() { + PersistentEntity entity = information.getPersistentEntity(); - @Override - public PersistentEntityResource get() { - return assembler.toFullResource(source); - } - }); + return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(// + () -> assembler.toFullResource(it)); + + }).orElseThrow(() -> new ResourceNotFoundException()); } /** @@ -243,7 +240,8 @@ class RepositorySearchController extends AbstractRepositoryRestController { PersistentEntityResourceAssembler assembler) { Method method = checkExecutability(resourceInformation, search); - Object result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, assembler); + Optional result = executeQueryMethod(resourceInformation.getInvoker(), parameters, method, pageable, sort, + assembler); ResourceMetadata metadata = resourceInformation.getResourceMetadata(); ResponseEntity entity = toResource(result, assembler, metadata.getDomainType(), null, headers, resourceInformation); @@ -331,7 +329,7 @@ class RepositorySearchController extends AbstractRepositoryRestController { * @param pageable * @return */ - private Object executeQueryMethod(final RepositoryInvoker invoker, + private Optional executeQueryMethod(final RepositoryInvoker invoker, @RequestParam MultiValueMap parameters, Method method, DefaultedPageable pageable, Sort sort, PersistentEntityResourceAssembler assembler) { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceStatus.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceStatus.java index ca1c05a23..59775d0cb 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceStatus.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/ResourceStatus.java @@ -21,9 +21,9 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import java.util.List; +import java.util.function.Supplier; import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.rest.core.util.Supplier; import org.springframework.data.rest.webmvc.support.ETag; import org.springframework.hateoas.Resource; import org.springframework.http.HttpHeaders; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/alps/RootResourceInformationToAlpsDescriptorConverter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/alps/RootResourceInformationToAlpsDescriptorConverter.java index 9a29419ba..38fdead70 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/alps/RootResourceInformationToAlpsDescriptorConverter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/alps/RootResourceInformationToAlpsDescriptorConverter.java @@ -256,7 +256,7 @@ public class RootResourceInformationToAlpsDescriptorConverter { */ private List getPaginationDescriptors(Class type, HttpMethod method) { - RepositoryInformation information = repositories.getRepositoryInformationFor(type); + RepositoryInformation information = repositories.getRequiredRepositoryInformation(type); if (!information.isPagingRepository() || !getType(method).equals(Type.SAFE)) { return Collections.emptyList(); @@ -290,7 +290,7 @@ public class RootResourceInformationToAlpsDescriptorConverter { private List buildPropertyDescriptors(final Class type, String baseRel) { - final PersistentEntity entity = persistentEntities.getPersistentEntity(type); + final PersistentEntity entity = persistentEntities.getRequiredPersistentEntity(type); final List propertyDescriptors = new ArrayList(); final JacksonMetadata jackson = new JacksonMetadata(mapper, type); final ResourceMetadata metadata = associations.getMetadataFor(entity.getType()); @@ -311,10 +311,10 @@ public class RootResourceInformationToAlpsDescriptorConverter { propertyDescriptors.add(// descriptor(). // - type(Type.SEMANTIC).// - name(propertyDefinition.getName()).// - doc(getDocFor(propertyMapping.getDescription(), property)).// - build()); + type(Type.SEMANTIC).// + name(propertyDefinition.getName()).// + doc(getDocFor(propertyMapping.getDescription(), property)).// + build()); } } }); @@ -333,7 +333,7 @@ public class RootResourceInformationToAlpsDescriptorConverter { ResourceMapping mapping = metadata.getMappingFor(property); DescriptorBuilder builder = descriptor().// - name(mapping.getRel()).doc(getDocFor(mapping.getDescription())); + name(mapping.getRel()).doc(getDocFor(mapping.getDescription())); ResourceMetadata targetTypeMetadata = associations.getMetadataFor(property.getActualType()); @@ -343,8 +343,8 @@ public class RootResourceInformationToAlpsDescriptorConverter { Link link = new Link(href).withSelfRel(); builder.// - type(Type.SAFE).// - rt(link.getHref()); + type(Type.SAFE).// + rt(link.getHref()); propertyDescriptors.add(builder.build()); } @@ -386,6 +386,7 @@ public class RootResourceInformationToAlpsDescriptorConverter { return getDocFor(description, null); } + @SuppressWarnings("unchecked") private Doc getDocFor(ResourceDescription description, PersistentProperty property) { if (description == null) { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/PersistentEntityResourceHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/PersistentEntityResourceHandlerMethodArgumentResolver.java index 95cb95779..1535506dc 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/PersistentEntityResourceHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/PersistentEntityResourceHandlerMethodArgumentResolver.java @@ -18,12 +18,12 @@ package org.springframework.data.rest.webmvc.config; import java.io.IOException; import java.io.Serializable; import java.util.List; +import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.springframework.core.MethodParameter; import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.repository.support.RepositoryInvoker; import org.springframework.data.rest.webmvc.IncomingRequest; import org.springframework.data.rest.webmvc.PersistentEntityResource; import org.springframework.data.rest.webmvc.PersistentEntityResource.Builder; @@ -124,16 +124,7 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha } Serializable id = idResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); - Object objectToUpdate = getObjectToUpdate(id, resourceInformation); - - boolean forUpdate = false; - Object entityIdentifier = null; - PersistentEntity entity = resourceInformation.getPersistentEntity(); - - if (objectToUpdate != null) { - forUpdate = true; - entityIdentifier = entity.getIdentifierAccessor(objectToUpdate).getIdentifier(); - } + Optional objectToUpdate = getObjectToUpdate(id, resourceInformation); Object obj = read(resourceInformation, incoming, converter, objectToUpdate); @@ -141,8 +132,13 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, domainType)); } - if (entityIdentifier != null) { - entity.getPropertyAccessor(obj).setProperty(entity.getIdProperty(), entityIdentifier); + PersistentEntity entity = resourceInformation.getPersistentEntity(); + boolean forUpdate = objectToUpdate.isPresent(); + Optional entityIdentifier = objectToUpdate + .flatMap(it -> entity.getIdentifierAccessor(it).getIdentifier()); + + if (entityIdentifier.isPresent()) { + entity.getPropertyAccessor(obj).setProperty(entity.getRequiredIdProperty(), entityIdentifier); } Builder build = PersistentEntityResource.build(obj, entity); @@ -163,27 +159,25 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha * @return */ private Object read(RootResourceInformation information, IncomingRequest request, - HttpMessageConverter converter, Object objectToUpdate) { + HttpMessageConverter converter, Optional objectToUpdate) { // JSON + PATCH request if (request.isPatchRequest() && converter instanceof MappingJackson2HttpMessageConverter) { - if (objectToUpdate == null) { - throw new ResourceNotFoundException(); - } + return objectToUpdate.map(it -> { - ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper(); - Object result = readPatch(request, mapper, objectToUpdate); + ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper(); + return readPatch(request, mapper, it); - return result; + }).orElseThrow(() -> new ResourceNotFoundException()); // JSON + PUT request } else if (converter instanceof MappingJackson2HttpMessageConverter) { ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper(); - return objectToUpdate == null ? read(request, converter, information) - : readPutForUpdate(request, mapper, objectToUpdate); + return objectToUpdate.map(it -> readPutForUpdate(request, mapper, it))// + .orElseGet(() -> read(request, converter, information)); } // Catch all @@ -238,13 +232,12 @@ public class PersistentEntityResourceHandlerMethodArgumentResolver implements Ha * @param information must not be {@literal null}. * @return */ - private static Object getObjectToUpdate(Serializable id, RootResourceInformation information) { + private static Optional getObjectToUpdate(Serializable id, RootResourceInformation information) { if (id == null) { - return null; + return Optional.empty(); } - RepositoryInvoker invoker = information.getInvoker(); - return invoker.invokeFindOne(id); + return information.getInvoker().invokeFindOne(id); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.java index 366d3134b..309d7e739 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import java.util.Map; import java.util.Map.Entry; import org.springframework.core.MethodParameter; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.QuerydslRepositoryInvokerAdapter; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.querydsl.binding.QuerydslBindingsFactory; @@ -76,22 +76,26 @@ class QuerydslAwareRootResourceInformationHandlerMethodArgumentResolver */ @Override @SuppressWarnings({ "unchecked" }) - protected RepositoryInvoker postProcess(MethodParameter parameter, RepositoryInvoker invoker, - Class domainType, Map parameters) { + protected RepositoryInvoker postProcess(MethodParameter parameter, RepositoryInvoker invoker, Class domainType, + Map parameters) { - Object repository = repositories.getRepositoryFor(domainType); - - if (!QueryDslPredicateExecutor.class.isInstance(repository) - || !parameter.hasParameterAnnotation(QuerydslPredicate.class)) { + if (!parameter.hasParameterAnnotation(QuerydslPredicate.class)) { return invoker; } - ClassTypeInformation type = ClassTypeInformation.from(domainType); + return repositories.getRepositoryFor(domainType)// + .filter(it -> QuerydslPredicateExecutor.class.isInstance(it))// + .map(it -> { - QuerydslBindings bindings = factory.createBindingsFor(null, type); - Predicate predicate = predicateBuilder.getPredicate(type, toMultiValueMap(parameters), bindings); + ClassTypeInformation type = ClassTypeInformation.from(domainType); - return new QuerydslRepositoryInvokerAdapter(invoker, (QueryDslPredicateExecutor) repository, predicate); + QuerydslBindings bindings = factory.createBindingsFor(type); + Predicate predicate = predicateBuilder.getPredicate(type, toMultiValueMap(parameters), bindings); + + return (RepositoryInvoker) new QuerydslRepositoryInvokerAdapter(invoker, + (QuerydslPredicateExecutor) it, predicate); + + }).orElse(invoker); } /** diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java index 7a2e3698c..f2327e9c0 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.java @@ -50,7 +50,7 @@ import org.springframework.data.geo.GeoModule; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; -import org.springframework.data.querydsl.QueryDslUtils; +import org.springframework.data.querydsl.QuerydslUtils; import org.springframework.data.querydsl.binding.QuerydslBindingsFactory; import org.springframework.data.querydsl.binding.QuerydslPredicateBuilder; import org.springframework.data.repository.support.DefaultRepositoryInvokerFactory; @@ -72,6 +72,7 @@ import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.RepositoryRelProvider; import org.springframework.data.rest.core.support.SelfLinkProvider; import org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.BasePathAwareController; import org.springframework.data.rest.webmvc.BasePathAwareHandlerMapping; import org.springframework.data.rest.webmvc.BaseUri; @@ -154,6 +155,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; /** * Main application configuration for Spring Data REST. To customize how the exporter works, subclass this and override @@ -189,6 +191,11 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon private RepositoryRestConfigurerDelegate configurerDelegate; + public RepositoryRestMvcConfiguration(ApplicationContext context, + @Qualifier("mvcConversionService") ObjectFactory conversionService) { + super(context, conversionService); + } + /* * (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() @@ -335,7 +342,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon @Bean public RootResourceInformationHandlerMethodArgumentResolver repoRequestArgumentResolver() { - if (QueryDslUtils.QUERY_DSL_PRESENT) { + if (QuerydslUtils.QUERY_DSL_PRESENT) { QuerydslBindingsFactory factory = applicationContext.getBean(QuerydslBindingsFactory.class); QuerydslPredicateBuilder predicateBuilder = new QuerydslPredicateBuilder(defaultConversionService(), @@ -357,7 +364,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon @Bean public BackendIdHandlerMethodArgumentResolver backendIdHandlerMethodArgumentResolver() { - return new BackendIdHandlerMethodArgumentResolver(backendIdConverterRegistry(), + return new BackendIdHandlerMethodArgumentResolver(Java8PluginRegistry.of(backendIdConverterRegistry()), resourceMetadataHandlerMethodArgumentResolver(), baseUri()); } @@ -380,7 +387,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon pageableResolver(), sortResolver()); return new RepositoryEntityLinks(repositories(), resourceMappings(), config(), templateVariables, - backendIdConverterRegistry()); + Java8PluginRegistry.of(backendIdConverterRegistry())); } /** @@ -443,8 +450,12 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon @Bean public ObjectMapper objectMapper() { + Jdk8Module jdk8Module = new Jdk8Module(); + jdk8Module.configureAbsentsAsNulls(true); + ObjectMapper mapper = basicObjectMapper(); mapper.registerModule(persistentEntityJackson2Module()); + mapper.registerModule(jdk8Module); return mapper; } @@ -635,7 +646,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon EmbeddedResourcesAssembler assembler = new EmbeddedResourcesAssembler(entities, associationLinks(), excerptProjector()); LookupObjectSerializer lookupObjectSerializer = new LookupObjectSerializer( - OrderAwarePluginRegistry.create(getEntityLookups())); + Java8PluginRegistry.of(getEntityLookups())); return new PersistentEntityJackson2Module(associationLinks(), entities, uriToEntityConverter, linkCollector(), repositoryInvokerFactory, lookupObjectSerializer, resourceProcessorInvoker(), assembler); @@ -655,7 +666,6 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon SpelAwareProxyProjectionFactory projectionFactory = new SpelAwareProxyProjectionFactory(); projectionFactory.setBeanFactory(applicationContext); - projectionFactory.setResourceLoader(applicationContext); return new DefaultExcerptProjector(projectionFactory, resourceMappings()); } @@ -732,7 +742,7 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver(); resolver.setPageParameterName(config().getPageParamName()); resolver.setSizeParameterName(config().getLimitParamName()); - resolver.setFallbackPageable(new PageRequest(0, config().getDefaultPageSize())); + resolver.setFallbackPageable(PageRequest.of(0, config().getDefaultPageSize())); resolver.setMaxPageSize(config().getMaxPageSize()); return resolver; diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/DomainObjectReader.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/DomainObjectReader.java index b25d1b97b..bca937e1b 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/DomainObjectReader.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/DomainObjectReader.java @@ -27,6 +27,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; @@ -107,9 +108,7 @@ public class DomainObjectReader { Class type = target.getClass(); - final PersistentEntity entity = entities.getPersistentEntity(type); - - Assert.notNull(entity, "No PersistentEntity found for ".concat(type.getName()).concat("!")); + entities.getRequiredPersistentEntity(type); try { @@ -139,24 +138,20 @@ public class DomainObjectReader { Class type = target.getClass(); - PersistentEntity entity = entities.getPersistentEntity(type); + return entities.getPersistentEntity(type).map(it -> { - if (entity == null) { - return source; - } + MergingPropertyHandler propertyHandler = new MergingPropertyHandler(source, target, it, mapper); - Assert.notNull(entity, "No PersistentEntity found for ".concat(type.getName()).concat("!")); + it.doWithProperties(propertyHandler); + it.doWithAssociations(new LinkedAssociationSkippingAssociationHandler(associationLinks, propertyHandler)); - MergingPropertyHandler propertyHandler = new MergingPropertyHandler(source, target, entity, mapper); + // Need to copy unmapped properties as the PersistentProperty model currently does not contain any transient + // properties + copyRemainingProperties(propertyHandler.getProperties(), source, target); - entity.doWithProperties(propertyHandler); - entity.doWithAssociations(new LinkedAssociationSkippingAssociationHandler(associationLinks, propertyHandler)); + return target; - // Need to copy unmapped properties as the PersistentProperty model currently does not contain any transient - // properties - copyRemainingProperties(propertyHandler.getProperties(), source, target); - - return target; + }).orElse(source); } /** @@ -213,12 +208,14 @@ public class DomainObjectReader { Assert.notNull(target, "Target object instance must not be null!"); Assert.notNull(mapper, "ObjectMapper must not be null!"); - PersistentEntity entity = entities.getPersistentEntity(target.getClass()); + Optional>> candidate = entities + .getPersistentEntity(target.getClass()); - if (entity == null) { + if (!candidate.isPresent()) { return mapper.readerForUpdating(target).readValue(root); } + PersistentEntity entity = candidate.get(); MappedProperties mappedProperties = MappedProperties.fromJacksonProperties(entity, mapper); for (Iterator> i = root.fields(); i.hasNext();) { @@ -233,51 +230,57 @@ public class DomainObjectReader { PersistentProperty property = mappedProperties.getPersistentProperty(fieldName); PersistentPropertyAccessor accessor = entity.getPropertyAccessor(target); - Object rawValue = accessor.getProperty(property); + Optional rawValue = accessor.getProperty(property); - if (rawValue == null) { + if (!rawValue.isPresent()) { continue; } - if (child.isArray()) { + rawValue.ifPresent(it -> { - if (handleArray(child, rawValue, mapper, property.getTypeInformation())) { - i.remove(); - } + if (child.isArray()) { - continue; - } - - if (child.isObject()) { - - if (associationLinks.isLinkableAssociation(property)) { - continue; - } - - ObjectNode objectNode = (ObjectNode) child; - - if (property.isMap()) { - - // Keep empty Map to wipe it as expected - if (!objectNode.fieldNames().hasNext()) { - continue; - } - - doMergeNestedMap((Map) rawValue, objectNode, mapper, property.getTypeInformation()); - - // Remove potentially emptied Map as values have been handled recursively - if (!objectNode.fieldNames().hasNext()) { + if (handleArray(child, it, mapper, property.getTypeInformation())) { i.remove(); } - continue; + return; } - if (property.isEntity()) { - i.remove(); - doMerge(objectNode, rawValue, mapper); + if (child.isObject()) { + + if (associationLinks.isLinkableAssociation(property)) { + return; + } + + ObjectNode objectNode = (ObjectNode) child; + + if (property.isMap()) { + + // Keep empty Map to wipe it as expected + if (!objectNode.fieldNames().hasNext()) { + return; + } + + execute( + () -> doMergeNestedMap((Map) it, objectNode, mapper, property.getTypeInformation())); + + // Remove potentially emptied Map as values have been handled recursively + if (!objectNode.fieldNames().hasNext()) { + i.remove(); + } + + return; + } + + if (property.isEntity()) { + i.remove(); + execute(() -> doMerge(objectNode, it, mapper)); + } } - } + + }); + } return mapper.readerForUpdating(target).readValue(root); @@ -295,8 +298,7 @@ public class DomainObjectReader { * @return * @throws Exception */ - private boolean handleArray(JsonNode node, Object source, ObjectMapper mapper, TypeInformation collectionType) - throws Exception { + private boolean handleArray(JsonNode node, Object source, ObjectMapper mapper, TypeInformation collectionType) { Collection collection = ifCollection(source); @@ -304,7 +306,7 @@ public class DomainObjectReader { return false; } - return handleArrayNode((ArrayNode) node, collection, mapper, collectionType.getComponentType()); + return execute(() -> handleArrayNode((ArrayNode) node, collection, mapper, collectionType.getComponentType())); } /** @@ -317,7 +319,7 @@ public class DomainObjectReader { * @return whether an object merge has been applied to the {@link ArrayNode}. */ private boolean handleArrayNode(ArrayNode array, Collection collection, ObjectMapper mapper, - TypeInformation componentType) throws Exception { + Optional> componentType) throws Exception { Assert.notNull(array, "ArrayNode must not be null!"); Assert.notNull(collection, "Source collection must not be null!"); @@ -375,7 +377,7 @@ public class DomainObjectReader { Iterator> fields = node.fields(); Class keyType = typeOrObject(type.getComponentType()); - TypeInformation valueType = type.getMapValueType(); + Optional> valueType = type.getMapValueType(); while (fields.hasNext()) { @@ -393,7 +395,7 @@ public class DomainObjectReader { } else if (value instanceof ArrayNode && sourceValue != null) { - handleArray(value, sourceValue, mapper, getTypeToMap(sourceValue, typeToMap)); + handleArray(value, sourceValue, mapper, getTypeToMap(sourceValue, Optional.of(typeToMap))); } else { @@ -405,89 +407,84 @@ public class DomainObjectReader { } @SuppressWarnings("unchecked") - private Map mergeMaps(PersistentProperty property, Object source, Object target, - ObjectMapper mapper) { + private Optional> mergeMaps(PersistentProperty property, Optional source, + Optional target, ObjectMapper mapper) { - Map sourceMap = (Map) source; + return source.map(it -> { - if (sourceMap == null) { - return null; - } + Map sourceMap = (Map) it; + Map targetMap = (Map) target.orElse(null); - Map targetMap = (Map) target; - Map result = targetMap == null ? CollectionFactory.createMap(Map.class, sourceMap.size()) - : CollectionFactory.createApproximateMap(targetMap, sourceMap.size()); + Map result = targetMap == null ? CollectionFactory.createMap(Map.class, sourceMap.size()) + : CollectionFactory.createApproximateMap(targetMap, sourceMap.size()); - for (Entry entry : sourceMap.entrySet()) { + for (Entry entry : sourceMap.entrySet()) { - Object targetValue = targetMap == null ? null : targetMap.get(entry.getKey()); - result.put(entry.getKey(), mergeForPut(entry.getValue(), targetValue, mapper)); - } + Object targetValue = targetMap == null ? null : targetMap.get(entry.getKey()); + result.put(entry.getKey(), mergeForPut(entry.getValue(), targetValue, mapper)); + } - if (targetMap == null) { - return result; - } + if (targetMap == null) { + return result; + } - try { + try { - targetMap.clear(); - targetMap.putAll(result); + targetMap.clear(); + targetMap.putAll(result); - return targetMap; + return targetMap; - } catch (UnsupportedOperationException o_O) { - return result; - } + } catch (UnsupportedOperationException o_O) { + return result; + } + }); } - private Collection mergeCollections(PersistentProperty property, Object source, Object target, - ObjectMapper mapper) { + private Optional> mergeCollections(PersistentProperty property, Optional source, + Optional target, ObjectMapper mapper) { - Collection sourceCollection = asCollection(source); + return source.map(it -> { - if (sourceCollection == null) { - return null; - } + Collection sourceCollection = asCollection(it); + Collection targetCollection = asCollection(target.orElse(null)); + Collection result = targetCollection == null + ? CollectionFactory.createCollection(Collection.class, sourceCollection.size()) + : CollectionFactory.createApproximateCollection(targetCollection, sourceCollection.size()); - Collection targetCollection = asCollection(target); - Collection result = targetCollection == null - ? CollectionFactory.createCollection(Collection.class, sourceCollection.size()) - : CollectionFactory.createApproximateCollection(targetCollection, sourceCollection.size()); + Iterator sourceIterator = sourceCollection.iterator(); + Iterator targetIterator = targetCollection == null ? Collections.emptyIterator() + : targetCollection.iterator(); - Iterator sourceIterator = sourceCollection.iterator(); - Iterator targetIterator = targetCollection == null ? Collections.emptyIterator() - : targetCollection.iterator(); + while (sourceIterator.hasNext()) { - while (sourceIterator.hasNext()) { + Object sourceElement = sourceIterator.next(); + Object targetElement = targetIterator.hasNext() ? targetIterator.next() : null; - Object sourceElement = sourceIterator.next(); - Object targetElement = targetIterator.hasNext() ? targetIterator.next() : null; + result.add(mergeForPut(sourceElement, targetElement, mapper)); + } - result.add(mergeForPut(sourceElement, targetElement, mapper)); - } + if (targetCollection == null) { + return result; + } - if (targetCollection == null) { - return result; - } + try { - try { + targetCollection.clear(); + targetCollection.addAll(result); - targetCollection.clear(); - targetCollection.addAll(result); + return targetCollection; - return targetCollection; - - } catch (UnsupportedOperationException o_O) { - return result; - } + } catch (UnsupportedOperationException o_O) { + return result; + } + }); } @SuppressWarnings("unchecked") private static Collection asCollection(Object source) { - if (source == null) { - return null; - } else if (source instanceof Collection) { + if (source instanceof Collection) { return (Collection) source; } else if (source.getClass().isArray()) { return Arrays.asList(ObjectUtils.toObjectArray(source)); @@ -535,8 +532,9 @@ public class DomainObjectReader { * @param type can be {@literal null}. * @return */ - private static Class typeOrObject(TypeInformation type) { - return type == null ? Object.class : type.getType(); + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static Class typeOrObject(Optional> type) { + return type.map(it -> it.getType()).orElse((Class) Object.class); } /** @@ -548,21 +546,21 @@ public class DomainObjectReader { * @param type can be {@literal null}. * @return */ - private static TypeInformation getTypeToMap(Object value, TypeInformation type) { + private static TypeInformation getTypeToMap(Object value, Optional> type) { - if (type == null) { - type = ClassTypeInformation.OBJECT; - } + return type.map(it -> { - if (value == null) { - return type; - } + if (value == null) { + return it; + } - if (Enum.class.isInstance(value)) { - return ClassTypeInformation.from(((Enum) value).getDeclaringClass()); - } + if (Enum.class.isInstance(value)) { + return ClassTypeInformation.from(((Enum) value).getDeclaringClass()); + } - return value.getClass().equals(type.getType()) ? type : ClassTypeInformation.from(value.getClass()); + return value.getClass().equals(it.getType()) ? it : ClassTypeInformation.from(value.getClass()); + + }).orElse(ClassTypeInformation.OBJECT); } /** @@ -642,9 +640,9 @@ public class DomainObjectReader { return; } - Object sourceValue = sourceAccessor.getProperty(property); - Object targetValue = targetAccessor.getProperty(property); - Object result = null; + Optional sourceValue = sourceAccessor.getProperty(property); + Optional targetValue = targetAccessor.getProperty(property); + Optional result = Optional.empty(); if (property.isMap()) { result = mergeMaps(property, sourceValue, targetValue, mapper); @@ -659,4 +657,30 @@ public class DomainObjectReader { targetAccessor.setProperty(property, result); } } + + private static T execute(SupplierWithException block) { + + try { + return block.execute(); + } catch (Exception o_O) { + throw new RuntimeException(o_O); + } + } + + private static void execute(RunnableWithException block) { + + try { + block.execute(); + } catch (Exception o_O) { + throw new RuntimeException(o_O); + } + } + + interface RunnableWithException { + void execute() throws Exception; + } + + interface SupplierWithException { + T execute() throws Exception; + } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JacksonMappingAwareSortTranslator.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JacksonMappingAwareSortTranslator.java index cb8e62a37..740da5d20 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JacksonMappingAwareSortTranslator.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/JacksonMappingAwareSortTranslator.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -153,7 +154,7 @@ public class JacksonMappingAwareSortTranslator { } } - return filteredOrders.isEmpty() ? null : new Sort(filteredOrders); + return filteredOrders.isEmpty() ? Sort.unsorted() : Sort.by(filteredOrders); } private String getMappedPropertyPath(PersistentEntity rootEntity, List iteratorSource) { @@ -209,32 +210,28 @@ public class JacksonMappingAwareSortTranslator { private final PersistentEntities persistentEntities; private final ObjectMapper objectMapper; - private final PersistentEntity currentType; + private final Optional>> currentType; private final MappedProperties currentProperties; private final WrappedProperties currentWrappedProperties; - private TypedSegment(TypedSegment previous, PersistentEntity persistentEntity) { + private TypedSegment(TypedSegment previous, + Optional>> persistentEntity) { this(previous.persistentEntities, previous.objectMapper, persistentEntity); } private TypedSegment(PersistentEntities persistentEntities, ObjectMapper objectMapper, - PersistentEntity persistentEntity) { + Optional>> persistentEntity) { this.persistentEntities = persistentEntities; this.objectMapper = objectMapper; this.currentType = persistentEntity; + this.currentProperties = persistentEntity// + .map(it -> MappedProperties.fromJacksonProperties(it, objectMapper))// + .orElseGet(() -> MappedProperties.none()); + this.currentWrappedProperties = persistentEntity// + .map(it -> WrappedProperties.fromJacksonProperties(persistentEntities, it, objectMapper))// + .orElseGet(() -> WrappedProperties.none()); - if (persistentEntity != null) { - - this.currentProperties = MappedProperties.fromJacksonProperties(currentType, objectMapper); - this.currentWrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, currentType, - objectMapper); - - } else { - - this.currentProperties = null; - this.currentWrappedProperties = null; - } } /** @@ -253,7 +250,7 @@ public class JacksonMappingAwareSortTranslator { Assert.notNull(objectMapper, "ObjectMapper must not be null!"); Assert.notNull(rootEntity, "PersistentEntity must not be null!"); - return new TypedSegment(persistentEntities, objectMapper, rootEntity); + return new TypedSegment(persistentEntities, objectMapper, Optional.of(rootEntity)); } /** @@ -266,8 +263,7 @@ public class JacksonMappingAwareSortTranslator { Assert.notNull(persistentProperty, "PersistentProperty must not be null!"); - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(persistentProperty.getType()); - return new TypedSegment(this, persistentEntity); + return new TypedSegment(this, persistentEntities.getPersistentEntity(persistentProperty.getType())); } private boolean hasPersistentPropertyForField(String fieldName) { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappedProperties.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappedProperties.java index 3492eb38d..a53ab6a11 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappedProperties.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappedProperties.java @@ -15,12 +15,16 @@ */ package org.springframework.data.rest.webmvc.json; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; + import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.springframework.data.mapping.PersistentEntity; @@ -39,6 +43,7 @@ import com.fasterxml.jackson.databind.introspect.ClassIntrospector; * @author Oliver Gierke * @author Mark Paluch */ +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) class MappedProperties { private static final ClassIntrospector INTROSPECTOR = new BasicClassIntrospector(); @@ -53,7 +58,7 @@ class MappedProperties { * @param entity must not be {@literal null}. * @param description must not be {@literal null}. */ - private MappedProperties(PersistentEntity entity, BeanDescription description) { + private MappedProperties(PersistentEntity> entity, BeanDescription description) { Assert.notNull(entity, "Entity must not be null!"); Assert.notNull(description, "BeanDescription must not be null!"); @@ -64,12 +69,15 @@ class MappedProperties { for (BeanPropertyDefinition property : description.findProperties()) { - PersistentProperty persistentProperty = entity.getPersistentProperty(property.getInternalName()); + Optional> persistentProperty = entity + .getPersistentProperty(property.getInternalName()); - if (persistentProperty != null) { - propertyToFieldName.put(persistentProperty, property); - fieldNameToProperty.put(property.getName(), persistentProperty); - } else { + persistentProperty.ifPresent(it -> { + propertyToFieldName.put(it, property); + fieldNameToProperty.put(property.getName(), it); + }); + + if (!persistentProperty.isPresent()) { unmappedProperties.add(property); } } @@ -90,6 +98,10 @@ class MappedProperties { return new MappedProperties(entity, description); } + public static MappedProperties none() { + return new MappedProperties(Collections.emptyMap(), Collections.emptyMap(), Collections.emptySet()); + } + /** * @param property must not be {@literal null} * @return the mapped name for the {@link PersistentProperty} diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareDefaultedPageableArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareDefaultedPageableArgumentResolver.java index 0583a86b3..5cd779661 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareDefaultedPageableArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareDefaultedPageableArgumentResolver.java @@ -71,7 +71,7 @@ public class MappingAwareDefaultedPageableArgumentResolver implements HandlerMet } Sort translated = translator.translateSort(pageable.getSort(), parameter, webRequest); - pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), translated); + pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), translated); return new DefaultedPageable(pageable, delegate.isFallbackPageable(pageable)); } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolver.java index 161688ee1..848821cf1 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolver.java @@ -70,6 +70,6 @@ public class MappingAwarePageableArgumentResolver implements HandlerMethodArgume } Sort translated = translator.translateSort(pageable.getSort(), methodParameter, webRequest); - return new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), translated); + return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), translated); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareSortArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareSortArgumentResolver.java index db7815fec..59c7ff3fa 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareSortArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/MappingAwareSortArgumentResolver.java @@ -63,6 +63,6 @@ public class MappingAwareSortArgumentResolver implements HandlerMethodArgumentRe Sort sort = delegate.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory); - return sort == null ? null : translator.translateSort(sort, methodParameter, webRequest); + return sort.isUnsorted() ? sort : translator.translateSort(sort, methodParameter, webRequest); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java index b7ae61471..6f5bd2a69 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2Module.java @@ -26,6 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,16 +45,17 @@ import org.springframework.data.rest.core.mapping.ResourceMappings; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.SelfLinkProvider; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler; import org.springframework.data.rest.webmvc.PersistentEntityResource; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.rest.webmvc.mapping.LinkCollector; +import org.springframework.data.util.CastUtils; import org.springframework.hateoas.Link; import org.springframework.hateoas.Links; import org.springframework.hateoas.Resource; import org.springframework.hateoas.UriTemplate; import org.springframework.hateoas.mvc.ResourceProcessorInvoker; -import org.springframework.plugin.core.PluginRegistry; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -78,7 +80,6 @@ import com.fasterxml.jackson.databind.deser.ValueInstantiator; import com.fasterxml.jackson.databind.deser.std.CollectionDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; -import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -242,58 +243,56 @@ public class PersistentEntityJackson2Module extends SimpleModule { public BeanSerializerBuilder updateBuilder(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder) { - PersistentEntity entity = entities.getPersistentEntity(beanDesc.getBeanClass()); + entities.getPersistentEntity(beanDesc.getBeanClass()).ifPresent(entity -> { - if (entity == null) { - return builder; - } + List result = new ArrayList(); - List result = new ArrayList(); + for (BeanPropertyWriter writer : builder.getProperties()) { - for (BeanPropertyWriter writer : builder.getProperties()) { + Optional> findProperty = findProperty(writer.getName(), entity, beanDesc); - // Skip exported associations - PersistentProperty persistentProperty = findProperty(writer.getName(), entity, beanDesc); + findProperty.ifPresent(it -> { - if (persistentProperty == null) { - result.add(writer); - continue; + if (associations.isLookupType(it)) { + + LOG.debug("Assigning lookup object serializer for {}.", it); + writer.assignSerializer(lookupObjectSerializer); + result.add(writer); + return; + } + + // Is there a default projection? + + if (associations.isLinkableAssociation(it)) { + return; + } + + // Skip ids unless explicitly configured to expose + if (it.isIdProperty() && !associations.isIdExposed(entity)) { + return; + } + + if (it.isVersionProperty()) { + return; + } + + if (it.isEntity() && !writer.isUnwrapping()) { + + LOG.debug("Assigning nested entity serializer for {}.", it); + + writer.assignSerializer(nestedEntitySerializer); + } + + result.add(writer); + }); + + if (!findProperty.isPresent()) { + result.add(writer); + } } - if (associations.isLookupType(persistentProperty)) { - - LOG.debug("Assigning lookup object serializer for {}.", persistentProperty); - writer.assignSerializer(lookupObjectSerializer); - result.add(writer); - continue; - } - - // Is there a default projection? - - if (associations.isLinkableAssociation(persistentProperty)) { - continue; - } - - // Skip ids unless explicitly configured to expose - if (persistentProperty.isIdProperty() && !associations.isIdExposed(entity)) { - continue; - } - - if (persistentProperty.isVersionProperty()) { - continue; - } - - if (persistentProperty.isEntity() && !writer.isUnwrapping()) { - - LOG.debug("Assigning nested entity serializer for {}.", persistentProperty); - - writer.assignSerializer(nestedEntitySerializer); - } - - result.add(writer); - } - - builder.setProperties(result); + builder.setProperties(result); + }); return builder; } @@ -307,16 +306,12 @@ public class PersistentEntityJackson2Module extends SimpleModule { * @param description the Jackson {@link BeanDescription}. * @return */ - private PersistentProperty findProperty(String finalName, PersistentEntity entity, - BeanDescription description) { + private Optional> findProperty(String finalName, + PersistentEntity> entity, BeanDescription description) { - for (BeanPropertyDefinition definition : description.findProperties()) { - if (definition.getName().equals(finalName)) { - return entity.getPersistentProperty(definition.getInternalName()); - } - } - - return null; + return description.findProperties().stream()// + .filter(it -> it.getName().equals(finalName))// + .findFirst().flatMap(it -> entity.getPersistentProperty(it.getInternalName())); } } @@ -390,7 +385,7 @@ public class PersistentEntityJackson2Module extends SimpleModule { private Resource toResource(Object value) { - PersistentEntity entity = entities.getPersistentEntity(value.getClass()); + PersistentEntity entity = entities.getRequiredPersistentEntity(value.getClass()); return invoker.invokeProcessorsFor(PersistentEntityResource.build(value, entity).// withEmbedded(assembler.getEmbeddedResources(value)).// @@ -422,37 +417,37 @@ public class PersistentEntityJackson2Module extends SimpleModule { BeanDeserializerBuilder builder) { Iterator properties = builder.getProperties(); - PersistentEntity entity = entities.getPersistentEntity(beanDesc.getBeanClass()); - if (entity == null) { - return builder; - } + entities.getPersistentEntity(beanDesc.getBeanClass()).ifPresent(entity -> { - while (properties.hasNext()) { + while (properties.hasNext()) { - SettableBeanProperty property = properties.next(); - PersistentProperty persistentProperty = entity.getPersistentProperty(property.getName()); + SettableBeanProperty property = properties.next(); - if (associationLinks.isLookupType(persistentProperty)) { + entity.getPersistentProperty(property.getName()).ifPresent(persistentProperty -> { - RepositoryInvokingDeserializer repositoryInvokingDeserializer = new RepositoryInvokingDeserializer(factory, - persistentProperty); - JsonDeserializer deserializer = wrapIfCollection(persistentProperty, repositoryInvokingDeserializer, - config); + if (associationLinks.isLookupType(persistentProperty)) { - builder.addOrReplaceProperty(property.withValueDeserializer(deserializer), false); - continue; + RepositoryInvokingDeserializer repositoryInvokingDeserializer = new RepositoryInvokingDeserializer( + factory, persistentProperty); + JsonDeserializer deserializer = wrapIfCollection(persistentProperty, repositoryInvokingDeserializer, + config); + + builder.addOrReplaceProperty(property.withValueDeserializer(deserializer), false); + return; + } + + if (!associationLinks.isLinkableAssociation(persistentProperty)) { + return; + } + + UriStringDeserializer uriStringDeserializer = new UriStringDeserializer(persistentProperty, converter); + JsonDeserializer deserializer = wrapIfCollection(persistentProperty, uriStringDeserializer, config); + + builder.addOrReplaceProperty(property.withValueDeserializer(deserializer), false); + }); } - - if (!associationLinks.isLinkableAssociation(persistentProperty)) { - continue; - } - - UriStringDeserializer uriStringDeserializer = new UriStringDeserializer(persistentProperty, converter); - JsonDeserializer deserializer = wrapIfCollection(persistentProperty, uriStringDeserializer, config); - - builder.addOrReplaceProperty(property.withValueDeserializer(deserializer), false); - } + }); return builder; } @@ -775,7 +770,7 @@ public class PersistentEntityJackson2Module extends SimpleModule { public static class LookupObjectSerializer extends ToStringSerializer { private static final long serialVersionUID = -3033458643050330913L; - private final PluginRegistry, Class> lookups; + private final Java8PluginRegistry, Class> lookups; /* * (non-Javadoc) @@ -799,11 +794,13 @@ public class PersistentEntityJackson2Module extends SimpleModule { } } - @SuppressWarnings("unchecked") private String getLookupKey(Object value) { - EntityLookup lookup = (EntityLookup) lookups.getPluginFor(value.getClass()); - return lookup.getResourceIdentifier(value).toString(); + Optional> map = lookups.getPluginFor(value.getClass()).map(CastUtils::cast); + + return map + .orElseThrow(() -> new IllegalArgumentException("No EntityLookup found for " + value.getClass().getName())) + .getResourceIdentifier(value).toString(); } } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java index a865400d5..b414991d2 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/PersistentEntityToJsonSchemaConverter.java @@ -25,6 +25,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; +import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; @@ -53,6 +54,7 @@ import org.springframework.data.rest.webmvc.json.JsonSchema.Item; import org.springframework.data.rest.webmvc.json.JsonSchema.JsonSchemaProperty; import org.springframework.data.rest.webmvc.mapping.Associations; import org.springframework.data.util.ClassTypeInformation; +import org.springframework.data.util.Optionals; import org.springframework.data.util.TypeInformation; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -78,10 +80,10 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric private final Set convertiblePairs = new HashSet(); private final Associations associations; private final PersistentEntities entities; - private final MessageSourceAccessor accessor; private final ObjectMapper objectMapper; private final RepositoryRestConfiguration configuration; private final ValueTypeSchemaPropertyCustomizerFactory customizerFactory; + private final MessageResolver resolver; /** * Creates a new {@link PersistentEntityToJsonSchemaConverter} for the given {@link PersistentEntities} and @@ -105,10 +107,10 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric this.entities = entities; this.associations = associations; - this.accessor = accessor; this.objectMapper = objectMapper; this.configuration = configuration; this.customizerFactory = customizerFactory; + this.resolver = new DefaultMessageResolver(accessor, configuration); for (TypeInformation domainType : entities.getManagedTypes()) { convertiblePairs.add(new ConvertiblePair(domainType.getType(), JsonSchema.class)); @@ -151,121 +153,116 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric @Override public JsonSchema convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - final PersistentEntity persistentEntity = entities.getPersistentEntity((Class) source); + final PersistentEntity persistentEntity = entities.getRequiredPersistentEntity((Class) source); final ResourceMetadata metadata = associations.getMappings().getMetadataFor(persistentEntity.getType()); Definitions definitions = new Definitions(); List> propertiesFor = getPropertiesFor(persistentEntity.getType(), metadata, definitions); - String title = resolveMessageWithDefault(new ResolvableType(persistentEntity.getType())); + String title = resolver.resolveWithDefault(new ResolvableType(persistentEntity.getType())); - return new JsonSchema(title, resolveMessage(metadata.getItemResourceDescription()), propertiesFor, definitions); + return new JsonSchema(title, resolver.resolve(metadata.getItemResourceDescription()), propertiesFor, definitions); } private List> getPropertiesFor(Class type, final ResourceMetadata metadata, final Definitions definitions) { - final PersistentEntity entity = entities.getPersistentEntity(type); - final JacksonMetadata jackson = new JacksonMetadata(objectMapper, type); + return entities.getPersistentEntity(type).map(entity -> { - if (entity == null) { - return Collections.> emptyList(); - } + final JacksonMetadata jackson = new JacksonMetadata(objectMapper, type); + JsonSchemaPropertyRegistrar registrar = new JsonSchemaPropertyRegistrar(jackson); - JsonSchemaPropertyRegistrar registrar = new JsonSchemaPropertyRegistrar(jackson); + for (BeanPropertyDefinition definition : jackson) { - for (BeanPropertyDefinition definition : jackson) { + JacksonProperty jacksonProperty = new JacksonProperty(jackson, + entity.getPersistentProperty(definition.getInternalName()), definition); - PersistentProperty persistentProperty = entity.getPersistentProperty(definition.getInternalName()); + Optional> prop = entity.getPersistentProperty(definition.getInternalName()); - // First pass, early drops to avoid unnecessary calculation - if (persistentProperty != null) { + // First pass, early drops to avoid unnecessary calculation + if (prop.isPresent()) { - if (persistentProperty.isIdProperty() && !configuration.isIdExposedFor(type)) { - continue; - } + PersistentProperty persistentProperty = prop.get(); - if (persistentProperty.isVersionProperty()) { - continue; - } - - if (!definition.couldSerialize()) { - continue; - } - } - - AnnotatedMember primaryMember = definition.getPrimaryMember(); - - if (primaryMember == null) { - continue; - } - - TypeInformation propertyType = persistentProperty == null - ? ClassTypeInformation.from(primaryMember.getRawType()) : persistentProperty.getTypeInformation(); - TypeInformation actualPropertyType = propertyType.getActualType(); - Class rawPropertyType = propertyType.getType(); - - JsonSchemaFormat format = configuration.getMetadataConfiguration().getSchemaFormatFor(rawPropertyType); - ResourceDescription description = persistentProperty == null - ? jackson.getFallbackDescription(metadata, definition) : getDescriptionFor(persistentProperty, metadata); - JsonSchemaProperty property = getSchemaProperty(definition, propertyType, description); - - boolean isSyntheticProperty = persistentProperty == null; - boolean isNotWritable = !isSyntheticProperty && !persistentProperty.isWritable(); - boolean isJacksonReadOnly = !isSyntheticProperty && jackson.isReadOnly(persistentProperty); - - if (isSyntheticProperty || isNotWritable || isJacksonReadOnly) { - property = property.withReadOnly(); - } - - if (format != null) { - - // Types with explicitly registered format -> value object with format - registrar.register(property.withFormat(format), actualPropertyType); - continue; - } - - Pattern pattern = configuration.getMetadataConfiguration().getPatternFor(rawPropertyType); - - if (pattern != null) { - registrar.register(property.withPattern(pattern), actualPropertyType); - continue; - } - - if (jackson.isValueType()) { - registrar.register(property.with(STRING_TYPE_INFORMATION), actualPropertyType); - continue; - } - - if (persistentProperty == null) { - registrar.register(property, actualPropertyType); - continue; - } - - if (configuration.isLookupType(persistentProperty.getActualType())) { - registrar.register(property.with(propertyType), actualPropertyType); - } else if (associations.isLinkableAssociation(persistentProperty)) { - registrar.register(property.asAssociation(), null); - } else { - - if (persistentProperty.isEntity()) { - - if (!definitions.hasDefinitionFor(propertyType)) { - definitions.addDefinition(propertyType, - new Item(propertyType, getNestedPropertiesFor(persistentProperty, definitions))); + if (persistentProperty.isIdProperty() && !configuration.isIdExposedFor(type)) { + continue; } - registrar.register(property.with(propertyType, Definitions.getReference(propertyType)), actualPropertyType); + if (persistentProperty.isVersionProperty()) { + continue; + } - } else { - - registrar.register(property.with(propertyType), actualPropertyType); + if (!definition.couldSerialize()) { + continue; + } } - } - } - return registrar.getProperties(); + AnnotatedMember primaryMember = definition.getPrimaryMember(); + + if (primaryMember == null) { + continue; + } + + TypeInformation propertyType = jacksonProperty.getPropertyType(); + TypeInformation actualPropertyType = propertyType.getActualType(); + Class rawPropertyType = propertyType.getType(); + + JsonSchemaFormat format = configuration.getMetadataConfiguration().getSchemaFormatFor(rawPropertyType); + + ResourceDescription description = prop.map(it -> getDescriptionFor(it, metadata)) + .orElseGet(() -> jackson.getFallbackDescription(metadata, definition)); + JsonSchemaProperty property = jacksonProperty.getSchemaProperty(description, resolver); + + if (format != null) { + + // Types with explicitly registered format -> value object with format + registrar.register(property.withFormat(format), actualPropertyType); + continue; + } + + Pattern pattern = configuration.getMetadataConfiguration().getPatternFor(rawPropertyType); + + if (pattern != null) { + registrar.register(property.withPattern(pattern), actualPropertyType); + continue; + } + + if (jackson.isValueType()) { + registrar.register(property.with(STRING_TYPE_INFORMATION), actualPropertyType); + continue; + } + + Optionals.ifPresentOrElse(prop, it -> { + + if (configuration.isLookupType(it.getActualType())) { + registrar.register(property.with(propertyType), actualPropertyType); + } else if (associations.isLinkableAssociation(it)) { + registrar.register(property.asAssociation(), null); + } else { + + if (it.isEntity()) { + + if (!definitions.hasDefinitionFor(propertyType)) { + definitions.addDefinition(propertyType, + new Item(propertyType, getNestedPropertiesFor(it, definitions))); + } + + registrar.register(property.with(propertyType, Definitions.getReference(propertyType)), + actualPropertyType); + + } else { + + registrar.register(property.with(propertyType), actualPropertyType); + } + } + + }, () -> registrar.register(property, actualPropertyType)); + } + + return registrar.getProperties(); + + }).orElse(Collections.emptyList()); } private Collection> getNestedPropertiesFor(PersistentProperty property, @@ -278,25 +275,25 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric return getPropertiesFor(property.getActualType(), associations.getMappings().getMetadataFor(property.getActualType()), descriptors); } - - private JsonSchemaProperty getSchemaProperty(BeanPropertyDefinition definition, TypeInformation type, - ResourceDescription description) { - - String name = definition.getName(); - String title = resolveMessageWithDefault(new ResolvableProperty(definition)); - String resolvedDescription = resolveMessage(description); - boolean required = definition.isRequired(); - Class rawType = type.getType(); - - if (!rawType.isEnum()) { - return new JsonSchemaProperty(name, title, resolvedDescription, required).with(type); - } - - String message = resolveMessage(new DefaultMessageSourceResolvable(description.getMessage())); - - return new EnumProperty(name, title, rawType, - description.getDefaultMessage().equals(resolvedDescription) ? message : resolvedDescription, required); - } + // + // private JsonSchemaProperty getSchemaProperty(BeanPropertyDefinition definition, TypeInformation type, + // ResourceDescription description) { + // + // String name = definition.getName(); + // String title = resolver.resolveWithDefault(new ResolvableProperty(definition)); + // String resolvedDescription = resolver.resolve(description); + // boolean required = definition.isRequired(); + // Class rawType = type.getType(); + // + // if (!rawType.isEnum()) { + // return new JsonSchemaProperty(name, title, resolvedDescription, required).with(type); + // } + // + // String message = resolver.resolve(new DefaultMessageSourceResolvable(description.getMessage())); + // + // return new EnumProperty(name, title, rawType, + // description.getDefaultMessage().equals(resolvedDescription) ? message : resolvedDescription, required); + // } private ResourceDescription getDescriptionFor(PersistentProperty property, ResourceMetadata metadata) { @@ -304,28 +301,6 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric return propertyMapping.getDescription(); } - private String resolveMessageWithDefault(MessageSourceResolvable resolvable) { - return resolveMessage(new DefaultingMessageSourceResolvable(resolvable)); - } - - private String resolveMessage(MessageSourceResolvable resolvable) { - - if (resolvable == null) { - return null; - } - - try { - return accessor.getMessage(resolvable); - } catch (NoSuchMessageException o_O) { - - if (configuration.getMetadataConfiguration().omitUnresolvableDescriptionKeys()) { - return null; - } else { - throw o_O; - } - } - } - /** * Helper to register {@link JsonSchemaProperty} instances after post-processing them. * @@ -407,6 +382,148 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric } } + /** + * A {@link BeanPropertyDefinition} that can be resolved via a {@link MessageSource}. + * + * @author Oliver Gierke + * @since 2.4.1 + */ + private static class ResolvableProperty extends DefaultMessageSourceResolvable { + + private static final long serialVersionUID = -5603381674553244480L; + + /** + * Creates a new {@link ResolvableProperty} for the given {@link BeanPropertyDefinition}. + * + * @param property must not be {@literal null}. + */ + public ResolvableProperty(BeanPropertyDefinition property) { + super(getCodes(property)); + } + + private static String[] getCodes(BeanPropertyDefinition property) { + + Assert.notNull(property, "BeanPropertyDefinition must not be null!"); + + Class owner = property.getPrimaryMember().getDeclaringClass(); + + String propertyTitle = property.getInternalName().concat("._title"); + String localName = owner.getSimpleName().concat(".").concat(propertyTitle); + String fullName = owner.getName().concat(".").concat(propertyTitle); + + return new String[] { fullName, localName, propertyTitle }; + } + } + + /** + * A type whose title can be resolved through a {@link MessageSource}. + * + * @author Oliver Gierke + * @since 2.4.1 + */ + private static class ResolvableType extends DefaultMessageSourceResolvable { + + private static final long serialVersionUID = -7199875272753949857L; + + /** + * Creates a new {@link ResolvableType} for the given type. + * + * @param type must not be {@literal null}. + */ + public ResolvableType(Class type) { + super(getTitleCodes(type)); + } + + private static String[] getTitleCodes(Class type) { + + Assert.notNull(type, "Type must not be null!"); + + return new String[] { type.getName().concat("._title"), type.getSimpleName().concat("._title") }; + } + } + + @RequiredArgsConstructor + private static class JacksonProperty { + + private final JacksonMetadata metadata; + private final Optional> property; + private final BeanPropertyDefinition definition; + + @SuppressWarnings("rawtypes") + public TypeInformation getPropertyType() { + return property.map(it -> (TypeInformation) it.getTypeInformation()) + .orElseGet(() -> ClassTypeInformation.from(definition.getPrimaryMember().getRawType())); + } + + public JsonSchemaProperty getSchemaProperty(ResourceDescription description, MessageResolver resolver) { + + JsonSchemaProperty result = getSchemaProperty(definition, getPropertyType(), description, resolver); + + boolean isSyntheticProperty = !property.isPresent(); + boolean isNotWritable = property.map(it -> !it.isWritable()).orElse(false); + boolean isJacksonReadOnly = property.map(it -> metadata.isReadOnly(it)).orElse(false); + + if (isSyntheticProperty || isNotWritable || isJacksonReadOnly) { + result = result.withReadOnly(); + } + + return result; + } + + private JsonSchemaProperty getSchemaProperty(BeanPropertyDefinition definition, TypeInformation type, + ResourceDescription description, MessageResolver resolver) { + + String name = definition.getName(); + String title = resolver.resolveWithDefault(new ResolvableProperty(definition)); + String resolvedDescription = resolver.resolve(description); + boolean required = definition.isRequired(); + Class rawType = type.getType(); + + if (!rawType.isEnum()) { + return new JsonSchemaProperty(name, title, resolvedDescription, required).with(type); + } + + String message = resolver.resolve(new DefaultMessageSourceResolvable(description.getMessage())); + + return new EnumProperty(name, title, rawType, + description.getDefaultMessage().equals(resolvedDescription) ? message : resolvedDescription, required); + } + } + + private interface MessageResolver { + + String resolve(MessageSourceResolvable resolvable); + + default String resolveWithDefault(MessageSourceResolvable resolvable) { + return resolve(new DefaultingMessageSourceResolvable(resolvable)); + } + } + + @RequiredArgsConstructor + private static class DefaultMessageResolver implements MessageResolver { + + private final MessageSourceAccessor accessor; + private final RepositoryRestConfiguration configuration; + + public String resolve(MessageSourceResolvable resolvable) { + + if (resolvable == null) { + return null; + } + + try { + return accessor.getMessage(resolvable); + } catch (NoSuchMessageException o_O) { + + if (configuration.getMetadataConfiguration().omitUnresolvableDescriptionKeys()) { + return null; + } else { + throw o_O; + } + } + } + } + /** * Message source resolvable that defaults the messages to the last segment of the dot-separated code in case the * configured delegate doesn't return a default message itself. @@ -468,64 +585,4 @@ public class PersistentEntityToJsonSchemaConverter implements ConditionalGeneric .collectionToDelimitedString(Arrays.asList(SPLIT_CAMEL_CASE.split(tail)), " ").toLowerCase(Locale.US)); } } - - /** - * A {@link BeanPropertyDefinition} that can be resolved via a {@link MessageSource}. - * - * @author Oliver Gierke - * @since 2.4.1 - */ - private static class ResolvableProperty extends DefaultMessageSourceResolvable { - - private static final long serialVersionUID = -5603381674553244480L; - - /** - * Creates a new {@link ResolvableProperty} for the given {@link BeanPropertyDefinition}. - * - * @param property must not be {@literal null}. - */ - public ResolvableProperty(BeanPropertyDefinition property) { - super(getCodes(property)); - } - - private static String[] getCodes(BeanPropertyDefinition property) { - - Assert.notNull(property, "BeanPropertyDefinition must not be null!"); - - Class owner = property.getPrimaryMember().getDeclaringClass(); - - String propertyTitle = property.getInternalName().concat("._title"); - String localName = owner.getSimpleName().concat(".").concat(propertyTitle); - String fullName = owner.getName().concat(".").concat(propertyTitle); - - return new String[] { fullName, localName, propertyTitle }; - } - } - - /** - * A type whose title can be resolved through a {@link MessageSource}. - * - * @author Oliver Gierke - * @since 2.4.1 - */ - private static class ResolvableType extends DefaultMessageSourceResolvable { - - private static final long serialVersionUID = -7199875272753949857L; - - /** - * Creates a new {@link ResolvableType} for the given type. - * - * @param type must not be {@literal null}. - */ - public ResolvableType(Class type) { - super(getTitleCodes(type)); - } - - private static String[] getTitleCodes(Class type) { - - Assert.notNull(type, "Type must not be null!"); - - return new String[] { type.getName().concat("._title"), type.getSimpleName().concat("._title") }; - } - } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/WrappedProperties.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/WrappedProperties.java index efa80ea8c..1e348c001 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/WrappedProperties.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/WrappedProperties.java @@ -24,10 +24,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.PersistentEntities; +import org.springframework.data.util.Optionals; import org.springframework.util.Assert; import com.fasterxml.jackson.annotation.JsonUnwrapped; @@ -81,6 +83,10 @@ class WrappedProperties { return new WrappedProperties(resolver.findUnwrappedPropertyPaths(entity.getType())); } + public static WrappedProperties none() { + return new WrappedProperties(Collections.emptyMap()); + } + /** * @param fieldName must not be empty or {@literal null}. * @return {@literal true} if the field name resolves to a {@literal PersistentProperty}. @@ -132,28 +138,28 @@ class WrappedProperties { private Map>> findUnwrappedPropertyPaths(Class type, NameTransformer nameTransformer, boolean considerRegularProperties) { - PersistentEntity entity = persistentEntities.getPersistentEntity(type); + return persistentEntities.getPersistentEntity(type).map(entity -> { - if (entity == null) { - return Collections.emptyMap(); - } + Map>> mapping = new HashMap>>(); - Map>> mapping = new HashMap>>(); + for (BeanPropertyDefinition property : getMappedProperties(entity)) { - for (BeanPropertyDefinition property : getMappedProperties(entity)) { + Optionals.ifAllPresent(entity.getPersistentProperty(property.getInternalName()), // + findAnnotatedMember(property), // + (prop, member) -> { - AnnotatedMember annotatedMember = findAnnotatedMember(property); - PersistentProperty persistentProperty = entity.getPersistentProperty(property.getInternalName()); - - if (isJsonUnwrapped(annotatedMember)) { - mapping.putAll(findUnwrappedPropertyPaths(nameTransformer, annotatedMember, persistentProperty)); - } else if (considerRegularProperties) { - mapping.put(nameTransformer.transform(property.getName()), - Collections.> singletonList(persistentProperty)); + if (isJsonUnwrapped(member)) { + mapping.putAll(findUnwrappedPropertyPaths(nameTransformer, member, prop)); + } else if (considerRegularProperties) { + mapping.put(nameTransformer.transform(property.getName()), + Collections.> singletonList(prop)); + } + }); } - } - return mapping; + return mapping; + + }).orElse(Collections.emptyMap()); } private Map>> findUnwrappedPropertyPaths(NameTransformer nameTransformer, @@ -187,13 +193,9 @@ class WrappedProperties { for (BeanPropertyDefinition property : properties) { - AnnotatedMember annotatedMember = findAnnotatedMember(property); - - if (annotatedMember == null || entity.getPersistentProperty(property.getInternalName()) == null) { - continue; - } - - withInternalName.add(property); + Optionals.ifAllPresent(findAnnotatedMember(property), // + entity.getPersistentProperty(property.getInternalName()), // + (member, prop) -> withInternalName.add(property)); } return withInternalName; @@ -204,21 +206,21 @@ class WrappedProperties { mapper.getDeserializationConfig()); } - private static AnnotatedMember findAnnotatedMember(BeanPropertyDefinition property) { + private static Optional findAnnotatedMember(BeanPropertyDefinition property) { if (property.getPrimaryMember() != null) { - return property.getPrimaryMember(); + return Optional.of(property.getPrimaryMember()); } if (property.getGetter() != null) { - return property.getGetter(); + return Optional.of(property.getGetter()); } if (property.getSetter() != null) { - return property.getSetter(); + return Optional.of(property.getSetter()); } - return null; + return Optional.empty(); } private static boolean isJsonUnwrapped(AnnotatedMember primaryMember) { diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/Associations.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/Associations.java index 06a25ae08..9fd76a7b6 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/Associations.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/Associations.java @@ -89,11 +89,14 @@ public class Associations { /** * Returns whether the type of the given {@link PersistentProperty} is configured as lookup type. * - * @param property can be {@literal null}. + * @param property must not be {@literal null}. * @return */ public boolean isLookupType(PersistentProperty property) { - return property == null ? false : config.isLookupType(property.getActualType()); + + Assert.notNull(property, "Persistent property must not be null!"); + + return config.isLookupType(property.getActualType()); } public boolean isIdExposed(PersistentEntity entity) { @@ -116,12 +119,14 @@ public class Associations { /** * Returns whether the given property is an association that is linkable. * - * @param property can be {@literal null}. + * @param property must not be {@literal null}. * @return */ public boolean isLinkableAssociation(PersistentProperty property) { - if (property == null || !property.isAssociation() || config.isLookupType(property.getActualType())) { + Assert.notNull(property, "PersistentProperty must not be null!"); + + if (!property.isAssociation() || config.isLookupType(property.getActualType())) { return false; } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/LinkCollector.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/LinkCollector.java index 286281fc9..e41396dcf 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/LinkCollector.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/LinkCollector.java @@ -90,8 +90,6 @@ public class LinkCollector { Assert.notNull(object, "Object must not be null!"); Assert.notNull(existingLinks, "Existing links must not be null!"); - PersistentEntity entity = entities.getPersistentEntity(object.getClass()); - Links links = new Links(existingLinks); Link selfLink = createSelfLink(object, links); @@ -102,7 +100,7 @@ public class LinkCollector { Path path = new Path(selfLink.expand().getHref()); LinkCollectingAssociationHandler handler = new LinkCollectingAssociationHandler(entities, path, associationLinks); - entity.doWithAssociations(handler); + entities.getRequiredPersistentEntity(object.getClass()).doWithAssociations(handler); List result = new ArrayList(existingLinks); result.addAll(handler.getLinks()); @@ -112,7 +110,7 @@ public class LinkCollector { public Links getLinksForNested(Object object, List existing) { - PersistentEntity entity = entities.getPersistentEntity(object.getClass()); + PersistentEntity entity = entities.getRequiredPersistentEntity(object.getClass()); NestedLinkCollectingAssociationHandler handler = new NestedLinkCollectingAssociationHandler(links, entity.getPropertyAccessor(object), associationLinks); @@ -217,19 +215,17 @@ public class LinkCollector { } PersistentProperty property = association.getInverse(); - Object value = accessor.getProperty(property); - if (value == null) { - return; - } + accessor.getProperty(property).ifPresent(it -> { - ResourceMetadata metadata = associations.getMappings().getMetadataFor(property.getOwner().getType()); - ResourceMapping propertyMapping = metadata.getMappingFor(property); + ResourceMetadata metadata = associations.getMappings().getMetadataFor(property.getOwner().getType()); + ResourceMapping propertyMapping = metadata.getMappingFor(property); - for (Object element : asCollection(value)) { - if (element != null) - links.add(getLinkFor(element, propertyMapping)); - } + for (Object element : asCollection(it)) { + if (element != null) + links.add(getLinkFor(element, propertyMapping)); + } + }); } /** diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/NestedLinkCollectingAssociationHandler.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/NestedLinkCollectingAssociationHandler.java index 2f6b15741..eabe6f2ae 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/NestedLinkCollectingAssociationHandler.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/mapping/NestedLinkCollectingAssociationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import java.util.List; import org.springframework.data.mapping.Association; import org.springframework.data.mapping.IdentifierAccessor; +import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.PersistentPropertyAccessor; import org.springframework.data.mapping.SimpleAssociationHandler; @@ -64,8 +65,8 @@ public class NestedLinkCollectingAssociationHandler implements SimpleAssociation for (Object element : (Collection) propertyValue) { - IdentifierAccessor identifierAccessor = entities.getPersistentEntity(element.getClass()) - .getIdentifierAccessor(element); + PersistentEntity entity = entities.getRequiredPersistentEntity(element.getClass()); + IdentifierAccessor identifierAccessor = entity.getIdentifierAccessor(element); links.add(entityLinks.linkForSingleResource(element.getClass(), identifierAccessor.getIdentifier()) .withRel(propertyMapping.getRel())); @@ -73,8 +74,8 @@ public class NestedLinkCollectingAssociationHandler implements SimpleAssociation } } else { - IdentifierAccessor identifierAccessor = entities.getPersistentEntity(propertyValue.getClass()) - .getIdentifierAccessor(propertyValue); + PersistentEntity entity = entities.getRequiredPersistentEntity(propertyValue.getClass()); + IdentifierAccessor identifierAccessor = entity.getIdentifierAccessor(propertyValue); links.add(entityLinks.linkForSingleResource(propertyValue.getClass(), identifierAccessor.getIdentifier()) .withRel(propertyMapping.getRel())); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BackendIdHandlerMethodArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BackendIdHandlerMethodArgumentResolver.java index 47370c13d..457d2d08a 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BackendIdHandlerMethodArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/BackendIdHandlerMethodArgumentResolver.java @@ -19,12 +19,12 @@ import java.io.Serializable; import org.springframework.core.MethodParameter; import org.springframework.data.rest.core.mapping.ResourceMetadata; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.BaseUri; import org.springframework.data.rest.webmvc.config.ResourceMetadataHandlerMethodArgumentResolver; import org.springframework.data.rest.webmvc.spi.BackendIdConverter; import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter; import org.springframework.data.rest.webmvc.util.UriUtils; -import org.springframework.plugin.core.PluginRegistry; import org.springframework.util.Assert; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; @@ -39,7 +39,7 @@ import org.springframework.web.method.support.ModelAndViewContainer; */ public class BackendIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { - private final PluginRegistry> idConverters; + private final Java8PluginRegistry> idConverters; private final ResourceMetadataHandlerMethodArgumentResolver resourceMetadataResolver; private final BaseUri baseUri; @@ -51,7 +51,7 @@ public class BackendIdHandlerMethodArgumentResolver implements HandlerMethodArgu * @param resourceMetadataResolver the resolver to obtain {@link ResourceMetadata} from, must not be {@literal null}. * @param baseUri must not be {@literal null}. */ - public BackendIdHandlerMethodArgumentResolver(PluginRegistry> idConverters, + public BackendIdHandlerMethodArgumentResolver(Java8PluginRegistry> idConverters, ResourceMetadataHandlerMethodArgumentResolver resourceMetadataResolver, BaseUri baseUri) { Assert.notNull(idConverters, "Id converters must not be null!"); @@ -95,7 +95,8 @@ public class BackendIdHandlerMethodArgumentResolver implements HandlerMethodArgu throw new IllegalArgumentException("Could not obtain ResourceMetadata for request " + request); } - BackendIdConverter pluginFor = idConverters.getPluginFor(metadata.getDomainType(), DefaultIdConverter.INSTANCE); + BackendIdConverter pluginFor = idConverters.getPluginFor(metadata.getDomainType()) + .orElse(DefaultIdConverter.INSTANCE); String lookupPath = baseUri.getRepositoryLookupPath(request); return pluginFor.fromRequestId(UriUtils.findMappingVariable("id", parameter.getMethod(), lookupPath), metadata.getDomainType()); diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETag.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETag.java index a48f786ee..29ce1735c 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETag.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETag.java @@ -17,18 +17,23 @@ package org.springframework.data.rest.webmvc.support; import static org.springframework.util.StringUtils.*; +import lombok.EqualsAndHashCode; + +import java.util.Optional; + import org.springframework.data.mapping.PersistentEntity; +import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.PersistentPropertyAccessor; import org.springframework.data.rest.webmvc.PersistentEntityResource; import org.springframework.http.HttpHeaders; import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; /** * A value object to represent ETags. * * @author Oliver Gierke */ +@EqualsAndHashCode public final class ETag { public static final ETag NO_ETAG = new ETag(null); @@ -48,21 +53,28 @@ public final class ETag { * Creates a new {@link ETag} for the given {@link String} value. Falls back to {@link #NO_ETAG} in case * {@literal null} is provided. * - * @param value the source ETag value, can be {@literal null}. + * @param value the source ETag value, must not be {@literal null}. * @return */ public static ETag from(String value) { - return value == null ? NO_ETAG : new ETag(value); + return new ETag(value); + } + + public static ETag from(Optional value) { + return value.map(ETag::new).orElse(NO_ETAG); } /** * Creates a new {@link ETag} for the given {@link PersistentEntityResource}. * - * @param resource can be {@literal null}. + * @param resource must not be {@literal null}. * @return */ public static ETag from(PersistentEntityResource resource) { - return resource == null ? NO_ETAG : from(resource.getPersistentEntity(), resource.getContent()); + + Assert.notNull(resource, "PersistentEntityResource must not be null!"); + + return from(resource.getPersistentEntity(), resource.getContent()); } /** @@ -72,8 +84,8 @@ public final class ETag { * @param bean must not be {@literal null}. * @return */ - public static ETag from(PersistentEntity entity, Object bean) { - return from(getVersionInformation(entity, bean)); + public static ETag from(PersistentEntity> entity, Object bean) { + return getVersionInformation(entity, bean).map(ETag::from).orElse(NO_ETAG); } /** @@ -142,35 +154,6 @@ public final class ETag { return value == null ? null : "\"".concat(value).concat("\""); } - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (!(obj instanceof ETag)) { - return false; - } - - ETag that = (ETag) obj; - - return ObjectUtils.nullSafeEquals(this.value, that.value); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return value.hashCode(); - } - /** * Returns the quoted version property of a domain object, returns null if it doesn't contains the property * @@ -178,17 +161,16 @@ public final class ETag { * @param bean * @return */ - @SuppressWarnings("rawtypes") - private static String getVersionInformation(PersistentEntity entity, Object bean) { + private static Optional getVersionInformation(PersistentEntity> entity, + Object bean) { Assert.notNull(entity, "PersistentEntity must not be null!"); Assert.notNull(bean, "Target bean must not be null!"); - if (!entity.hasVersionProperty()) { - return null; - } - PersistentPropertyAccessor accessor = entity.getPropertyAccessor(bean); - return accessor.getProperty(entity.getVersionProperty()).toString(); + + return entity.getVersionProperty()// + .flatMap(it -> accessor.getProperty(it))// + .map(Object::toString); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETagArgumentResolver.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETagArgumentResolver.java index 891bc7a49..9ba48eac6 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETagArgumentResolver.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ETagArgumentResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,8 @@ package org.springframework.data.rest.webmvc.support; import static org.springframework.http.HttpHeaders.*; +import java.util.Optional; + import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; @@ -48,6 +50,6 @@ public class ETagArgumentResolver implements HandlerMethodArgumentResolver { @Override public ETag resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - return ETag.from(webRequest.getHeader(IF_MATCH)); + return ETag.from(Optional.ofNullable(webRequest.getHeader(IF_MATCH))); } } diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java index 7c0b3440e..a6b591fdb 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/RepositoryEntityLinks.java @@ -35,6 +35,7 @@ import org.springframework.data.rest.core.mapping.ResourceMapping; import org.springframework.data.rest.core.mapping.ResourceMappings; import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.core.mapping.SearchResourceMappings; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.BaseUri; import org.springframework.data.rest.webmvc.spi.BackendIdConverter; import org.springframework.data.rest.webmvc.spi.BackendIdConverter.DefaultIdConverter; @@ -47,7 +48,6 @@ import org.springframework.hateoas.TemplateVariable.VariableType; import org.springframework.hateoas.TemplateVariables; import org.springframework.hateoas.UriTemplate; import org.springframework.hateoas.core.AbstractEntityLinks; -import org.springframework.plugin.core.PluginRegistry; import org.springframework.util.Assert; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @@ -66,7 +66,7 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { private final @NonNull ResourceMappings mappings; private final @NonNull RepositoryRestConfiguration config; private final @NonNull PagingAndSortingTemplateVariables templateVariables; - private final @NonNull PluginRegistry> idConverters; + private final @NonNull Java8PluginRegistry> idConverters; /* * (non-Javadoc) @@ -135,7 +135,9 @@ public class RepositoryEntityLinks extends AbstractEntityLinks { Assert.isInstanceOf(Serializable.class, id, "Id must be assignable to Serializable!"); ResourceMetadata metadata = mappings.getMetadataFor(type); - String mappedId = idConverters.getPluginFor(type, DefaultIdConverter.INSTANCE).toRequestId((Serializable) id, type); + String mappedId = idConverters.getPluginFor(type)// + .orElse(DefaultIdConverter.INSTANCE)// + .toRequestId((Serializable) id, type); Link link = linkFor(type).slash(mappedId).withRel(metadata.getItemResourceRel()); return new Link(new UriTemplate(link.getHref(), getProjectionVariable(type)).toString(), diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AssociationLinksUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AssociationLinksUnitTests.java old mode 100644 new mode 100755 index b9e23b49b..fe91ab5ed --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AssociationLinksUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AssociationLinksUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Arrays; @@ -26,11 +25,10 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Reference; -import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; -import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; +import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.rest.core.Path; @@ -53,8 +51,8 @@ public class AssociationLinksUnitTests { Associations links; ResourceMappings mappings; - KeyValueMappingContext mappingContext; - KeyValuePersistentEntity entity; + KeyValueMappingContext mappingContext; + PersistentEntity entity; ResourceMetadata sampleResourceMetadata; @Mock RepositoryRestConfiguration config; @@ -62,8 +60,8 @@ public class AssociationLinksUnitTests { @Before public void setUp() { - this.mappingContext = new KeyValueMappingContext(); - this.entity = mappingContext.getPersistentEntity(Sample.class); + this.mappingContext = new KeyValueMappingContext<>(); + this.entity = mappingContext.getRequiredPersistentEntity(Sample.class); this.mappings = new PersistentEntitiesResourceMappings(new PersistentEntities(Arrays.asList(mappingContext))); this.links = new Associations(mappings, config); } @@ -79,37 +77,33 @@ public class AssociationLinksUnitTests { } @Test // DATAREST-262 - public void considersNullPropertyUnlinkable() { - assertThat(links.isLinkableAssociation((PersistentProperty) null), is(false)); + public void rejectsNullPropertyForIsLinkable() { + + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + links.isLinkableAssociation((PersistentProperty) null); + }); } @Test // DATAREST-262 public void consideredHiddenPropertyUnlinkable() { - assertThat(links.isLinkableAssociation(entity.getPersistentProperty("hiddenProperty")), is(false)); - } - - @Test // DATAREST-262 - public void considersUnexportedPropertyUnlinkable() { - - KeyValuePersistentProperty property = entity.getPersistentProperty("unexportedProperty"); - assertThat(links.isLinkableAssociation(property), is(false)); + assertThat(links.isLinkableAssociation(entity.getRequiredPersistentProperty("hiddenProperty"))).isFalse(); } @Test // DATAREST-262 public void createsLinkToAssociationProperty() { - PersistentProperty property = entity.getPersistentProperty("property"); - List associationLinks = links.getLinksFor(property.getAssociation(), new Path("/base")); + PersistentProperty property = entity.getRequiredPersistentProperty("property"); + List associationLinks = links.getLinksFor(property.getRequiredAssociation(), new Path("/base")); - assertThat(associationLinks, hasSize(1)); - assertThat(associationLinks, hasItem(new Link("/base/property", "property"))); + assertThat(associationLinks).hasSize(1); + assertThat(associationLinks).contains(new Link("/base/property", "property")); } @Test // DATAREST-262 public void doesNotCreateLinksForHiddenProperty() { - PersistentProperty property = entity.getPersistentProperty("hiddenProperty"); - assertThat(links.getLinksFor(property.getAssociation(), new Path("/sample")), hasSize(0)); + PersistentProperty property = entity.getRequiredPersistentProperty("hiddenProperty"); + assertThat(links.getLinksFor(property.getRequiredAssociation(), new Path("/sample"))).hasSize(0); } @Test @@ -117,12 +111,12 @@ public class AssociationLinksUnitTests { doReturn(true).when(config).isLookupType(Property.class); - assertThat(links.isLookupType(entity.getPersistentProperty("hiddenProperty")), is(true)); + assertThat(links.isLookupType(entity.getRequiredPersistentProperty("hiddenProperty"))).isTrue(); } @Test public void delegatesResourceMetadataLookupToMappings() { - assertThat(links.getMetadataFor(Property.class), is(mappings.getMetadataFor(Property.class))); + assertThat(links.getMetadataFor(Property.class)).isEqualTo(mappings.getMetadataFor(Property.class)); } public static class Sample { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AugmentingHandlerMappingUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AugmentingHandlerMappingUnitTests.java old mode 100644 new mode 100755 index 81a676e04..e5ef6e474 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AugmentingHandlerMappingUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/AugmentingHandlerMappingUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,11 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -66,7 +64,7 @@ public class AugmentingHandlerMappingUnitTests { Map handlerMethods = mapping.getHandlerMethods(); for (RequestMappingInfo info : handlerMethods.keySet()) { - assertThat(info.getPatternsCondition().getPatterns(), hasItem(Matchers.startsWith("/api"))); + assertThat(info.getPatternsCondition().getPatterns()).allMatch(it -> it.startsWith("/api")); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/BaseUriUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/BaseUriUnitTests.java old mode 100644 new mode 100755 index 14cacf48f..978283712 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/BaseUriUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/BaseUriUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import java.net.URI; @@ -32,8 +33,8 @@ public class BaseUriUnitTests { @Test // DATAREST-276 public void doesNotMatchNonOverlap() { - assertThat(new BaseUri(URI.create("foo")).getRepositoryLookupPath("/bar"), is(nullValue())); - assertThat(new BaseUri(URI.create("http://localhost:8080/foo/")).getRepositoryLookupPath("/bar"), is(nullValue())); + assertThat(new BaseUri(URI.create("foo")).getRepositoryLookupPath("/bar")).isNull(); + assertThat(new BaseUri(URI.create("http://localhost:8080/foo/")).getRepositoryLookupPath("/bar")).isNull(); } @Test // DATAREST-276 @@ -69,12 +70,12 @@ public class BaseUriUnitTests { assertThat(uri.getRepositoryLookupPath("/foo"), isEmptyString()); assertThat(uri.getRepositoryLookupPath("/foo/"), isEmptyString()); - assertThat(uri.getRepositoryLookupPath("/foo/people"), is("/people")); - assertThat(uri.getRepositoryLookupPath("/foo/people/"), is("/people")); + assertThat(uri.getRepositoryLookupPath("/foo/people")).isEqualTo("/people"); + assertThat(uri.getRepositoryLookupPath("/foo/people/")).isEqualTo("/people"); } @Test // DATAREST-674, SPR-13455 public void repositoryLookupPathHandlesDoubleSlashes() { - assertThat(BaseUri.NONE.getRepositoryLookupPath("/books//1"), is("/books/1")); + assertThat(BaseUri.NONE.getRepositoryLookupPath("/books//1")).isEqualTo("/books/1"); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomAcceptHeaderHttpServletRequestUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomAcceptHeaderHttpServletRequestUnitTests.java old mode 100644 new mode 100755 index 9ba98619e..025a49e6b --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomAcceptHeaderHttpServletRequestUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/CustomAcceptHeaderHttpServletRequestUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.Collections; @@ -52,7 +53,7 @@ public class CustomAcceptHeaderHttpServletRequestUnitTests { List expected = Collections.list(servletRequest.getHeaders(HttpHeaders.ACCEPT)); - assertThat(expected, hasSize(2)); - assertThat(expected, hasItems(MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_ATOM_XML_VALUE)); + assertThat(expected).hasSize(2); + assertThat(expected).contains(MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_ATOM_XML_VALUE); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/IncomingRequestUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/IncomingRequestUnitTests.java old mode 100644 new mode 100755 index 580441788..2294b4005 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/IncomingRequestUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/IncomingRequestUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; @@ -44,8 +43,8 @@ public class IncomingRequestUnitTests { IncomingRequest incomingRequest = new IncomingRequest(new ServletServerHttpRequest(request)); - assertThat(incomingRequest.isJsonPatchRequest(), is(true)); - assertThat(incomingRequest.isJsonMergePatchRequest(), is(false)); + assertThat(incomingRequest.isJsonPatchRequest()).isTrue(); + assertThat(incomingRequest.isJsonMergePatchRequest()).isFalse(); } @Test // DATAREST-498 @@ -55,7 +54,7 @@ public class IncomingRequestUnitTests { IncomingRequest incomingRequest = new IncomingRequest(new ServletServerHttpRequest(request)); - assertThat(incomingRequest.isJsonPatchRequest(), is(false)); - assertThat(incomingRequest.isJsonMergePatchRequest(), is(true)); + assertThat(incomingRequest.isJsonPatchRequest()).isFalse(); + assertThat(incomingRequest.isJsonMergePatchRequest()).isTrue(); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceUnitTests.java old mode 100644 new mode 100755 index e5144adbe..a0a7cac74 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/PersistentEntityResourceUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Collections; @@ -24,7 +23,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.mapping.PersistentEntity; import org.springframework.hateoas.Link; import org.springframework.hateoas.Resources; @@ -68,7 +67,7 @@ public class PersistentEntityResourceUnitTests { PersistentEntityResource resource = PersistentEntityResource.build(payload, entity).build(); - assertThat(resource.getEmbeddeds(), is(notNullValue())); - assertThat(resource.getEmbeddeds(), is(emptyIterable())); + assertThat(resource.getEmbeddeds()).isNotNull(); + assertThat(resource.getEmbeddeds()).isEmpty(); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryCorsConfigurationAccessorUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryCorsConfigurationAccessorUnitTests.java old mode 100644 new mode 100755 index 92764ee5f..b6b1d312d --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryCorsConfigurationAccessorUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryCorsConfigurationAccessorUnitTests.java @@ -15,20 +15,20 @@ */ package org.springframework.data.rest.webmvc; -import static java.util.Collections.*; -import static org.hamcrest.MatcherAssert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; +import java.util.Optional; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.repository.support.Repositories; -import org.springframework.data.rest.core.Path; import org.springframework.data.rest.core.mapping.ResourceMappings; -import org.springframework.data.rest.core.mapping.ResourceMetadata; import org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping.NoOpStringValueResolver; import org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping.RepositoryCorsConfigurationAccessor; import org.springframework.web.bind.annotation.CrossOrigin; @@ -53,7 +53,8 @@ public class RepositoryCorsConfigurationAccessorUnitTests { @Before public void before() throws Exception { - accessor = new RepositoryCorsConfigurationAccessor(mappings, NoOpStringValueResolver.INSTANCE, repositories); + accessor = new RepositoryCorsConfigurationAccessor(mappings, NoOpStringValueResolver.INSTANCE, + Optional.of(repositories)); } @Test // DATAREST-573 @@ -61,13 +62,13 @@ public class RepositoryCorsConfigurationAccessorUnitTests { CorsConfiguration configuration = accessor.createConfiguration(AnnotatedRepository.class); - assertThat(configuration, is(notNullValue())); - assertThat(configuration.getAllowCredentials(), is(true)); - assertThat(configuration.getAllowedHeaders(), hasItem("*")); - assertThat(configuration.getAllowedOrigins(), hasItem("*")); + assertThat(configuration).isNotNull(); + assertThat(configuration.getAllowCredentials()).isTrue(); + assertThat(configuration.getAllowedHeaders()).contains("*"); + assertThat(configuration.getAllowedOrigins()).contains("*"); assertThat(configuration.getAllowedMethods(), hasItems("OPTIONS", "HEAD", "GET", "PATCH", "POST", "PUT", "DELETE", "TRACE")); - assertThat(configuration.getMaxAge(), is(1800L)); + assertThat(configuration.getMaxAge()).isEqualTo(1800L); } @Test // DATAREST-573 @@ -75,30 +76,25 @@ public class RepositoryCorsConfigurationAccessorUnitTests { CorsConfiguration configuration = accessor.createConfiguration(FullyConfiguredCorsRepository.class); - assertThat(configuration, is(notNullValue())); - assertThat(configuration.getAllowCredentials(), is(true)); - assertThat(configuration.getAllowedHeaders(), hasItem("Content-type")); - assertThat(configuration.getExposedHeaders(), hasItem("Accept")); - assertThat(configuration.getAllowedOrigins(), hasItem("http://far.far.away")); - assertThat(configuration.getAllowedMethods(), hasItem("PATCH")); - assertThat(configuration.getAllowedMethods(), not(hasItem("DELETE"))); - assertThat(configuration.getAllowCredentials(), is(true)); - assertThat(configuration.getMaxAge(), is(1234L)); + assertThat(configuration).isNotNull(); + assertThat(configuration.getAllowCredentials()).isTrue(); + assertThat(configuration.getAllowedHeaders()).contains("Content-type"); + assertThat(configuration.getExposedHeaders()).contains("Accept"); + assertThat(configuration.getAllowedOrigins()).contains("http://far.far.away"); + assertThat(configuration.getAllowedMethods()).contains("PATCH"); + assertThat(configuration.getAllowedMethods()).doesNotContain("DELETE"); + assertThat(configuration.getAllowCredentials()).isTrue(); + assertThat(configuration.getMaxAge()).isEqualTo(1234L); } @Test // DATAREST-994 - public void returnsNullCorsConfigurationWithNullRepositories() { + public void returnsNoCorsConfigurationWithNoRepositories() { - accessor = new RepositoryCorsConfigurationAccessor(mappings, NoOpStringValueResolver.INSTANCE, null); - - ResourceMetadata resourceMetadata = mock(ResourceMetadata.class); - when(resourceMetadata.getPath()).thenReturn(new Path("/people")); - when(resourceMetadata.isExported()).thenReturn(true); + accessor = new RepositoryCorsConfigurationAccessor(mappings, NoOpStringValueResolver.INSTANCE, Optional.empty()); when(mappings.exportsTopLevelResourceFor("/people")).thenReturn(true); - when(mappings.iterator()).thenReturn(singletonList(resourceMetadata).iterator()); - assertThat(accessor.findCorsConfiguration("/people"), is(nullValue())); + assertThat(accessor.findCorsConfiguration("/people")).isEmpty(); } interface PlainRepository {} diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerUnitTests.java old mode 100644 new mode 100755 index 758bcf6d5..3c6b55293 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerUnitTests.java @@ -15,7 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.mockito.Matchers.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.ArrayList; @@ -23,12 +23,13 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; @@ -62,12 +63,12 @@ public class RepositoryPropertyReferenceControllerUnitTests { @Mock RepositoryInvoker invoker; @Mock ApplicationEventPublisher publisher; - KeyValueMappingContext mappingContext = new KeyValueMappingContext(); + KeyValueMappingContext mappingContext = new KeyValueMappingContext<>(); @Test // DATAREST-791 public void usesRepositoryInvokerToLookupRelatedInstance() throws Exception { - KeyValuePersistentEntity entity = mappingContext.getPersistentEntity(Sample.class); + KeyValuePersistentEntity entity = mappingContext.getRequiredPersistentEntity(Sample.class); ResourceMappings mappings = new PersistentEntitiesResourceMappings( new PersistentEntities(Collections.singleton(mappingContext))); @@ -79,8 +80,8 @@ public class RepositoryPropertyReferenceControllerUnitTests { controller.setApplicationEventPublisher(publisher); doReturn(invoker).when(invokerFactory).getInvokerFor(Reference.class); - doReturn(new Sample()).when(invoker).invokeFindOne(4711); - doReturn(new Reference()).when(invoker).invokeFindOne("some-id"); + doReturn(Optional.of(new Sample())).when(invoker).invokeFindOne(4711); + doReturn(Optional.of(new Reference())).when(invoker).invokeFindOne("some-id"); doReturn(new Sample()).when(invoker).invokeSave(any(Object.class)); RootResourceInformation information = new RootResourceInformation(metadata, entity, invoker); diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandlerUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandlerUnitTests.java old mode 100644 new mode 100755 index ebacb732d..7e418e497 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandlerUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandlerUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; @@ -63,7 +62,7 @@ public class RepositoryRestExceptionHandlerUnitTests { ResponseEntity result = HANDLER .handleNotReadable(new HttpMessageNotReadableException("Message!")); - assertThat(result.getStatusCode(), is(HttpStatus.BAD_REQUEST)); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test // DATAREST-507 @@ -71,7 +70,7 @@ public class RepositoryRestExceptionHandlerUnitTests { ResponseEntity result = HANDLER.handleConflict(new DataIntegrityViolationException("Message!")); - assertThat(result.getStatusCode(), is(HttpStatus.CONFLICT)); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); } @Test // DATAREST-706 @@ -81,7 +80,7 @@ public class RepositoryRestExceptionHandlerUnitTests { ResponseEntity result = HANDLER.handleMiscFailures(new Exception(message)); - assertThat(result.getBody(), is(notNullValue())); - assertThat(result.getBody().getMessage(), is(message)); + assertThat(result.getBody()).isNotNull(); + assertThat(result.getBody().getMessage()).isEqualTo(message); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingUnitTests.java old mode 100644 new mode 100755 index cd43863b0..547cf02bb --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMappingUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.lang.reflect.Method; @@ -25,7 +24,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.Sort; import org.springframework.data.repository.support.Repositories; import org.springframework.data.rest.core.config.EnumTranslationConfiguration; @@ -46,7 +45,7 @@ import org.springframework.web.method.HandlerMethod; * @author Oliver Gierke * @author Greg Turnquist */ -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class RepositoryRestHandlerMappingUnitTests { static final AnnotationConfigWebApplicationContext CONTEXT = new AnnotationConfigWebApplicationContext(); @@ -95,7 +94,7 @@ public class RepositoryRestHandlerMappingUnitTests { public void returnsNullForUriNotMapped() throws Exception { handlerMapping.afterPropertiesSet(); - assertThat(handlerMapping.lookupHandlerMethod("/foo", mockRequest), is(nullValue())); + assertThat(handlerMapping.lookupHandlerMethod("/foo", mockRequest)).isNull(); } @Test // DATAREST-111 @@ -107,8 +106,8 @@ public class RepositoryRestHandlerMappingUnitTests { handlerMapping.afterPropertiesSet(); HandlerMethod method = handlerMapping.lookupHandlerMethod("/people", mockRequest); - assertThat(method, is(notNullValue())); - assertThat(method.getMethod(), is(listEntitiesMethod)); + assertThat(method).isNotNull(); + assertThat(method.getMethod()).isEqualTo(listEntitiesMethod); } @Test // DATAREST-292 @@ -122,14 +121,13 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/base/people", mockRequest); - assertThat(method, is(notNullValue())); - assertThat(method.getMethod(), is(listEntitiesMethod)); + assertThat(method).isNotNull(); + assertThat(method.getMethod()).isEqualTo(listEntitiesMethod); } @Test // DATAREST-292 public void returnsRootHandlerMethodWithBaseUriConfigured() throws Exception { - when(mappings.exportsTopLevelResourceFor("/people")).thenReturn(true); mockRequest = new MockHttpServletRequest("GET", "/base"); configuration.setBasePath("/base"); @@ -137,8 +135,8 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/base", mockRequest); - assertThat(method, is(notNullValue())); - assertThat(method.getMethod(), is(rootHandlerMethod)); + assertThat(method).isNotNull(); + assertThat(method.getMethod()).isEqualTo(rootHandlerMethod); } @Test // DATAREST-276 @@ -152,8 +150,8 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/base/people/", mockRequest); - assertThat(method, is(notNullValue())); - assertThat(method.getMethod(), is(listEntitiesMethod)); + assertThat(method).isNotNull(); + assertThat(method.getMethod()).isEqualTo(listEntitiesMethod); } @Test // DATAREST-276 @@ -168,14 +166,13 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/base/people", mockRequest); - assertThat(method, is(notNullValue())); - assertThat(method.getMethod(), is(listEntitiesMethod)); + assertThat(method).isNotNull(); + assertThat(method.getMethod()).isEqualTo(listEntitiesMethod); } @Test // DATAREST-276 public void refrainsFromMappingIfTheRequestDoesNotPointIntoAbsolutelyDefinedUriSpace() throws Exception { - when(mappings.exportsTopLevelResourceFor("/people")).thenReturn(true); mockRequest = new MockHttpServletRequest("GET", "/servlet-path"); mockRequest.setServletPath("/servlet-path"); @@ -183,7 +180,7 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/servlet-path", mockRequest); - assertThat(method, is(nullValue())); + assertThat(method).isNull(); } @Test // DATAREST-276 @@ -200,7 +197,7 @@ public class RepositoryRestHandlerMappingUnitTests { HandlerMethod method = handlerMapping.lookupHandlerMethod("/people", mockRequest); - assertThat(method, is(nullValue())); + assertThat(method).isNull(); } @Test // DATAREST-609 @@ -210,7 +207,7 @@ public class RepositoryRestHandlerMappingUnitTests { mockRequest = new MockHttpServletRequest("GET", "/people{?projection}"); - assertThat(handlerMapping.getHandler(mockRequest), is(nullValue())); + assertThat(handlerMapping.getHandler(mockRequest)).isNull(); } @Test // DATAREST-994 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchesResourceUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchesResourceUnitTests.java old mode 100644 new mode 100755 index 52d098f04..7894f20a0 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchesResourceUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RepositorySearchesResourceUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; @@ -35,6 +34,6 @@ public class RepositorySearchesResourceUnitTests { @Test // DATAREST-515 public void returnsConfiguredDomainType() { - assertThat(new RepositorySearchesResource(String.class).getDomainType(), is(typeCompatibleWith(String.class))); + assertThat(new RepositorySearchesResource(String.class).getDomainType()).isAssignableFrom(String.class); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceStatusUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceStatusUnitTests.java old mode 100644 new mode 100755 index 910f8bb78..6227f30eb --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceStatusUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/ResourceStatusUnitTests.java @@ -15,23 +15,22 @@ */ package org.springframework.data.rest.webmvc; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import lombok.Value; +import java.util.function.Supplier; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Matchers; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Version; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; -import org.springframework.data.rest.core.util.Supplier; import org.springframework.data.rest.webmvc.ResourceStatus.StatusAndHeaders; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -45,7 +44,7 @@ import org.springframework.http.HttpStatus; public class ResourceStatusUnitTests { ResourceStatus status; - KeyValuePersistentEntity entity; + KeyValuePersistentEntity entity; @Mock HttpHeadersPreparer preparer; @Mock Supplier supplier; @@ -55,10 +54,10 @@ public class ResourceStatusUnitTests { this.status = ResourceStatus.of(preparer); - KeyValueMappingContext context = new KeyValueMappingContext(); - this.entity = context.getPersistentEntity(Sample.class); + KeyValueMappingContext context = new KeyValueMappingContext<>(); + this.entity = context.getRequiredPersistentEntity(Sample.class); - doReturn(new HttpHeaders()).when(preparer).prepareHeaders(eq(entity), Matchers.any()); + doReturn(new HttpHeaders()).when(preparer).prepareHeaders(eq(entity), any()); } @Test(expected = IllegalArgumentException.class) // DATAREST-835 @@ -83,22 +82,22 @@ public class ResourceStatusUnitTests { @Test // DATAREST-835 public void returnsNotModifiedIfEntityIsStillConsideredValid() { - doReturn(true).when(preparer).isObjectStillValid(Matchers.any(), Matchers.any(HttpHeaders.class)); + doReturn(true).when(preparer).isObjectStillValid(any(), any(HttpHeaders.class)); assertNotModified(status.getStatusAndHeaders(new HttpHeaders(), new Sample(0), entity)); } private void assertModified(StatusAndHeaders statusAndHeaders) { - assertThat(statusAndHeaders.isModified(), is(true)); - assertThat(statusAndHeaders.toResponseEntity(supplier).getStatusCode(), is(HttpStatus.OK)); + assertThat(statusAndHeaders.isModified()).isTrue(); + assertThat(statusAndHeaders.toResponseEntity(supplier).getStatusCode()).isEqualTo(HttpStatus.OK); verify(supplier).get(); } private void assertNotModified(StatusAndHeaders statusAndHeaders) { - assertThat(statusAndHeaders.isModified(), is(false)); - assertThat(statusAndHeaders.toResponseEntity(supplier).getStatusCode(), is(HttpStatus.NOT_MODIFIED)); + assertThat(statusAndHeaders.isModified()).isFalse(); + assertThat(statusAndHeaders.toResponseEntity(supplier).getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); } @Value diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationUnitTests.java old mode 100644 new mode 100755 index a8455f091..6ae1665f0 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/RootResourceInformationUnitTests.java @@ -25,7 +25,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.repository.support.RepositoryInvoker; diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/ArgumentResolverPagingAndSortingTemplateVariablesUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/ArgumentResolverPagingAndSortingTemplateVariablesUnitTests.java old mode 100644 new mode 100755 index 52e833bd8..c5764d543 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/ArgumentResolverPagingAndSortingTemplateVariablesUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/ArgumentResolverPagingAndSortingTemplateVariablesUnitTests.java @@ -15,16 +15,15 @@ */ package org.springframework.data.rest.webmvc.config; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.MethodParameter; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -63,19 +62,19 @@ public class ArgumentResolverPagingAndSortingTemplateVariablesUnitTests { PagingAndSortingTemplateVariables variables = new ArgumentResolverPagingAndSortingTemplateVariables( pageableResolver, sortResolver); - assertThat(variables.supportsParameter(getParameterMock(Pageable.class)), is(true)); - assertThat(variables.supportsParameter(getParameterMock(Sort.class)), is(true)); - assertThat(variables.supportsParameter(getParameterMock(Object.class)), is(false)); + assertThat(variables.supportsParameter(getParameterMock(Pageable.class))).isTrue(); + assertThat(variables.supportsParameter(getParameterMock(Sort.class))).isTrue(); + assertThat(variables.supportsParameter(getParameterMock(Object.class))).isFalse(); } @Test // DATAREST-467 public void forwardsEnhanceRequestForPageable() { - assertForwardsEnhanceFor(new PageRequest(0, 10), pageableResolver, sortResolver); + assertForwardsEnhanceFor(PageRequest.of(0, 10), pageableResolver, sortResolver); } @Test // DATAREST-467 public void forwardsEnhanceRequestForSort() { - assertForwardsEnhanceFor(new Sort("property"), sortResolver, pageableResolver); + assertForwardsEnhanceFor(Sort.by("property"), sortResolver, pageableResolver); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -97,6 +96,6 @@ public class ArgumentResolverPagingAndSortingTemplateVariablesUnitTests { verify(expected, times(1)).enhance(builder, null, value); verify(unexpected, times(0)).enhance(Mockito.any(UriComponentsBuilder.class), Mockito.any(MethodParameter.class), - anyObject()); + any()); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java old mode 100644 new mode 100755 index faf5e7996..f3d2c95ba --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/config/RepositoryRestMvConfigurationIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.config; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Collection; import java.util.Date; @@ -85,8 +84,8 @@ public class RepositoryRestMvConfigurationIntegrationTests { @Test // DATAREST-210 public void assertEnableHypermediaSupportWorkingCorrectly() { - assertThat(context.getBean("entityLinksPluginRegistry"), is(notNullValue())); - assertThat(context.getBean(LinkDiscoverers.class), is(notNullValue())); + assertThat(context.getBean("entityLinksPluginRegistry")).isNotNull(); + assertThat(context.getBean(LinkDiscoverers.class)).isNotNull(); } @Test @@ -107,15 +106,15 @@ public class RepositoryRestMvConfigurationIntegrationTests { .getBean(HateoasPageableHandlerMethodArgumentResolver.class); UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); - resolver.enhance(builder, null, new PageRequest(0, 9000, Direction.ASC, "firstname")); + resolver.enhance(builder, null, PageRequest.of(0, 9000, Direction.ASC, "firstname")); MultiValueMap params = builder.build().getQueryParams(); - assertThat(params.containsKey("myPage"), is(true)); - assertThat(params.containsKey("mySort"), is(true)); + assertThat(params.containsKey("myPage")).isTrue(); + assertThat(params.containsKey("mySort")).isTrue(); - assertThat(params.get("mySize"), hasSize(1)); - assertThat(params.get("mySize").get(0), is("7000")); + assertThat(params.get("mySize")).hasSize(1); + assertThat(params.get("mySize").get(0)).isEqualTo("7000"); } @Test // DATAREST-336 @@ -131,8 +130,8 @@ public class RepositoryRestMvConfigurationIntegrationTests { formatter.setTimeZone(TimeZone.getTimeZone("UTC")); Object result = JsonPath.read(mapper.writeValueAsString(sample), "$.date"); - assertThat(result, is(instanceOf(String.class))); - assertThat(result, is((Object) formatter.print(sample.date, Locale.US))); + assertThat(result).isInstanceOf(String.class); + assertThat(result).isEqualTo(formatter.print(sample.date, Locale.US)); } @Test(expected = NoSuchBeanDefinitionException.class) // DATAREST-362 @@ -146,10 +145,10 @@ public class RepositoryRestMvConfigurationIntegrationTests { Collection converters = context .getBeansOfType(MappingJackson2HttpMessageConverter.class).values(); - for (HttpMessageConverter converter : converters) { - assertThat(converter, is(anyOf(instanceOf(TypeConstrainedMappingJackson2HttpMessageConverter.class), - instanceOf(AlpsJsonHttpMessageConverter.class)))); - } + converters.forEach(converter -> { + assertThat(converter).isInstanceOfAny(TypeConstrainedMappingJackson2HttpMessageConverter.class, + AlpsJsonHttpMessageConverter.class); + }); } @Test // DATAREST-424 @@ -158,8 +157,8 @@ public class RepositoryRestMvConfigurationIntegrationTests { CollectingComponent component = context.getBean(CollectingComponent.class); List> converters = component.converters; - assertThat(converters.get(0).getSupportedMediaTypes(), hasItem(MediaTypes.HAL_JSON)); - assertThat(converters.get(1).getSupportedMediaTypes(), hasItem(RestMediaTypes.SCHEMA_JSON)); + assertThat(converters.get(0).getSupportedMediaTypes()).contains(MediaTypes.HAL_JSON); + assertThat(converters.get(1).getSupportedMediaTypes()).contains(RestMediaTypes.SCHEMA_JSON); } @Test // DATAREST-424 @@ -171,8 +170,8 @@ public class RepositoryRestMvConfigurationIntegrationTests { List> converters = component.converters; - assertThat(converters.get(0).getSupportedMediaTypes(), hasItem(RestMediaTypes.SCHEMA_JSON)); - assertThat(converters.get(1).getSupportedMediaTypes(), hasItem(MediaTypes.HAL_JSON)); + assertThat(converters.get(0).getSupportedMediaTypes()).contains(RestMediaTypes.SCHEMA_JSON); + assertThat(converters.get(1).getSupportedMediaTypes()).contains(MediaTypes.HAL_JSON); } @Test // DATAREST-431, DATACMNS-626 @@ -180,10 +179,10 @@ public class RepositoryRestMvConfigurationIntegrationTests { ConversionService service = context.getBean("defaultConversionService", ConversionService.class); - assertThat(service.canConvert(String.class, Point.class), is(true)); - assertThat(service.canConvert(Point.class, String.class), is(true)); - assertThat(service.canConvert(String.class, Distance.class), is(true)); - assertThat(service.canConvert(Distance.class, String.class), is(true)); + assertThat(service.canConvert(String.class, Point.class)).isTrue(); + assertThat(service.canConvert(Point.class, String.class)).isTrue(); + assertThat(service.canConvert(String.class, Distance.class)).isTrue(); + assertThat(service.canConvert(Distance.class, String.class)).isTrue(); } @Test // DATAREST-686 @@ -193,7 +192,7 @@ public class RepositoryRestMvConfigurationIntegrationTests { MessageSourceAccessor.class); Object messageSource = ReflectionTestUtils.getField(accessor, "messageSource"); - assertThat((String) ReflectionTestUtils.getField(messageSource, "defaultEncoding"), is("UTF-8")); + assertThat((String) ReflectionTestUtils.getField(messageSource, "defaultEncoding")).isEqualTo("UTF-8"); } @Configuration diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/DomainObjectReaderUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/DomainObjectReaderUnitTests.java old mode 100644 new mode 100755 index 2527ca50e..899964271 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/DomainObjectReaderUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/DomainObjectReaderUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc.json; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import lombok.AllArgsConstructor; @@ -42,7 +43,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.ReadOnlyProperty; @@ -82,7 +83,7 @@ public class DomainObjectReaderUnitTests { @Before public void setUp() { - KeyValueMappingContext mappingContext = new KeyValueMappingContext(); + KeyValueMappingContext mappingContext = new KeyValueMappingContext<>(); mappingContext.getPersistentEntity(SampleUser.class); mappingContext.getPersistentEntity(Person.class); mappingContext.getPersistentEntity(TypeWithGenericMap.class); @@ -112,8 +113,8 @@ public class DomainObjectReaderUnitTests { SampleUser result = reader.readPut((ObjectNode) node, user, new ObjectMapper()); - assertThat(result.name, is(nullValue())); - assertThat(result.password, is("password")); + assertThat(result.name).isNull(); + assertThat(result.password).isEqualTo("password"); } @Test // DATAREST-556 @@ -126,8 +127,8 @@ public class DomainObjectReaderUnitTests { Person result = reader.readPut((ObjectNode) node, new Person("Dave", "Matthews"), mapper); - assertThat(result.firstName, is("Carter")); - assertThat(result.lastName, is("Beauford")); + assertThat(result.firstName).isEqualTo("Carter"); + assertThat(result.lastName).isEqualTo("Beauford"); } @Test // DATAREST-605 @@ -142,8 +143,8 @@ public class DomainObjectReaderUnitTests { SampleUser result = reader.readPut((ObjectNode) node, user, new ObjectMapper()); // Assert that the nested Map values also consider ignored properties - assertThat(result.relatedUsers.get("parent").password, is("password")); - assertThat(result.relatedUsers.get("parent").name, is("Oliver")); + assertThat(result.relatedUsers.get("parent").password).isEqualTo("password"); + assertThat(result.relatedUsers.get("parent").name).isEqualTo("Oliver"); } @Test // DATAREST-701 @@ -159,11 +160,11 @@ public class DomainObjectReaderUnitTests { TypeWithGenericMap result = reader.readPut((ObjectNode) node, target, mapper); - assertThat(result.map.get("a"), is((Object) "1")); + assertThat(result.map.get("a")).isEqualTo((Object) "1"); Object object = result.map.get("b"); - assertThat(object, is(instanceOf(Map.class))); - assertThat(((Map) object).get("c"), is((Object) "2")); + assertThat(object).isInstanceOf(Map.class); + assertThat(((Map) object).get("c")).isEqualTo((Object) "2"); } @Test(expected = IllegalArgumentException.class) // DATAREST-701 @@ -188,10 +189,10 @@ public class DomainObjectReaderUnitTests { VersionedType result = reader.readPut(node, type, mapper); - assertThat(result.lastname, is("Matthews")); - assertThat(result.firstname, is(nullValue())); - assertThat(result.id, is(1L)); - assertThat(result.version, is(1L)); + assertThat(result.lastname).isEqualTo("Matthews"); + assertThat(result.firstname).isNull(); + assertThat(result.id).isEqualTo(1L); + assertThat(result.version).isEqualTo(1L); } @Test // DATAREST-873 @@ -205,7 +206,7 @@ public class DomainObjectReaderUnitTests { SampleWithCreatedDate sample = new SampleWithCreatedDate(); sample.createdDate = reference; - assertThat(reader.readPut(node, sample, mapper).createdDate, is(reference)); + assertThat(reader.readPut(node, sample, mapper).createdDate).isEqualTo(reference); } @Test // DATAREST-931 @@ -222,7 +223,7 @@ public class DomainObjectReaderUnitTests { User result = reader.read(source, user, new ObjectMapper()); - assertThat(result.phones.get(0).creationDate, is(notNullValue())); + assertThat(result.phones.get(0).creationDate).isNotNull(); } @Test // DATAREST-919 @@ -249,18 +250,18 @@ public class DomainObjectReaderUnitTests { TypeWithGenericMap result = reader.readPut(payload, map, mapper); - assertThat(result.map.get("sub1"), is((Object) "ok")); + assertThat(result.map.get("sub1")).isEqualTo((Object) "ok"); List sub2 = as(result.map.get("sub2"), List.class); - assertThat(sub2.get(0), is("ok1")); - assertThat(sub2.get(1), is("ok2")); + assertThat(sub2.get(0)).isEqualTo("ok1"); + assertThat(sub2.get(1)).isEqualTo("ok2"); List> sub3 = as(result.map.get("sub3"), List.class); - assertThat(sub3.get(0).get("childOk1"), is("ok")); + assertThat(sub3.get(0).get("childOk1")).isEqualTo("ok"); Map sub4 = as(result.map.get("sub4"), Map.class); - assertThat(sub4.get("c1"), is("v1")); - assertThat(sub4.get("c2"), is("new")); + assertThat(sub4.get("c1")).isEqualTo("v1"); + assertThat(sub4.get("c2")).isEqualTo("new"); } @Test // DATAREST-938 @@ -279,11 +280,11 @@ public class DomainObjectReaderUnitTests { Outer result = reader.doMerge((ObjectNode) node, outer, new ObjectMapper()); - assertThat(result, is(sameInstance(outer))); - assertThat(result.prop, is("else")); - assertThat(result.inner.prop, is("something")); - assertThat(result.inner.name, is("new inner name")); - assertThat(result.inner, is(sameInstance(inner))); + assertThat(result).isSameAs(outer); + assertThat(result.prop).isEqualTo("else"); + assertThat(result.inner.prop).isEqualTo("something"); + assertThat(result.inner.name).isEqualTo("new inner name"); + assertThat(result.inner).isSameAs(inner); } @Test // DATAREST-937 @@ -297,8 +298,8 @@ public class DomainObjectReaderUnitTests { SampleWithTransient result = reader.readPut((ObjectNode) node, sample, new ObjectMapper()); - assertThat(result.name, is("new name")); - assertThat(result.temporary, is("new temp")); + assertThat(result.name).isEqualTo("new name"); + assertThat(result.temporary).isEqualTo("new temp"); } @Test // DATAREST-953 @@ -315,7 +316,7 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items.get(0).some, is("value")); + assertThat(result.inner.items.get(0).some).isEqualTo("value"); } @Test // DATAREST-956 @@ -333,10 +334,10 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items.size(), is(3)); - assertThat(result.inner.items.get(0).some, is("value1")); - assertThat(result.inner.items.get(1).some, is("value2")); - assertThat(result.inner.items.get(2).some, is("value3")); + assertThat(result.inner.items).hasSize(3); + assertThat(result.inner.items.get(0).some).isEqualTo("value1"); + assertThat(result.inner.items.get(1).some).isEqualTo("value2"); + assertThat(result.inner.items.get(2).some).isEqualTo("value3"); } @Test // DATAREST-956 @@ -355,8 +356,8 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items.size(), is(1)); - assertThat(result.inner.items.get(0).some, is("value")); + assertThat(result.inner.items).hasSize(1); + assertThat(result.inner.items.get(0).some).isEqualTo("value"); } @Test // DATAREST-959 @@ -370,8 +371,8 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items.size(), is(1)); - assertThat(result.inner.items.get(0).some, is("value")); + assertThat(result.inner.items).hasSize(1); + assertThat(result.inner.items.get(0).some).isEqualTo("value"); } @Test // DATAREST-959 @@ -386,14 +387,14 @@ public class DomainObjectReaderUnitTests { .readTree("{ \"inner\" : { \"object\" : [ { \"some\" : \"value\" }, { \"some\" : \"otherValue\" } ] } }"); Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.object, is(instanceOf(Collection.class))); + assertThat(result.inner.object).isInstanceOf(Collection.class); Collection collection = (Collection) result.inner.object; - assertThat(collection.size(), is(2)); + assertThat(collection).hasSize(2); Iterator> iterator = (Iterator>) collection.iterator(); - assertThat(iterator.next().get("some"), is((Object) "value")); - assertThat(iterator.next().get("some"), is((Object) "otherValue")); + assertThat(iterator.next().get("some")).isEqualTo((Object) "value"); + assertThat(iterator.next().get("some")).isEqualTo((Object) "otherValue"); } @Test // DATAREST-965 @@ -411,8 +412,8 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items, is(nullValue())); - assertThat((String) result.inner.object, is("value")); + assertThat(result.inner.items).isNull(); + assertThat((String) result.inner.object).isEqualTo("value"); } @Test // DATAREST-965 @@ -428,9 +429,9 @@ public class DomainObjectReaderUnitTests { Parent result = reader.readPut((ObjectNode) node, source, new ObjectMapper()); - assertThat(result.inner.items.size(), is(1)); - assertThat(result.inner.items.get(0).some, is("value")); - assertThat(result.inner.object, is(nullValue())); + assertThat(result.inner.items).hasSize(1); + assertThat(result.inner.items.get(0).some).isEqualTo("value"); + assertThat(result.inner.object).isNull(); } @Test // DATAREST-986 @@ -442,8 +443,8 @@ public class DomainObjectReaderUnitTests { Product result = reader.readPut((ObjectNode) node, new Product(), mapper); - assertThat(result.map.get(Locale.ENGLISH), is(new LocalizedValue("eventual"))); - assertThat(result.map.get(Locale.GERMAN), is(new LocalizedValue("schlussendlich"))); + assertThat(result.map.get(Locale.ENGLISH)).isEqualTo(new LocalizedValue("eventual")); + assertThat(result.map.get(Locale.GERMAN)).isEqualTo(new LocalizedValue("schlussendlich")); } @Test // DATAREST-987 @@ -478,8 +479,8 @@ public class DomainObjectReaderUnitTests { SampleWithReference result = reader.mergeForPut(source, target, new ObjectMapper()); - assertThat(result.nested, is(source.nested)); - assertThat(result.nested == originalCollection, is(false)); + assertThat(result.nested).isEqualTo(source.nested); + assertThat(result.nested == originalCollection).isFalse(); } @Test // DATAREST-944 @@ -492,14 +493,14 @@ public class DomainObjectReaderUnitTests { SampleWithReference result = reader.mergeForPut(source, target, new ObjectMapper()); - assertThat(result.nested, is(source.nested)); - assertThat(result.nested == originalCollection, is(true)); + assertThat(result.nested).isEqualTo(source.nested); + assertThat(result.nested).isSameAs(originalCollection); } @SuppressWarnings("unchecked") private static T as(Object source, Class type) { - assertThat(source, is(instanceOf(type))); + assertThat(source).isInstanceOf(type); return (T) source; } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/EnumTranslatorUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/EnumTranslatorUnitTests.java old mode 100644 new mode 100755 index 8719e2812..1d0253361 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/EnumTranslatorUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/EnumTranslatorUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Locale; @@ -54,17 +53,17 @@ public class EnumTranslatorUnitTests { @Test // DATAREST-654 public void parsesNullForNullSource() { - assertThat(configuration.fromText(MyEnum.class, null), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, null)).isNull(); } @Test // DATAREST-654 public void parsesNullForEmptySource() { - assertThat(configuration.fromText(MyEnum.class, null), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, null)).isNull(); } @Test // DATAREST-654 public void parsesNullForUnknownValue() { - assertThat(configuration.fromText(MyEnum.class, "Foobar"), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, "Foobar")).isNull(); } @Test // DATAREST-654 @@ -72,13 +71,13 @@ public class EnumTranslatorUnitTests { configuration.setEnableDefaultTranslation(false); - assertThat(configuration.asText(MyEnum.SECOND_VALUE), is(MyEnum.SECOND_VALUE.name())); + assertThat(configuration.asText(MyEnum.SECOND_VALUE)).isEqualTo(MyEnum.SECOND_VALUE.name()); } @Test // DATAREST-654 public void returnsDefaultTranslationByDefault() { - assertThat(configuration.asText(MyEnum.SECOND_VALUE), is("Second value")); + assertThat(configuration.asText(MyEnum.SECOND_VALUE)).isEqualTo("Second value"); } @Test // DATAREST-654 @@ -86,14 +85,14 @@ public class EnumTranslatorUnitTests { configuration.setEnableDefaultTranslation(false); - assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE"), is(MyEnum.FIRST_VALUE)); + assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE")).isEqualTo(MyEnum.FIRST_VALUE); } @Test // DATAREST-654 public void parsesStandardTranslationAndEnumNameByDefault() { - assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE"), is(MyEnum.FIRST_VALUE)); - assertThat(configuration.fromText(MyEnum.class, "Second value"), is(MyEnum.SECOND_VALUE)); + assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE")).isEqualTo(MyEnum.FIRST_VALUE); + assertThat(configuration.fromText(MyEnum.class, "Second value")).isEqualTo(MyEnum.SECOND_VALUE); } @Test // DATAREST-654 @@ -104,22 +103,22 @@ public class EnumTranslatorUnitTests { messageSource.addMessage(MyEnum.class.getName().concat(".").concat(MyEnum.FIRST_VALUE.name()), Locale.US, "Translated"); - assertThat(configuration.asText(MyEnum.FIRST_VALUE), is("Translated")); + assertThat(configuration.asText(MyEnum.FIRST_VALUE)).isEqualTo("Translated"); } @Test // DATAREST-654 public void parsesEnumNameByDefaultEvenIfMessageDefined() { // Parses resolved message and enum name - assertThat(configuration.fromText(MyEnum.class, "Translated"), is(MyEnum.FIRST_VALUE)); - assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE"), is(MyEnum.FIRST_VALUE)); + assertThat(configuration.fromText(MyEnum.class, "Translated")).isEqualTo(MyEnum.FIRST_VALUE); + assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE")).isEqualTo(MyEnum.FIRST_VALUE); // Does not parse default translation as explicit translation is available - assertThat(configuration.fromText(MyEnum.class, "First value"), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, "First value")).isNull(); // Parses default translation as no explicit translation is available - assertThat(configuration.fromText(MyEnum.class, "Second value"), is(MyEnum.SECOND_VALUE)); - assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE"), is(MyEnum.SECOND_VALUE)); + assertThat(configuration.fromText(MyEnum.class, "Second value")).isEqualTo(MyEnum.SECOND_VALUE); + assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE")).isEqualTo(MyEnum.SECOND_VALUE); } @Test // DATAREST-654 @@ -128,8 +127,8 @@ public class EnumTranslatorUnitTests { configuration.setEnableDefaultTranslation(false); // Parses default translation as no explicit translation is available - assertThat(configuration.fromText(MyEnum.class, "Second value"), is(nullValue())); - assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE"), is(MyEnum.SECOND_VALUE)); + assertThat(configuration.fromText(MyEnum.class, "Second value")).isNull(); + assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE")).isEqualTo(MyEnum.SECOND_VALUE); } @Test @@ -138,12 +137,12 @@ public class EnumTranslatorUnitTests { configuration.setParseEnumNameAsFallback(false); // Parses resolved message and enum name - assertThat(configuration.fromText(MyEnum.class, "Translated"), is(MyEnum.FIRST_VALUE)); - assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE"), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, "Translated")).isEqualTo(MyEnum.FIRST_VALUE); + assertThat(configuration.fromText(MyEnum.class, "FIRST_VALUE")).isNull(); // Parses default translation as no explicit translation is available - assertThat(configuration.fromText(MyEnum.class, "Second value"), is(MyEnum.SECOND_VALUE)); - assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE"), is(nullValue())); + assertThat(configuration.fromText(MyEnum.class, "Second value")).isEqualTo(MyEnum.SECOND_VALUE); + assertThat(configuration.fromText(MyEnum.class, "SECOND_VALUE")).isNull(); } static enum MyEnum { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonMetadataUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonMetadataUnitTests.java old mode 100644 new mode 100755 index 6dba244fd..f38b4ba70 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonMetadataUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonMetadataUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.io.IOException; @@ -51,7 +50,7 @@ public class JacksonMetadataUnitTests { @Before public void setUp() { - this.context = new KeyValueMappingContext(); + this.context = new KeyValueMappingContext<>(); this.mapper = new ObjectMapper(); this.mapper.disable(MapperFeature.INFER_PROPERTY_MUTATORS); @@ -62,11 +61,11 @@ public class JacksonMetadataUnitTests { JacksonMetadata metadata = new JacksonMetadata(mapper, User.class); - PersistentEntity entity = context.getPersistentEntity(User.class); - PersistentProperty property = entity.getPersistentProperty("username"); + PersistentEntity entity = context.getRequiredPersistentEntity(User.class); + PersistentProperty property = entity.getRequiredPersistentProperty("username"); - assertThat(metadata.isExported(property), is(true)); - assertThat(metadata.isReadOnly(property), is(true)); + assertThat(metadata.isExported(property)).isTrue(); + assertThat(metadata.isReadOnly(property)).isTrue(); } @Test // DATAREST-644 @@ -74,10 +73,10 @@ public class JacksonMetadataUnitTests { JacksonMetadata metadata = new JacksonMetadata(mapper, Value.class); - PersistentEntity entity = context.getPersistentEntity(Value.class); - PersistentProperty property = entity.getPersistentProperty("value"); + PersistentEntity entity = context.getRequiredPersistentEntity(Value.class); + PersistentProperty property = entity.getRequiredPersistentProperty("value"); - assertThat(metadata.isReadOnly(property), is(false)); + assertThat(metadata.isReadOnly(property)).isFalse(); } @Test // DATAREST-644 @@ -86,7 +85,7 @@ public class JacksonMetadataUnitTests { JsonSerializer serializer = new JacksonMetadata(new ObjectMapper(), SomeBean.class) .getTypeSerializer(SomeBean.class); - assertThat(serializer, is(instanceOf(SomeBeanSerializer.class))); + assertThat(serializer).isInstanceOf(SomeBeanSerializer.class); } static class User { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonSerializersUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonSerializersUnitTests.java old mode 100644 new mode 100755 index 702100b73..12b1935dd --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonSerializersUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JacksonSerializersUnitTests.java @@ -15,8 +15,9 @@ */ package org.springframework.data.rest.webmvc.json; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.Collection; @@ -53,7 +54,7 @@ public class JacksonSerializersUnitTests { Sample result = mapper.readValue("{ \"property\" : \"value\"}", Sample.class); - assertThat(result.property, is(SampleEnum.VALUE)); + assertThat(result.property).isEqualTo(SampleEnum.VALUE); } @Test // DATAREST-929 @@ -61,7 +62,7 @@ public class JacksonSerializersUnitTests { Sample result = mapper.readValue("{ \"collection\" : [ \"value\" ] }", Sample.class); - assertThat(result.collection, hasItem(SampleEnum.VALUE)); + assertThat(result.collection).contains(SampleEnum.VALUE); } @Test // DATAREST-929 @@ -77,7 +78,7 @@ public class JacksonSerializersUnitTests { Sample result = mapper.readValue("{ \"mapToEnum\" : { \"foo\" : \"value\" } }", Sample.class); - assertThat(result.mapToEnum.get("foo"), is(SampleEnum.VALUE)); + assertThat(result.mapToEnum.get("foo")).isEqualTo(SampleEnum.VALUE); } static class Sample { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JsonSchemaUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JsonSchemaUnitTests.java old mode 100644 new mode 100755 index 95a8ad0d7..8493a5d7a --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JsonSchemaUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/JsonSchemaUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.data.rest.webmvc.json.JsonSchema.JsonSchemaProperty; @@ -37,7 +36,7 @@ public class JsonSchemaUnitTests { JsonSchemaProperty property = new JsonSchemaProperty("foo", null, "bar", false); - assertThat(property.with(type.getProperty("foo")).type, is("number")); + assertThat(property.with(type.getRequiredProperty("foo")).type).isEqualTo("number"); } static class Sample { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappedPropertiesUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappedPropertiesUnitTests.java old mode 100644 new mode 100755 index 6d20a72f9..3077e6903 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappedPropertiesUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappedPropertiesUnitTests.java @@ -15,13 +15,12 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.data.annotation.Transient; -import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; +import org.springframework.data.mapping.PersistentEntity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -35,37 +34,37 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class MappedPropertiesUnitTests { ObjectMapper mapper = new ObjectMapper(); - KeyValueMappingContext context = new KeyValueMappingContext(); - KeyValuePersistentEntity entity = context.getPersistentEntity(Sample.class); + KeyValueMappingContext context = new KeyValueMappingContext<>(); + PersistentEntity entity = context.getRequiredPersistentEntity(Sample.class); MappedProperties properties = MappedProperties.fromJacksonProperties(entity, mapper); @Test // DATAREST-575 public void doesNotExposeMappedPropertyForNonSpringDataPersistentProperty() { - assertThat(properties.hasPersistentPropertyForField("notExposedBySpringData"), is(false)); - assertThat(properties.getPersistentProperty("notExposedBySpringData"), is(nullValue())); + assertThat(properties.hasPersistentPropertyForField("notExposedBySpringData")).isFalse(); + assertThat(properties.getPersistentProperty("notExposedBySpringData")).isNull(); } @Test // DATAREST-575 public void doesNotExposeMappedPropertyForNonJacksonProperty() { - assertThat(properties.hasPersistentPropertyForField("notExposedByJackson"), is(false)); - assertThat(properties.getPersistentProperty("notExposedByJackson"), is(nullValue())); + assertThat(properties.hasPersistentPropertyForField("notExposedByJackson")).isFalse(); + assertThat(properties.getPersistentProperty("notExposedByJackson")).isNull(); } @Test // DATAREST-575 public void exposesProperty() { - assertThat(properties.hasPersistentPropertyForField("exposedProperty"), is(true)); - assertThat(properties.getPersistentProperty("exposedProperty"), is(notNullValue())); + assertThat(properties.hasPersistentPropertyForField("exposedProperty")).isTrue(); + assertThat(properties.getPersistentProperty("exposedProperty")).isNotNull(); } @Test // DATAREST-575 public void exposesRenamedPropertyByExternalName() { - assertThat(properties.hasPersistentPropertyForField("email"), is(true)); - assertThat(properties.getPersistentProperty("email"), is(notNullValue())); - assertThat(properties.getMappedName(entity.getPersistentProperty("emailAddress")), is("email")); + assertThat(properties.hasPersistentPropertyForField("email")).isTrue(); + assertThat(properties.getPersistentProperty("email")).isNotNull(); + assertThat(properties.getMappedName(entity.getRequiredPersistentProperty("emailAddress"))).isEqualTo("email"); } static class Sample { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolverUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolverUnitTests.java old mode 100644 new mode 100755 index b065762bd..d9c370d41 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolverUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/MappingAwarePageableArgumentResolverUnitTests.java @@ -15,15 +15,14 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.MethodParameter; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -59,31 +58,31 @@ public class MappingAwarePageableArgumentResolverUnitTests { @Test // DATAREST-906 public void resolveArgumentShouldReturnTranslatedPageable() throws Exception { - Sort translated = new Sort("world"); - Pageable pageable = new PageRequest(0, 1, Direction.ASC, "hello"); + Sort translated = Sort.by("world"); + Pageable pageable = PageRequest.of(0, 1, Direction.ASC, "hello"); when(delegate.resolveArgument(parameter, modelAndViewContainer, webRequest, binderFactory)).thenReturn(pageable); when(translator.translateSort(pageable.getSort(), parameter, webRequest)).thenReturn(translated); Pageable result = resolver.resolveArgument(parameter, modelAndViewContainer, webRequest, binderFactory); - assertThat(result.getPageSize(), is(1)); - assertThat(result.getPageNumber(), is(0)); - assertThat(result.getSort(), is(equalTo(translated))); + assertThat(result.getPageSize()).isEqualTo(1); + assertThat(result.getPageNumber()).isEqualTo(0); + assertThat(result.getSort()).isEqualTo(translated); } @Test // DATAREST-906 public void resolveArgumentShouldReturnPageableWithoutSort() throws Exception { - Pageable pageable = new PageRequest(0, 1); + Pageable pageable = PageRequest.of(0, 1); when(delegate.resolveArgument(parameter, modelAndViewContainer, webRequest, binderFactory)).thenReturn(pageable); Pageable result = resolver.resolveArgument(parameter, modelAndViewContainer, webRequest, binderFactory); - assertThat(result.getPageSize(), is(1)); - assertThat(result.getPageNumber(), is(0)); - assertThat(result.getSort(), is(nullValue())); + assertThat(result.getPageSize()).isEqualTo(1); + assertThat(result.getPageNumber()).isEqualTo(0); + assertThat(result.getSort()).isNull(); } @Test // DATAREST-906 @@ -91,6 +90,6 @@ public class MappingAwarePageableArgumentResolverUnitTests { Pageable result = resolver.resolveArgument(parameter, modelAndViewContainer, webRequest, binderFactory); - assertThat(result, is(nullValue())); + assertThat(result).isNull(); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2ModuleUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2ModuleUnitTests.java old mode 100644 new mode 100755 index b614c8aa7..6e4c15e03 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2ModuleUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/PersistentEntityJackson2ModuleUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.io.IOException; @@ -28,7 +27,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.convert.TypeDescriptor; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; import org.springframework.data.mapping.PersistentProperty; @@ -36,8 +35,8 @@ import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.repository.support.RepositoryInvokerFactory; import org.springframework.data.rest.core.UriToEntityConverter; import org.springframework.data.rest.core.mapping.ResourceMappings; -import org.springframework.data.rest.core.support.EntityLookup; import org.springframework.data.rest.core.support.SelfLinkProvider; +import org.springframework.data.rest.core.util.Java8PluginRegistry; import org.springframework.data.rest.webmvc.EmbeddedResourcesAssembler; import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.AssociationOmittingSerializerModifier; import org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module.AssociationUriResolvingDeserializerModifier; @@ -49,7 +48,6 @@ import org.springframework.hateoas.EntityLinks; import org.springframework.hateoas.ResourceProcessor; import org.springframework.hateoas.UriTemplate; import org.springframework.hateoas.mvc.ResourceProcessorInvoker; -import org.springframework.plugin.core.OrderAwarePluginRegistry; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -78,7 +76,7 @@ public class PersistentEntityJackson2ModuleUnitTests { @Before public void setUp() { - KeyValueMappingContext mappingContext = new KeyValueMappingContext(); + KeyValueMappingContext mappingContext = new KeyValueMappingContext<>(); mappingContext.getPersistentEntity(Sample.class); mappingContext.getPersistentEntity(SampleWithAdditionalGetters.class); mappingContext.getPersistentEntity(PersistentEntityJackson2ModuleUnitTests.PetOwner.class); @@ -89,12 +87,10 @@ public class PersistentEntityJackson2ModuleUnitTests { NestedEntitySerializer nestedEntitySerializer = new NestedEntitySerializer(persistentEntities, new EmbeddedResourcesAssembler(persistentEntities, associations, mock(ExcerptProjector.class)), invoker); - OrderAwarePluginRegistry, Class> lookups = OrderAwarePluginRegistry.create(); - SimpleModule module = new SimpleModule(); module.setSerializerModifier(new AssociationOmittingSerializerModifier(persistentEntities, associations, - nestedEntitySerializer, new LookupObjectSerializer(lookups))); + nestedEntitySerializer, new LookupObjectSerializer(Java8PluginRegistry.empty()))); module.setDeserializerModifier(new AssociationUriResolvingDeserializerModifier(persistentEntities, associations, converter, mock(RepositoryInvokerFactory.class))); @@ -110,7 +106,7 @@ public class PersistentEntityJackson2ModuleUnitTests { String result = mapper.writeValueAsString(sample); - assertThat(JsonPath.read(result, "$.foo"), is((Object) "bar")); + assertThat(JsonPath. read(result, "$.foo")).isEqualTo("bar"); } @Test // DATAREST-340 @@ -119,14 +115,15 @@ public class PersistentEntityJackson2ModuleUnitTests { SampleWithAdditionalGetters sample = new SampleWithAdditionalGetters(); String result = mapper.writeValueAsString(sample); - assertThat(JsonPath.read(result, "$.number"), is((Object) 5)); + + assertThat(JsonPath. read(result, "$.number")).isEqualTo(5); } @Test // DATAREST-662 public void resolvesReferenceToSubtypeCorrectly() throws IOException { - PersistentProperty property = persistentEntities.getPersistentEntity(PetOwner.class) - .getPersistentProperty("pet"); + PersistentProperty property = persistentEntities.getRequiredPersistentEntity(PetOwner.class) + .getRequiredPersistentProperty("pet"); when(associations.isLinkableAssociation(property)).thenReturn(true); when(converter.convert(new UriTemplate("/pets/1").expand(), TypeDescriptor.valueOf(URI.class), @@ -134,8 +131,8 @@ public class PersistentEntityJackson2ModuleUnitTests { PetOwner petOwner = mapper.readValue("{\"pet\":\"/pets/1\"}", PetOwner.class); - assertThat(petOwner, is(notNullValue())); - assertThat(petOwner.getPet(), is(notNullValue())); + assertThat(petOwner).isNotNull(); + assertThat(petOwner.getPet()).isNotNull(); } static class PetOwner { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/ProjectionJacksonIntegrationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/ProjectionJacksonIntegrationTests.java old mode 100644 new mode 100755 index 99b5dd65a..4150aed52 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/ProjectionJacksonIntegrationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/ProjectionJacksonIntegrationTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; @@ -62,7 +61,7 @@ public class ProjectionJacksonIntegrationTests { CustomerProjection projection = factory.createProjection(CustomerProjection.class, customer); String result = mapper.writeValueAsString(projection); - assertThat(JsonPath.read(result, "$.firstname"), is((Object) "Dave")); + assertThat(JsonPath. read(result, "$.firstname")).isEqualTo((Object) "Dave"); } @Test // DATAREST-221 @@ -83,7 +82,7 @@ public class ProjectionJacksonIntegrationTests { String result = mapper.writeValueAsString(resources); - assertThat(JsonPath.read(result, "$._embedded.customers[0].firstname"), is((Object) "Dave")); + assertThat(JsonPath. read(result, "$._embedded.customers[0].firstname")).isEqualTo((Object) "Dave"); } static class Customer { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/SortTranslatorUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/SortTranslatorUnitTests.java old mode 100644 new mode 100755 index 8a09132a0..6cd795477 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/SortTranslatorUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/SortTranslatorUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Collections; @@ -48,14 +47,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class SortTranslatorUnitTests { ObjectMapper objectMapper = new ObjectMapper(); - KeyValueMappingContext mappingContext; + KeyValueMappingContext mappingContext; PersistentEntities persistentEntities; SortTranslator sortTranslator; @Before public void setUp() { - mappingContext = new KeyValueMappingContext(); + mappingContext = new KeyValueMappingContext<>(); mappingContext.getPersistentEntity(Plain.class); mappingContext.getPersistentEntity(WithJsonProperty.class); mappingContext.getPersistentEntity(UnwrapEmbedded.class); @@ -70,106 +69,106 @@ public class SortTranslatorUnitTests { @Test // DATAREST-883 public void shouldMapKnownProperties() { - Sort translatedSort = sortTranslator.translateSort(new Sort("hello", "name"), - mappingContext.getPersistentEntity(Plain.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("hello", "name"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort.getOrderFor("hello"), is(nullValue())); - assertThat(translatedSort.getOrderFor("name"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("hello")).isNull(); + assertThat(translatedSort.getOrderFor("name")).isNotNull(); } @Test // DATAREST-883 public void returnsNullSortIfNoPropertiesMatch() { - Sort translatedSort = sortTranslator.translateSort(new Sort("hello", "world"), - mappingContext.getPersistentEntity(Plain.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("hello", "world"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort, is(nullValue())); + assertThat(translatedSort).isEqualTo(Sort.unsorted()); } @Test // DATAREST-883 public void shouldMapKnownPropertiesWithJsonProperty() { - Sort translatedSort = sortTranslator.translateSort(new Sort("hello", "foo"), - mappingContext.getPersistentEntity(WithJsonProperty.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("hello", "foo"), + mappingContext.getRequiredPersistentEntity(WithJsonProperty.class)); - assertThat(translatedSort.getOrderFor("hello"), is(nullValue())); - assertThat(translatedSort.getOrderFor("name"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("hello")).isNull(); + assertThat(translatedSort.getOrderFor("name")).isNotNull(); } @Test // DATAREST-883 public void shouldJacksonFieldNameForMapping() { - Sort translatedSort = sortTranslator.translateSort(new Sort("name"), - mappingContext.getPersistentEntity(WithJsonProperty.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("name"), + mappingContext.getRequiredPersistentEntity(WithJsonProperty.class)); - assertThat(translatedSort, is(nullValue())); + assertThat(translatedSort).isEqualTo(Sort.unsorted()); } @Test // DATAREST-910 public void shouldMapKnownNestedProperties() { Sort translatedSort = sortTranslator.translateSort( - new Sort("embedded.name", "embedded.collection", "embedded.someInterface"), - mappingContext.getPersistentEntity(Plain.class)); + Sort.by("embedded.name", "embedded.collection", "embedded.someInterface"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort.getOrderFor("embedded.name"), is(notNullValue())); - assertThat(translatedSort.getOrderFor("embedded.collection"), is(notNullValue())); - assertThat(translatedSort.getOrderFor("embedded.someInterface"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("embedded.name")).isNotNull(); + assertThat(translatedSort.getOrderFor("embedded.collection")).isNotNull(); + assertThat(translatedSort.getOrderFor("embedded.someInterface")).isNotNull(); } @Test // DATAREST-910 public void shouldSkipWrongNestedProperties() { - Sort translatedSort = sortTranslator.translateSort(new Sort("embedded.unknown"), - mappingContext.getPersistentEntity(Plain.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("embedded.unknown"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort, is(nullValue())); + assertThat(translatedSort).isEqualTo(Sort.unsorted()); } @Test // DATAREST-910, DATAREST-976 public void shouldSkipKnownAssociationProperties() { - Sort translatedSort = sortTranslator.translateSort(new Sort("association.name"), - mappingContext.getPersistentEntity(Plain.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("association.name"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort, is(nullValue())); + assertThat(translatedSort).isEqualTo(Sort.unsorted()); } @Test // DATAREST-976 public void shouldMapEmbeddableAssociationProperties() { - Sort translatedSort = sortTranslator.translateSort(new Sort("refEmbedded.name"), - mappingContext.getPersistentEntity(Plain.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("refEmbedded.name"), + mappingContext.getRequiredPersistentEntity(Plain.class)); - assertThat(translatedSort.getOrderFor("refEmbedded.name"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("refEmbedded.name")).isNotNull(); } @Test // DATAREST-910 public void shouldJacksonFieldNameForNestedFieldMapping() { - Sort translatedSort = sortTranslator.translateSort(new Sort("em.foo"), - mappingContext.getPersistentEntity(WithJsonProperty.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("em.foo"), + mappingContext.getRequiredPersistentEntity(WithJsonProperty.class)); - assertThat(translatedSort.getOrderFor("embeddedWithJsonProperty.bar"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("embeddedWithJsonProperty.bar")).isNotNull(); } @Test // DATAREST-910 public void shouldTranslatePathForSingleLevelJsonUnwrappedObject() { - Sort translatedSort = sortTranslator.translateSort(new Sort("un-name"), - mappingContext.getPersistentEntity(UnwrapEmbedded.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("un-name"), + mappingContext.getRequiredPersistentEntity(UnwrapEmbedded.class)); - assertThat(translatedSort.getOrderFor("embedded.name"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("embedded.name")).isNotNull(); } @Test // DATAREST-910 public void shouldTranslatePathForMultiLevelLevelJsonUnwrappedObject() { - Sort translatedSort = sortTranslator.translateSort(new Sort("un-name", "burrito.un-name"), - mappingContext.getPersistentEntity(MultiUnwrapped.class)); + Sort translatedSort = sortTranslator.translateSort(Sort.by("un-name", "burrito.un-name"), + mappingContext.getRequiredPersistentEntity(MultiUnwrapped.class)); - assertThat(translatedSort.getOrderFor("anotherWrap.embedded.name"), is(notNullValue())); - assertThat(translatedSort.getOrderFor("burrito.embedded.name"), is(notNullValue())); + assertThat(translatedSort.getOrderFor("anotherWrap.embedded.name")).isNotNull(); + assertThat(translatedSort.getOrderFor("burrito.embedded.name")).isNotNull(); } static class Plain { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/UriStringDeserializerUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/UriStringDeserializerUnitTests.java old mode 100644 new mode 100755 index b2d7e0bd0..604d20f20 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/UriStringDeserializerUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/UriStringDeserializerUnitTests.java @@ -15,9 +15,8 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.net.URI; @@ -29,7 +28,7 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.convert.TypeDescriptor; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.rest.core.UriToEntityConverter; @@ -82,8 +81,8 @@ public class UriStringDeserializerUnitTests { @Test // DATAREST-377 public void returnsNullUriIfSourceIsEmptyOrNull() throws Exception { - assertThat(invokeConverterWith(""), is(nullValue())); - assertThat(invokeConverterWith(null), is(nullValue())); + assertThat(invokeConverterWith("")).isNull(); + assertThat(invokeConverterWith(null)).isNull(); } @Test // DATAREST-377 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/WrappedPropertiesUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/WrappedPropertiesUnitTests.java old mode 100644 new mode 100755 index 7569d461e..3d05208a6 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/WrappedPropertiesUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/WrappedPropertiesUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.json; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.*; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,13 +45,13 @@ public class WrappedPropertiesUnitTests { static final ObjectMapper MAPPER = new ObjectMapper(); - KeyValueMappingContext mappingContext; + KeyValueMappingContext mappingContext; PersistentEntities persistentEntities; @Before public void setUp() { - mappingContext = new KeyValueMappingContext(); + mappingContext = new KeyValueMappingContext<>(); mappingContext.getPersistentEntity(MultiLevelNesting.class); mappingContext.getPersistentEntity(SyntheticProperties.class); @@ -62,72 +61,72 @@ public class WrappedPropertiesUnitTests { @Test // DATAREST-910 public void wrappedPropertiesShouldConsiderSingleLevelUnwrapping() { - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(OneLevelNesting.class); + PersistentEntity persistentEntity = persistentEntities.getRequiredPersistentEntity(OneLevelNesting.class); WrappedProperties wrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, persistentEntity, MAPPER); - assertThat(wrappedProperties.hasPersistentPropertiesForField("street"), is(true)); - assertThat(wrappedProperties.hasPersistentPropertiesForField("one"), is(false)); + assertThat(wrappedProperties.hasPersistentPropertiesForField("street")).isTrue(); + assertThat(wrappedProperties.hasPersistentPropertiesForField("one")).isFalse(); List> street = wrappedProperties.getPersistentProperties("street"); - PersistentProperty addressProperty = persistentEntity.getPersistentProperty("address"); - PersistentProperty streetProperty = persistentEntities.getPersistentEntity(Address.class) - .getPersistentProperty("street"); + PersistentProperty addressProperty = persistentEntity.getRequiredPersistentProperty("address"); + PersistentProperty streetProperty = persistentEntities.getRequiredPersistentEntity(Address.class) + .getRequiredPersistentProperty("street"); - assertThat(street, contains(addressProperty, streetProperty)); + assertThat(street).contains(addressProperty, streetProperty); } @Test // DATAREST-910 public void wrappedPropertiesShouldConsiderMultiLevelUnwrapping() { - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(MultiLevelNesting.class); + PersistentEntity persistentEntity = persistentEntities.getRequiredPersistentEntity(MultiLevelNesting.class); WrappedProperties wrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, persistentEntity, new ObjectMapper()); - assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-one-post"), is(true)); - assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-street-post"), is(true)); - assertThat(wrappedProperties.hasPersistentPropertiesForField("nested"), is(false)); + assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-one-post")).isTrue(); + assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-street-post")).isTrue(); + assertThat(wrappedProperties.hasPersistentPropertiesForField("nested")).isFalse(); List> street = wrappedProperties.getPersistentProperties("pre-street-post"); - PersistentProperty oneLevelNestingProperty = persistentEntity.getPersistentProperty("unwrapped"); - PersistentProperty addressProperty = persistentEntities.getPersistentEntity(OneLevelNesting.class) - .getPersistentProperty("address"); - PersistentProperty streetProperty = persistentEntities.getPersistentEntity(Address.class) - .getPersistentProperty("street"); + PersistentProperty oneLevelNestingProperty = persistentEntity.getRequiredPersistentProperty("unwrapped"); + PersistentProperty addressProperty = persistentEntities.getRequiredPersistentEntity(OneLevelNesting.class) + .getRequiredPersistentProperty("address"); + PersistentProperty streetProperty = persistentEntities.getRequiredPersistentEntity(Address.class) + .getRequiredPersistentProperty("street"); - assertThat(street, contains(oneLevelNestingProperty, addressProperty, streetProperty)); + assertThat(street).contains(oneLevelNestingProperty, addressProperty, streetProperty); } @Test // DATAREST-910 public void wrappedPropertiesShouldConsiderJacksonFieldNames() { - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(MultiLevelNesting.class); + PersistentEntity persistentEntity = persistentEntities.getRequiredPersistentEntity(MultiLevelNesting.class); WrappedProperties wrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, persistentEntity, new ObjectMapper()); - assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-zip-post"), is(true)); + assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-zip-post")).isTrue(); } @Test // DATAREST-910 public void wrappedPropertiesShouldIgnoreIgnoredJacksonFields() { - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(MultiLevelNesting.class); + PersistentEntity persistentEntity = persistentEntities.getRequiredPersistentEntity(MultiLevelNesting.class); WrappedProperties wrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, persistentEntity, new ObjectMapper()); - assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-street-ignored"), is(false)); + assertThat(wrappedProperties.hasPersistentPropertiesForField("pre-street-ignored")).isFalse(); } @Test // DATAREST-910 public void wrappedPropertiesShouldIgnoreSyntheticProperties() { - PersistentEntity persistentEntity = persistentEntities.getPersistentEntity(SyntheticProperties.class); + PersistentEntity persistentEntity = persistentEntities.getRequiredPersistentEntity(SyntheticProperties.class); WrappedProperties wrappedProperties = WrappedProperties.fromJacksonProperties(persistentEntities, persistentEntity, new ObjectMapper()); - assertThat(wrappedProperties.hasPersistentPropertiesForField("street"), is(false)); + assertThat(wrappedProperties.hasPersistentPropertiesForField("street")).isFalse(); } @Data diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationTests.java old mode 100644 new mode 100755 index bd74f7e12..0c42a7d14 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationTests.java @@ -15,7 +15,7 @@ */ package org.springframework.data.rest.webmvc.json.patch; -import static org.hamcrest.CoreMatchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; import java.util.ArrayList; @@ -82,6 +82,6 @@ public class AddOperationTests { new AddOperation("/items/-", "Some text.").perform(todo, Todo.class); - assertThat(todo.getItems().get(0), is("Some text.")); + assertThat(todo.getItems().get(0)).isEqualTo("Some text."); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/CopyOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/CopyOperationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/JsonPatchTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/JsonPatchTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/MoveOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/MoveOperationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/PathToSpelTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/PathToSpelTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/RemoveOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/RemoveOperationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/ReplaceOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/ReplaceOperationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/TestOperationTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/TestOperationTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/Todo.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/Todo.java index 5046ea84c..4d937fbd3 100644 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/Todo.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/Todo.java @@ -16,13 +16,13 @@ package org.springframework.data.rest.webmvc.json.patch; +import lombok.Data; +import lombok.NoArgsConstructor; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; -import lombok.Data; -import lombok.NoArgsConstructor; - /** * @author Roy Clarkson * @author Craig Walls diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mapping/AssociationsUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mapping/AssociationsUnitTests.java old mode 100644 new mode 100755 index 3248113af..515cc8af5 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mapping/AssociationsUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/mapping/AssociationsUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.mapping; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.Arrays; @@ -26,7 +25,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Reference; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity; import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentProperty; @@ -55,13 +54,13 @@ public class AssociationsUnitTests { Associations associations; - KeyValueMappingContext mappingContext; + KeyValueMappingContext mappingContext; ResourceMappings mappings; @Before public void setUp() { - this.mappingContext = new KeyValueMappingContext(); + this.mappingContext = new KeyValueMappingContext<>(); this.mappingContext.getPersistentEntity(Root.class); this.mappings = new PersistentEntitiesResourceMappings(new PersistentEntities(Arrays.asList(mappingContext))); @@ -81,37 +80,37 @@ public class AssociationsUnitTests { @Test public void handlesNullPropertyForLookupTypeCheck() { - assertThat(associations.isLookupType(null), is(false)); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> associations.isLookupType(null)); } @Test public void forwardsLookupTypeCheckToConfiguration() { doReturn(Root.class).when(property).getActualType(); - assertThat(associations.isLookupType(property), is(false)); + assertThat(associations.isLookupType(property)).isFalse(); doReturn(true).when(configuration).isLookupType(Root.class); - assertThat(associations.isLookupType(property), is(true)); + assertThat(associations.isLookupType(property)).isTrue(); } @Test public void forwardsIdExposureCheckToConfiguration() { doReturn(Root.class).when(entity).getType(); - assertThat(associations.isIdExposed(entity), is(false)); + assertThat(associations.isIdExposed(entity)).isFalse(); doReturn(true).when(configuration).isIdExposedFor(Root.class); - assertThat(associations.isIdExposed(entity), is(true)); + assertThat(associations.isIdExposed(entity)).isTrue(); } @Test public void exposesConfiguredMapping() { - assertThat(associations.getMappings(), is(mappings)); + assertThat(associations.getMappings()).isEqualTo(mappings); } @Test public void forwardsMetadataLookupToMappings() { - assertThat(associations.getMetadataFor(Root.class), is(notNullValue())); + assertThat(associations.getMetadataFor(Root.class)).isNotNull(); } @Test @@ -119,8 +118,8 @@ public class AssociationsUnitTests { List links = associations.getLinksFor(getAssociation(Root.class, "relatedAndExported"), new Path("")); - assertThat(links, hasSize(1)); - assertThat(links, hasItem(new Link("/relatedAndExported", "relatedAndExported"))); + assertThat(links).hasSize(1); + assertThat(links).contains(new Link("/relatedAndExported", "relatedAndExported")); } @Test @@ -128,13 +127,16 @@ public class AssociationsUnitTests { List links = associations.getLinksFor(getAssociation(Root.class, "relatedButNotExported"), new Path("")); - assertThat(links, hasSize(0)); + assertThat(links).hasSize(0); } private Association> getAssociation(Class type, String name) { - KeyValuePersistentEntity rootEntity = mappingContext.getPersistentEntity(type); - return new Association(rootEntity.getPersistentProperty(name), null); + KeyValuePersistentEntity> rootEntity = mappingContext + .getRequiredPersistentEntity(type); + KeyValuePersistentProperty property = rootEntity.getRequiredPersistentProperty(name); + + return new Association(property, null); } static class Root { diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/DelegatingHandlerMappingUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/DelegatingHandlerMappingUnitTests.java old mode 100644 new mode 100755 index 72b37ef11..9292caabb --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/DelegatingHandlerMappingUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/DelegatingHandlerMappingUnitTests.java @@ -15,8 +15,8 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import java.util.Arrays; @@ -26,7 +26,7 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; @@ -54,7 +54,6 @@ public class DelegatingHandlerMappingUnitTests { assertHandlerTriedButExceptionThrown(mapping, UnsatisfiedServletRequestParameterException.class); } - @SuppressWarnings("unchecked") private final void assertHandlerTriedButExceptionThrown(HandlerMapping mapping, Class type) throws Exception { @@ -66,7 +65,7 @@ public class DelegatingHandlerMappingUnitTests { fail(String.format("Expected %s!", type.getSimpleName())); } catch (Exception o_O) { - assertThat(o_O, is(instanceOf(type))); + assertThat(o_O).isInstanceOf(type); verify(second, times(1)).getHandler(request); } finally { reset(first, second); diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagDoesntMatchExceptionUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagDoesntMatchExceptionUnitTests.java old mode 100644 new mode 100755 diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagUnitTests.java old mode 100644 new mode 100755 index 5ddf25a72..f051837e8 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/ETagUnitTests.java @@ -15,12 +15,11 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.annotation.Version; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; import org.springframework.data.mapping.PersistentEntity; @@ -36,42 +35,45 @@ import org.springframework.http.HttpHeaders; @RunWith(MockitoJUnitRunner.class) public class ETagUnitTests { - KeyValueMappingContext context = new KeyValueMappingContext(); + KeyValueMappingContext context = new KeyValueMappingContext<>(); @Test(expected = ETagDoesntMatchException.class) // DATAREST-160 public void expectWrongEtag() throws Exception { ETag eTag = ETag.from("1"); - eTag.verify(context.getPersistentEntity(Sample.class), new Sample(0L)); + eTag.verify(context.getRequiredPersistentEntity(Sample.class), new Sample(0L)); } @Test // DATAREST-160 public void expectCorrectEtag() throws Exception { - ETag.from("0").verify(context.getPersistentEntity(Sample.class), new Sample(0L)); + ETag.from("0").verify(context.getRequiredPersistentEntity(Sample.class), new Sample(0L)); } @Test // DATAREST-160 public void createsETagFromVersionValue() throws Exception { - PersistentEntity entity = context.getPersistentEntity(Sample.class); + PersistentEntity entity = context.getRequiredPersistentEntity(Sample.class); ETag from = ETag.from(PersistentEntityResource.build(new Sample(0L), entity).build()); - assertThat(from.toString(), is((Object) "\"0\"")); + assertThat(from.toString()).isEqualTo((Object) "\"0\""); } @Test // DATAREST-160 public void surroundsValueWithQuotationMarksOnToString() { - assertThat(ETag.from("1").toString(), is("\"1\"")); + assertThat(ETag.from("1").toString()).isEqualTo("\"1\""); } @Test // DATAREST-160 public void returnsNoEtagForNullStringSource() { - assertThat(ETag.from((String) null), is(ETag.NO_ETAG)); + assertThat(ETag.from((String) null)).isEqualTo(ETag.NO_ETAG); } @Test // DATAREST-160 public void returnsNoEtagForNullPersistentEntityResourceSource() { - assertThat(ETag.from((PersistentEntityResource) null), is(ETag.NO_ETAG)); + + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + ETag.from((PersistentEntityResource) null); + }); } @Test // DATAREST-160 @@ -81,48 +83,49 @@ public class ETagUnitTests { ETag two = ETag.from("2"); ETag nullETag = ETag.from((String) null); - assertThat(one.equals(one), is(true)); - assertThat(one.equals(two), is(false)); - assertThat(two.equals(one), is(false)); - assertThat(nullETag.equals(one), is(false)); - assertThat(one.equals(two), is(false)); - assertThat(one.equals(""), is(false)); + assertThat(one.equals(one)).isTrue(); + assertThat(one.equals(two)).isFalse(); + assertThat(two.equals(one)).isFalse(); + assertThat(nullETag.equals(one)).isFalse(); + assertThat(one.equals(two)).isFalse(); + assertThat(one.equals("")).isFalse(); } @Test // DATAREST-160 public void returnsNoEtagForEntityWithoutVersionProperty() { - PersistentEntity entity = context.getPersistentEntity(SampleWithoutVersion.class); - assertThat(ETag.from(PersistentEntityResource.build(new SampleWithoutVersion(), entity).build()), is(ETag.NO_ETAG)); + PersistentEntity entity = context.getRequiredPersistentEntity(SampleWithoutVersion.class); + assertThat(ETag.from(PersistentEntityResource.build(new SampleWithoutVersion(), entity).build())) + .isEqualTo(ETag.NO_ETAG); } @Test // DATAREST-160 public void noETagReturnsNullForToString() { - assertThat(ETag.NO_ETAG.toString(), is(nullValue())); + assertThat(ETag.NO_ETAG.toString()).isNull(); } @Test // DATAREST-160 public void noETagDoesNotRejectVerification() { - ETag.NO_ETAG.verify(context.getPersistentEntity(Sample.class), new Sample(5L)); + ETag.NO_ETAG.verify(context.getRequiredPersistentEntity(Sample.class), new Sample(5L)); } @Test // DATAREST-160 public void verificationDoesNotRejectNullEntity() { - ETag.from("5").verify(context.getPersistentEntity(Sample.class), null); + ETag.from("5").verify(context.getRequiredPersistentEntity(Sample.class), null); } @Test // DATAREST-160 public void stripsTrailingAndLeadingQuotesOnCreation() { - assertThat(ETag.from("\"1\""), is(ETag.from("1"))); - assertThat(ETag.from("\"\"1\"\""), is(ETag.from("1"))); + assertThat(ETag.from("\"1\"")).isEqualTo(ETag.from("1")); + assertThat(ETag.from("\"\"1\"\"")).isEqualTo(ETag.from("1")); } @Test // DATAREST-160 public void addsETagToHeadersIfNotNoETag() { HttpHeaders headers = ETag.from("1").addTo(new HttpHeaders()); - assertThat(headers.getETag(), is(notNullValue())); + assertThat(headers.getETag()).isNotNull(); } @Test // DATAREST-160 @@ -130,7 +133,7 @@ public class ETagUnitTests { HttpHeaders headers = ETag.NO_ETAG.addTo(new HttpHeaders()); - assertThat(headers.containsKey("ETag"), is(false)); + assertThat(headers.containsKey("ETag")).isFalse(); } // tag::versioned-sample[] diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/PersistentEntityProjectorUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/PersistentEntityProjectorUnitTests.java old mode 100644 new mode 100755 index f613bbae5..ee446f966 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/PersistentEntityProjectorUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/PersistentEntityProjectorUnitTests.java @@ -15,15 +15,14 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.rest.core.config.ProjectionDefinitionConfiguration; @@ -61,7 +60,7 @@ public class PersistentEntityProjectorUnitTests { Object object = new Object(); - assertThat(projector.project(object), is(object)); + assertThat(projector.project(object)).isEqualTo(object); } @Test // DATAREST-221 @@ -69,7 +68,7 @@ public class PersistentEntityProjectorUnitTests { configuration.addProjection(Sample.class, Object.class); - assertThat(projector.project(new Object()), is(instanceOf(Sample.class))); + assertThat(projector.project(new Object())).isInstanceOf(Sample.class); } @Test // DATAREST-806 @@ -77,12 +76,12 @@ public class PersistentEntityProjectorUnitTests { configuration.addProjection(Sample.class, Object.class); - assertThat(projector.projectExcerpt(new Object()), is(instanceOf(Sample.class))); + assertThat(projector.projectExcerpt(new Object())).isInstanceOf(Sample.class); } @Test // DATAREST-806 public void excerptProjectionIsUsedForExcerpt() { - assertThat(projector.projectExcerpt(new Object()), is(instanceOf(Excerpt.class))); + assertThat(projector.projectExcerpt(new Object())).isInstanceOf(Excerpt.class); } @Test // DATAREST-806 @@ -92,7 +91,7 @@ public class PersistentEntityProjectorUnitTests { PersistentEntityProjector projector = new PersistentEntityProjector(configuration, factory, null, mappings); - assertThat(projector.projectExcerpt(new Object()), is(instanceOf(Excerpt.class))); + assertThat(projector.projectExcerpt(new Object())).isInstanceOf(Excerpt.class); } interface Sample {} diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessageUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessageUnitTests.java old mode 100644 new mode 100755 index a8c2a9272..878630110 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessageUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/support/RepositoryConstraintViolationExceptionMessageUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.support; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Collections; import java.util.HashMap; @@ -84,7 +83,7 @@ public class RepositoryConstraintViolationExceptionMessageUnitTests { List result = message.getErrors(); - assertThat(result, hasSize(1)); - assertThat(result.get(0).getInvalidValue(), is(value)); + assertThat(result).hasSize(1); + assertThat(result.get(0).getInvalidValue()).isEqualTo(value); } } diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/util/UriUtilsUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/util/UriUtilsUnitTests.java old mode 100644 new mode 100755 index fcd01a943..3a4fe8b37 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/util/UriUtilsUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/util/UriUtilsUnitTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.rest.webmvc.util; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.lang.reflect.Method; import java.util.List; @@ -38,7 +37,7 @@ public class UriUtilsUnitTests { Method method = ClassUtils.getMethod(MappedMethod.class, "method"); List pathSegments = UriUtils.getPathSegments(method); - assertThat(pathSegments, hasItems("hello", "world")); + assertThat(pathSegments).contains("hello", "world"); } @Test // DATAREST-910 @@ -47,7 +46,7 @@ public class UriUtilsUnitTests { Method method = ClassUtils.getMethod(MappedClassAndMethod.class, "method"); List pathSegments = UriUtils.getPathSegments(method); - assertThat(pathSegments, hasItems("hello", "world")); + assertThat(pathSegments).contains("hello", "world"); } static class MappedMethod {