From 0e1edfd5a438768a30f0f2c92b2209046e5f0dbc Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Wed, 29 Nov 2017 12:45:31 +0400 Subject: [PATCH 01/10] Branch tags 2.1.8 taken from spring-data-solr repsoitories --- pom.xml | 59 +- src/main/asciidoc/preface.adoc | 6 +- src/main/asciidoc/reference/data-solr.adoc | 77 +- src/main/asciidoc/reference/misc.adoc | 78 +- .../data/solr/SolrRealtimeGetRequest.java | 78 + .../data/solr/VersionUtil.java | 47 +- .../data/solr/config/package-info.java | 2 - .../data/solr/core/CollectionCallback.java | 41 + .../data/solr/core/DefaultQueryParser.java | 40 +- .../data/solr/core/QueryParser.java | 10 +- .../data/solr/core/QueryParserBase.java | 140 +- .../data/solr/core/QueryParsers.java | 8 +- .../data/solr/core/RequestMethod.java | 4 +- .../data/solr/core/ResultHelper.java | 109 +- .../data/solr/core/SolrCallback.java | 4 +- .../solr/core/SolrExceptionTranslator.java | 11 +- .../data/solr/core/SolrOperations.java | 671 +++++-- .../data/solr/core/SolrTemplate.java | 931 ++++++++-- ...SolrTransactionSynchronizationAdapter.java | 26 +- ...nsactionSynchronizationAdapterBuilder.java | 20 +- .../data/solr/core/TermsQueryParser.java | 6 +- .../solr/core/convert/CustomConversions.java | 258 ++- .../solr/core/convert/DateTimeConverters.java | 61 +- .../core/convert/MappingSolrConverter.java | 254 ++- .../solr/core/convert/NumberConverters.java | 8 +- .../data/solr/core/convert/SolrConverter.java | 8 +- .../solr/core/convert/SolrConverterBase.java | 39 +- .../core/convert/SolrCustomConversions.java | 61 - .../solr/core/convert/SolrJConverter.java | 23 +- .../solr/core/convert/SolrjConverters.java | 24 +- .../data/solr/core/convert/package-info.java | 6 - .../data/solr/core/geo/GeoConverters.java | 22 +- .../data/solr/core/geo/Point.java | 9 +- .../data/solr/core/geo/package-info.java | 6 - .../data/solr/core/mapping/ChildDocument.java | 37 - .../data/solr/core/mapping/Indexed.java | 4 +- .../mapping/SimpleSolrMappingContext.java | 21 +- .../mapping/SimpleSolrPersistentEntity.java | 74 +- .../mapping/SimpleSolrPersistentProperty.java | 87 +- .../data/solr/core/mapping/SolrDocument.java | 14 +- .../core/mapping/SolrPersistentEntity.java | 14 +- .../core/mapping/SolrPersistentProperty.java | 19 +- .../solr/core/mapping/SolrSimpleTypes.java | 6 +- .../data/solr/core/mapping/package-info.java | 6 - .../data/solr/core/package-info.java | 2 - .../data/solr/core/query/AbstractQuery.java | 18 +- .../core/query/AbstractQueryDecorator.java | 32 +- .../core/query/AbstractValueHoldingField.java | 9 +- .../data/solr/core/query/AnyCriteria.java | 8 +- .../data/solr/core/query/Criteria.java | 44 +- .../data/solr/core/query/Crotch.java | 17 +- .../solr/core/query/CurrencyFunction.java | 12 +- .../data/solr/core/query/DistanceField.java | 5 +- .../solr/core/query/DistanceFunction.java | 9 +- .../data/solr/core/query/ExistsFunction.java | 6 +- .../data/solr/core/query/FacetOptions.java | 37 +- .../data/solr/core/query/FacetQuery.java | 5 +- .../data/solr/core/query/Field.java | 7 +- .../core/query/FieldWithQueryParameters.java | 3 +- .../data/solr/core/query/GeoHashFunction.java | 6 +- .../data/solr/core/query/GroupOptions.java | 24 +- .../solr/core/query/HighlightOptions.java | 34 +- .../data/solr/core/query/HighlightQuery.java | 5 +- .../data/solr/core/query/Join.java | 12 +- .../data/solr/core/query/MaxFunction.java | 16 +- .../data/solr/core/query/Node.java | 10 +- .../data/solr/core/query/NotFunction.java | 6 +- .../data/solr/core/query/ParameterHolder.java | 5 +- .../data/solr/core/query/PartialUpdate.java | 20 +- .../data/solr/core/query/ProductFunction.java | 6 +- .../data/solr/core/query/Query.java | 37 +- .../data/solr/core/query/QueryFunction.java | 6 +- .../data/solr/core/query/QueryParameter.java | 5 +- .../solr/core/query/QueryParameterImpl.java | 6 +- .../core/query/SimpleCalculatedField.java | 5 +- .../query/SimpleFacetAndHighlightQuery.java | 14 +- .../solr/core/query/SimpleFacetQuery.java | 8 +- .../solr/core/query/SimpleHighlightQuery.java | 8 +- .../solr/core/query/SimplePivotField.java | 25 +- .../data/solr/core/query/SimpleQuery.java | 65 +- .../solr/core/query/SimpleTermsQuery.java | 5 +- .../solr/core/query/SimpleUpdateField.java | 11 +- .../data/solr/core/query/SolrDataQuery.java | 9 +- .../data/solr/core/query/SolrPageRequest.java | 22 +- .../solr/core/query/SpellcheckOptions.java | 27 +- .../data/solr/core/query/StatsOptions.java | 15 +- .../data/solr/core/query/TermsOptions.java | 25 +- .../data/solr/core/query/Update.java | 5 +- .../solr/core/query/ValueHoldingField.java | 7 +- .../data/solr/core/query/package-info.java | 6 - .../data/solr/core/query/result/Cursor.java | 7 +- .../core/query/result/DelegatingCursor.java | 18 +- .../core/query/result/FacetQueryResult.java | 4 +- .../core/query/result/FieldStatsResult.java | 6 +- .../query/result/FieldValueCountEntry.java | 8 +- .../solr/core/query/result/GroupPage.java | 10 +- .../solr/core/query/result/GroupResult.java | 10 +- .../core/query/result/HighlightEntry.java | 9 +- .../data/solr/core/query/result/PageKey.java | 2 - .../solr/core/query/result/ScoredPage.java | 4 +- .../query/result/SimpleFacetPivotEntry.java | 21 +- .../query/result/SimpleFieldStatsResult.java | 18 +- .../core/query/result/SimpleGroupResult.java | 14 +- .../core/query/result/SimpleStatsResult.java | 43 +- .../core/query/result/SolrResultPage.java | 47 +- .../query/result/SpellcheckQueryResult.java | 34 +- .../solr/core/query/result/StatsResult.java | 30 +- .../solr/core/query/result/StringPageKey.java | 2 +- .../solr/core/query/result/TermsPage.java | 5 +- .../core/query/result/TermsResultPage.java | 10 +- .../solr/core/query/result/package-info.java | 6 - .../core/schema/DefaultSchemaOperations.java | 94 +- .../schema/MappingJacksonResponseParser.java | 7 +- .../solr/core/schema/SchemaDefinition.java | 86 +- .../solr/core/schema/SolrJsonRequest.java | 25 +- .../solr/core/schema/SolrJsonResponse.java | 6 +- .../SolrPersistentEntitySchemaCreator.java | 13 +- .../solr/core/schema/SolrSchemaRequest.java | 110 ++ .../solr/core/schema/SolrSchemaResolver.java | 20 +- .../solr/core/schema/SolrSchemaWriter.java | 4 +- .../data/solr/core/schema/package-info.java | 6 - .../data/solr/package-info.java | 6 - .../data/solr/repository/Query.java | 2 - .../data/solr/repository/SelectiveStats.java | 8 +- .../data/solr/repository/Stats.java | 10 +- .../repository/cdi/SolrRepositoryBean.java | 17 +- .../cdi/SolrRepositoryExtension.java | 12 +- .../solr/repository/cdi/package-info.java | 6 - .../config/AbstractSolrConfiguration.java | 115 -- .../config/EnableSolrRepositories.java | 7 + .../config/SolrRepositoryConfigExtension.java | 94 +- .../solr/repository/config/package-info.java | 6 - .../data/solr/repository/package-info.java | 2 - .../repository/query/AbstractSolrQuery.java | 97 +- .../repository/query/PartTreeSolrQuery.java | 9 +- .../query/SolrEntityInformation.java | 14 +- .../query/SolrEntityInformationCreator.java | 6 +- .../solr/repository/query/SolrParameter.java | 4 +- .../SolrParametersParameterAccessor.java | 3 +- .../repository/query/SolrQueryCreator.java | 13 +- .../repository/query/SolrQueryMethod.java | 186 +- .../query/StringBasedSolrQuery.java | 13 +- .../solr/repository/query/package-info.java | 6 - .../support/MappingSolrEntityInformation.java | 21 +- .../support/SimpleSolrRepository.java | 148 +- .../SolrEntityInformationCreatorImpl.java | 13 +- .../support/SolrRepositoryFactory.java | 44 +- .../support/SolrRepositoryFactoryBean.java | 15 +- .../solr/repository/support/package-info.java | 6 - .../data/solr/server/SolrClientFactory.java | 20 +- ...mbeddedSolrServerBeanDefinitionParser.java | 4 +- .../HttpSolrClientBeanDefinitionParser.java | 4 +- .../data/solr/server/config/package-info.java | 6 - .../support/EmbeddedSolrServerFactory.java | 30 +- .../server/support/HttpSolrClientFactory.java | 45 +- .../support/HttpSolrClientFactoryBean.java | 15 +- .../support/MulticoreSolrClientFactory.java | 154 ++ .../server/support/SolrClientFactoryBase.java | 7 +- .../solr/server/support/SolrClientUtils.java | 287 +++ .../solr/server/support/package-info.java | 7 - src/main/resources/META-INF/spring.schemas | 3 +- src/main/resources/changelog.txt | 17 - src/main/resources/notice.txt | 2 +- .../data/solr/config/spring-solr-3.0.xsd | 84 - .../AbstractITestWithEmbeddedSolrServer.java | 11 +- .../data/solr/ExampleSolrBean.java | 4 +- .../data/solr/HttpSolrClientFactoryTests.java | 48 +- .../solr/SolrRealtimeGetRequestUnitTests.java | 68 + .../solr/core/DefaultQueryParserTests.java | 14 +- .../solr/core/FunctionQueryFragmentTests.java | 40 +- .../data/solr/core/ITestSolrTemplate.java | 852 ++++----- .../data/solr/core/QueryParserBaseTests.java | 12 +- .../data/solr/core/ResultHelperTests.java | 204 ++- .../data/solr/core/SolrTemplateTests.java | 570 ++++-- .../core/convert/CustomConversionsTests.java | 93 + .../core/convert/DateTimeConvertersTests.java | 26 +- .../solr/core/convert/GeoConverterTests.java | 17 +- .../convert/ITestMappingSolrConverter.java | 140 +- ...ocumentObjectBinderCompatibilityTests.java | 123 +- .../convert/MappingSolrConverterTests.java | 62 +- .../core/convert/NumberConvertersTests.java | 18 +- .../core/convert/SolrJConverterTests.java | 2 +- .../SimpleSolrPersistentEntityTests.java | 63 +- ...impleSolrPersistentPropertyBoostTests.java | 21 +- .../SimpleSolrPersistentPropertyTest.java | 35 +- ...leSolrPersitentPropertyFieldNameTests.java | 30 +- .../data/solr/core/query/CriteriaTests.java | 65 +- .../query/FieldWithQueryParametersTests.java | 8 +- .../core/query/ITestCriteriaExecution.java | 70 +- .../solr/core/query/SimpleQueryTests.java | 28 +- .../result/DelegatingCursorUnitTests.java | 38 +- .../query/result/SimpleStatsResultTests.java | 28 - .../query/result/SolrGroupResultPageTest.java | 26 +- .../schema/DefaultSchemaOperationsTests.java | 2 +- .../core/schema/ITestSolrSchemaCreation.java | 105 +- .../core/schema/ITestSolrSchemaWriter.java | 6 +- ....java => SolrSchmeaResolverUnitTests.java} | 3 +- .../repository/ExampleSolrBeanRepository.java | 6 +- .../repository/ITestSimpleSolrRepository.java | 22 +- .../ITestSolrRepositoryOperations.java | 89 +- ...epositoryDeleteOperationRollbackFalse.java | 19 +- ...RepositoryDeleteOperationRollbackTrue.java | 13 +- ...rRepositorySaveOperationRollbackFalse.java | 15 +- ...lrRepositorySaveOperationRollbackTrue.java | 11 +- .../data/solr/repository/ProductBean.java | 38 +- .../solr/repository/ProductRepository.java | 4 +- .../repository/SimpleSolrRepositoryTests.java | 40 +- .../repository/cdi/CdiProductRepository.java | 6 +- .../repository/cdi/ITestCdiRepository.java | 49 +- .../repository/cdi/SolrTemplateProducer.java | 14 +- ...riesWithPredefinedConvertersUnitTests.java | 22 +- ...lrRepositoriesJustDeclaringSolrClient.java | 71 - ...eSolrRepositoriesWithMulticoreSupport.java | 13 +- ...RepositoriesWithSchemaCreationSupport.java | 11 +- .../config/ITestXmlNamespaceMulticore.java | 46 + .../SolrParametersParameterAccessorTests.java | 8 +- .../query/SolrQueryCreatorTests.java | 2 +- .../query/SolrQueryMethodTests.java | 11 +- .../solr/repository/query/SolrQueryTests.java | 80 +- .../query/StringBasedSolrQueryTests.java | 2 +- .../support/ITestSolrRepositoryFactory.java | 14 +- .../MappingSolrEntityInformationTests.java | 121 +- .../support/SolrRepositoryFactoryTests.java | 12 +- .../MulticoreSolrClientFactoryTests.java | 184 ++ .../server/support/SolrClientUtilTests.java | 315 ++++ .../solr/test/util/EmbeddedSolrServer.java | 10 +- src/test/resources/META-INF/beans.xml | 3 + .../collection1/conf/elevate.xml | 26 +- .../collection1/conf/email_url_types.txt | 2 - .../collection1/conf/managed-schema | 169 +- .../collection1/conf/params.json | 38 +- .../collection1/conf/solrconfig.xml | 417 +++-- .../ITestSolrRepositoryOperations-context.xml | 1 + .../repository/config/namespace-multicore.xml | 11 + .../collection1/conf/managed-schema | 1189 ------------ .../static-schema/collection1/conf/schema.xml | 1627 ++++++++--------- .../collection1/conf/solrconfig.xml | 416 +++-- .../core/schema/default_schema.json | 2 +- template.mf | 24 + 239 files changed, 7701 insertions(+), 6649 deletions(-) create mode 100644 src/main/java/org/springframework/data/solr/SolrRealtimeGetRequest.java create mode 100644 src/main/java/org/springframework/data/solr/core/CollectionCallback.java delete mode 100644 src/main/java/org/springframework/data/solr/core/convert/SolrCustomConversions.java delete mode 100644 src/main/java/org/springframework/data/solr/core/convert/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/core/geo/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/core/mapping/ChildDocument.java delete mode 100644 src/main/java/org/springframework/data/solr/core/mapping/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/core/query/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/core/query/result/package-info.java create mode 100644 src/main/java/org/springframework/data/solr/core/schema/SolrSchemaRequest.java delete mode 100644 src/main/java/org/springframework/data/solr/core/schema/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/repository/cdi/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/repository/config/AbstractSolrConfiguration.java delete mode 100644 src/main/java/org/springframework/data/solr/repository/config/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/repository/query/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/repository/support/package-info.java delete mode 100644 src/main/java/org/springframework/data/solr/server/config/package-info.java create mode 100644 src/main/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactory.java delete mode 100644 src/main/java/org/springframework/data/solr/server/support/package-info.java delete mode 100644 src/main/resources/org/springframework/data/solr/config/spring-solr-3.0.xsd create mode 100644 src/test/java/org/springframework/data/solr/SolrRealtimeGetRequestUnitTests.java create mode 100644 src/test/java/org/springframework/data/solr/core/convert/CustomConversionsTests.java rename src/test/java/org/springframework/data/solr/core/schema/{SolrSchmemaResolverUnitTests.java => SolrSchmeaResolverUnitTests.java} (99%) delete mode 100644 src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesJustDeclaringSolrClient.java create mode 100644 src/test/java/org/springframework/data/solr/repository/config/ITestXmlNamespaceMulticore.java create mode 100644 src/test/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactoryTests.java create mode 100644 src/test/java/org/springframework/data/solr/server/support/SolrClientUtilTests.java create mode 100644 src/test/resources/META-INF/beans.xml delete mode 100644 src/test/resources/managed-schema/collection1/conf/email_url_types.txt create mode 100644 src/test/resources/org/springframework/data/solr/repository/config/namespace-multicore.xml delete mode 100644 src/test/resources/static-schema/collection1/conf/managed-schema create mode 100644 template.mf diff --git a/pom.xml b/pom.xml index caca522..f74e20f 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.data spring-data-solr - 3.1.0.BUILD-SNAPSHOT + 2.1.8.RELEASE Spring Data Solr Spring Data module providing support for Apache Solr repositories. @@ -14,16 +14,16 @@ org.springframework.data.build spring-data-parent - 2.1.0.BUILD-SNAPSHOT + 1.9.8.RELEASE + DATASOLR 3.2.1 3.1 4.3.1 - 6.6.1 - 2.1.0.BUILD-SNAPSHOT - spring.data.solr + 5.5.0 + 1.13.8.RELEASE @@ -141,28 +141,9 @@ - - org.apache.solr - solr-langid - ${solr} - test - - - - org.apache.geronimo.specs - geronimo-jcdi_2.0_spec - 1.0.1 - test - - - javax.interceptor - javax.interceptor-api - 1.2.1 - test - javax.enterprise cdi-api @@ -171,14 +152,8 @@ true - javax.annotation - javax.annotation-api - ${javax-annotation-api} - test - - - org.apache.openwebbeans - openwebbeans-se + org.apache.openwebbeans.test + cditest-owb ${webbeans} test @@ -281,22 +256,6 @@ - - solr-next - - - apache.snapshots - Apache Snapshot Repository - http://repository.apache.org/snapshots - - false - - - - - 6.7.0-SNAPSHOT - - @@ -317,8 +276,8 @@ - spring-libs-snapshot - https://repo.spring.io/libs-snapshot + spring-libs-release + https://repo.spring.io/libs-release diff --git a/src/main/asciidoc/preface.adoc b/src/main/asciidoc/preface.adoc index d0db4fc..3c04a0b 100644 --- a/src/main/asciidoc/preface.adoc +++ b/src/main/asciidoc/preface.adoc @@ -1,6 +1,6 @@ = Preface -The Spring Data for Apache Solr project applies core Spring concepts to the development of solutions using the Apache Solr Search Engine. We provide a "template" as a high-level abstraction for storing and querying documents. You will notice similarities to the mongodb support in the Spring Framework. +The Spring Data Solr project applies core Spring concepts to the development of solutions using the Apache Solr Search Engine. We provide a "template" as a high-level abstraction for storing and querying documents. You will notice similarities to the mongodb support in the Spring Framework. [[project]] [preface] @@ -16,13 +16,13 @@ The Spring Data for Apache Solr project applies core Spring concepts to the deve [preface] == Requirements -Requires Java 8 runtime and http://lucene.apache.org/solr/[Apache Solr] 6.6. Preferably the latest 6.6.x version. +Requires http://lucene.apache.org/solr/[Apache Solr] 5. Preferably the latest 5.x version. [source,xml] ---- org.apache.solr - solr-solrj + solr-core ${solr.version} ---- \ No newline at end of file diff --git a/src/main/asciidoc/reference/data-solr.adoc b/src/main/asciidoc/reference/data-solr.adoc index f470f24..abfe1c0 100644 --- a/src/main/asciidoc/reference/data-solr.adoc +++ b/src/main/asciidoc/reference/data-solr.adoc @@ -31,7 +31,7 @@ Using the `repositories` element looks up Spring Data repositories as described ---- ==== -Using the `solr-server` or `embedded-solr-server` element registers an instance of `SolrClient` in the context. +Using the `solr-server` or `embedded-solr-server` element registers an instance of `SolrClient` in the context. .HttpSolrClient using Namespace ==== @@ -47,7 +47,7 @@ Using the `solr-server` or `embedded-solr-server` element registers an instance http://www.springframework.org/schema/data/solr/spring-solr.xsd"> - + ---- ==== @@ -65,7 +65,7 @@ Using the `solr-server` or `embedded-solr-server` element registers an instance http://www.springframework.org/schema/data/solr/spring-solr.xsd"> - + ---- ==== @@ -83,7 +83,7 @@ Using the `solr-server` or `embedded-solr-server` element registers an instance http://www.springframework.org/schema/data/solr/spring-solr.xsd"> - + ---- ==== @@ -99,13 +99,13 @@ The Spring Data Solr repositories support cannot only be activated through an XM @Configuration @EnableSolrRepositories class ApplicationConfig { - + @Bean public SolrClient solrClient() { EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory("classpath:com/acme/solr"); return factory.getSolrServer(); } - + @Bean public SolrOperations solrTemplate() { return new SolrTemplate(solrClient()); @@ -116,6 +116,33 @@ class ApplicationConfig { The configuration above sets up an `EmbeddedSolrServer` which is used by the `SolrTemplate` . Spring Data Solr Repositories are activated using the `@EnableSolrRepositories` annotation, which essentially carries the same attributes as the XML namespace does. If no base package is configured, it will use the one the configuration class resides in. +[[solr.multicore]] +=== Multicore Support + +Solr handles different collections within one core. Use `MulticoreSolrClientFactory` to create separate `SolrClient` for each core. + +.Multicore Configuration +==== +[source,java] +---- +@Configuration +@EnableSolrRepositories(multicoreSupport = true) +class ApplicationConfig { + + private static final String PROPERTY_NAME_SOLR_SERVER_URL = "solr.host"; + + @Resource + private Environment environment; + + @Bean + public SolrClient solrClient() { + return new HttpSolrClient(environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL)); + } + +} +---- +==== + [[solr.cdi]] === Solr Repositores using CDI @@ -182,7 +209,7 @@ Deriving the query from the method name is not always sufficient and/or may resu [[solr.query-methods.criterions]] === Query creation -Generally the query creation mechanism for Solr works as described in <> . Here's a short example of what a Solr query method translates into: +Generally the query creation mechanism for Solr works as described in <> . Here's a short example of what a Solr query method translates into: .Query creation from method names ==== @@ -201,7 +228,7 @@ The method name above will be translated into the following solr query q=name:?0 AND popularity:?1 ---- -A list of supported keywords for Solr is shown below. +A list of supported keywords for Solr is shown below. [cols="1,2,3", options="header"] .Supported keywords inside method names @@ -362,12 +389,12 @@ Product.findByName=name:?0 [source,java] ---- public interface ProductRepository extends SolrCrudRepository { - + List findByNamedQuery(Integer popularity); - + @Query(name = "Product.findByName") - List findByAnnotatedNamedQuery(String name); - + List findByAnnotatedNamedQuery(String name); + } ---- @@ -388,32 +415,32 @@ Though there is already support for Entity Mapping within SolrJ, Spring Data Sol public class Product { @Field private String simpleProperty; - + @Field("somePropertyName") private String namedPropery; - + @Field private List listOfValues; - + @Indexed(readonly = true) @Field("property_*") private List ignoredFromWriting; - + @Field("mappedField_*") - private Map> mappedFieldValues; - + private Map> mappedFieldValues; + @Dynamic @Field("dynamicMappedField_*") - private Map dynamicMappedFieldValues; - + private Map dynamicMappedFieldValues; + @Field private GeoLocation location; - + } ---- ==== -Taking a look as the above `MappingSolrConverter` will do as follows: +Taking a look as the above `MappingSolrConverter` will do as follows: [cols="1,3", options="header"] |=== @@ -440,7 +467,7 @@ Taking a look as the above `MappingSolrConverter` will do as follows: | `48.362893,14.534437` |=== -To register a custom converter one must add `CustomConversions` to `SolrTemplate` initializing it with own `Converter` implementation. +To register a custom converter one must add `CustomConversions` to `SolrTemplate` initializing it with own `Converter` implementation. ==== [source] @@ -450,9 +477,9 @@ To register a custom converter one must add `CustomConversions` to `SolrTemplate - + - + diff --git a/src/main/asciidoc/reference/misc.adoc b/src/main/asciidoc/reference/misc.adoc index 89e0304..4054c94 100644 --- a/src/main/asciidoc/reference/misc.adoc +++ b/src/main/asciidoc/reference/misc.adoc @@ -13,7 +13,7 @@ PartialUpdates can be done using `PartialUpdate` which implements `Update`. ---- PartialUpdate update = new PartialUpdate("id", "123"); update.add("name", "updated-name"); -solrTemplate.saveBean("collection-1", update); +solrTemplate.saveBean(update); ---- ==== @@ -40,7 +40,7 @@ Faceting cannot be directly applied using the `SolrRepository` but the `SolrTemp ---- FacetQuery query = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) .setFacetOptions(new FacetOptions().addFacetOnField("name").setFacetLimit(5)); -FacetPage page = solrTemplate.queryForFacetPage("collection-1", query, Product.class); +FacetPage page = solrTemplate.queryForFacetPage(query, Product.class); ---- ==== @@ -98,7 +98,7 @@ facetOptions.setFacetMinCount(0); Criteria criteria = new SimpleStringCriteria("*:*"); SimpleFacetQuery facetQuery = new SimpleFacetQuery(criteria).setFacetOptions(facetOptions); -FacetPage statResultPage = solrTemplate.queryForFacetPage("collection-1", facetQuery, ExampleSolrBean.class); +FacetPage statResultPage = solrTemplate.queryForFacetPage(facetQuery, ExampleSolrBean.class); ---- ==== @@ -143,7 +143,7 @@ FacetOptions facetOptions = new FacetOptions(); facetOptions.setFacetMinCount(0); facetOptions.addFacetOnPivot("category","dimension"); facetQuery.setFacetOptions(facetOptions); -FacetPage facetResult = solrTemplate.queryForFacetPage("collection-1", facetQuery, Product.class); +FacetPage facetResult = solrTemplate.queryForFacetPage(facetQuery, Product.class); ---- ==== @@ -165,7 +165,7 @@ Terms Vector cannot directly be used within `SolrRepository` but can be applied [source,java] ---- TermsQuery query = SimpleTermsQuery.queryBuilder().fields("name").build(); -TermsPage page = solrTemplate.queryForTermsPage("collection-1", query); +TermsPage page = solrTemplate.queryForTermsPage(query); ---- ==== @@ -188,7 +188,7 @@ GroupOptions groupOptions = new GroupOptions() .addGroupByQuery(query); groupQuery.setGroupOptions(groupOptions); -GroupPage page = solrTemplate.queryForGroupPage("collection-1", query, Product.class); +GroupPage page = solrTemplate.queryForGroupPage(query, Product.class); GroupResult fieldGroup = page.getGroupResult(field); GroupResult funcGroup = page.getGroupResult(func); @@ -210,7 +210,7 @@ StatsOptions statsOptions = new StatsOptions().addField("price"); // query SimpleQuery statsQuery = new SimpleQuery("*:*"); statsQuery.setStatsOptions(statsOptions); -StatsPage statsPage = solrTemplate.queryForStatsPage("collection-1", statsQuery, Product.class); +StatsPage statsPage = solrTemplate.queryForStatsPage(statsQuery, Product.class); // retrieving stats info FieldStatsResult priceStatResult = statResultPage.getFieldStatsResult("price"); @@ -245,7 +245,7 @@ StatsOptions statsOptions = new StatsOptions() // query SimpleQuery statsQuery = new SimpleQuery("*:*"); statsQuery.setStatsOptions(statsOptions); -StatsPage statsPage = solrTemplate.queryForStatsPage("collection-1", statsQuery, Product.class); +StatsPage statsPage = solrTemplate.queryForStatsPage(statsQuery, Product.class); // field stats FieldStatsResult categoryStatResult = statResultPage.getFieldStatsResult("category"); @@ -413,7 +413,7 @@ To highlight matches in search result add `HighlightOptions` to the `SimpleHighl ---- SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("name:with")); query.setHighlightOptions(new HighlightOptions()); -HighlightPage page = solrTemplate.queryForHighlightPage("collection-1", query, Product.class); +HighlightPage page = solrTemplate.queryForHighlightPage(query, Product.class); ---- ==== @@ -551,7 +551,7 @@ NOTE: realtime get relies on the update log feature. ==== [source,java] ---- -Optional product = solrTemplate.getById("collection-1", "123", Product.class); +Product product = solrTemplate.getById("123", Product.class); ---- ==== @@ -562,7 +562,7 @@ Multiple documents can be retrieved by providing a collection of ids as follows: [source,java] ---- Collection ids = Arrays.asList("123", "134"); -Collection products = solrTemplate.getByIds("collection-1", ids, Product.class); +Collection products = solrTemplate.getById(ids, Product.class); ---- ==== @@ -590,60 +590,4 @@ public class MyEntity { } ---- -==== - -[[solr.misc.child-documents]] -== Nested Documents - -Nested Documents provides the ability to add documents inside of other documents in a parent/child relationship. - -The nested documents need to be indexed along with the parent one and cannot be updated individually. Though nested documents will appear as individual ones in the index. -Resolving the parent child relation is done at query query time. - -To indicate a property should be treated as nested object it has to be annotated with either `@o.a.s.c.solrj.beans.Field(child=true)` or `@o.s.d.s.core.mapping.ChildDocument`. - -==== -[source,java] ----- -public class Book { - - @Id String id; - @Indexed("type_s") String type; - @Indexed("title_t") String title; - @Indexed("author_s") String author; - @Indexed("publisher_s") String publisher; - - @ChildDocument List reviews; <1> - - // setters and getters ... - -} - -public class Review { - - @Id String id; <2> - @Indexed("type_s") String type; - @Indexed("review_dt") Date date; - @Indexed("stars_i") int stars; - @Indexed("author_s") String author; - @Indexed("comment_t") String comment; - -} ----- -<1> Multiple child documents can be associated with a prarent one, or just use the domain type to store a single relation ship. -<2> Note that the nested document also needs to have an unique `id` assigned. -==== - -Assuming `Book#type` is _book_, and `Review#type` resolves to _review_ retrieving `Book` with its child relations `reviews` can be done by altering the `fl` query parameter. - -==== -[source,java] ----- -Query query = new SimpleQuery(where("id").is("theWayOfKings")); -query.addProjectionOnField(new SimpleField("*")); -query.addProjectionOnField(new SimpleField("[child parentFilter=type_s:book]")); <1> - -return solrTemplate.queryForObject("books", query, Book.class); ----- -<1> The parent filter always defines the complete set of parent documents in the index, not the one for a single document. ==== \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/SolrRealtimeGetRequest.java b/src/main/java/org/springframework/data/solr/SolrRealtimeGetRequest.java new file mode 100644 index 0000000..ada6895 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/SolrRealtimeGetRequest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014 - 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.solr; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrRequest; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.params.ModifiableSolrParams; +import org.apache.solr.common.params.SolrParams; +import org.apache.solr.common.util.ContentStream; +import org.springframework.util.Assert; + +/** + * @author Christoph Strobl + * @since 1.4 + * @deprecated since 2.1. Please use {@link SolrClient#getById(Collection)} instead. + */ +@Deprecated +public class SolrRealtimeGetRequest extends SolrRequest { + + private static final long serialVersionUID = 1500782684874146272L; + private Collection ids; + + public SolrRealtimeGetRequest(Serializable... ids) { + this(Arrays.asList(ids)); + } + + public SolrRealtimeGetRequest(Collection ids) { + super(METHOD.GET, "/get"); + + Assert.notEmpty(ids, "At least one 'id' is required for real time get request."); + Assert.noNullElements(ids.toArray(), "Real time get request can't be made for 'null' id."); + + toStringIds(ids); + } + + private void toStringIds(Collection ids) { + + this.ids = new ArrayList(ids.size()); + for (Serializable id : ids) { + this.ids.add(id.toString()); + } + } + + @Override + public SolrParams getParams() { + return new ModifiableSolrParams().add("ids", this.ids.toArray(new String[this.ids.size()])); + } + + @Override + public Collection getContentStreams() throws IOException { + return null; + } + + @Override + protected QueryResponse createResponse(SolrClient client) { + return new QueryResponse(); + } +} diff --git a/src/main/java/org/springframework/data/solr/VersionUtil.java b/src/main/java/org/springframework/data/solr/VersionUtil.java index 1d46c5f..72fb4ae 100644 --- a/src/main/java/org/springframework/data/solr/VersionUtil.java +++ b/src/main/java/org/springframework/data/solr/VersionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -18,8 +18,8 @@ import org.springframework.util.ClassUtils; /** - * Version util uses {@link org.springframework.util.ClassUtils#isPresent(String, ClassLoader)} to determine presence of - * certain classes that are unique to some libraries, which allows to en-/disable some of the features in eg. + * Version util uses {@link org.springframework.util.ClassUtils#isPresent(String)} to determine presence of certain + * classes that are unique to some libraries, which allows to en-/disable some of the features in eg. * {@link org.springframework.data.solr.core.DefaultQueryParser}. * * @author Christoph Strobl @@ -30,13 +30,54 @@ private VersionUtil() { // hide utility class constructor } + private static final boolean IS_SOLR_3_X_AVAILABLE = ClassUtils + .isPresent("org.apache.solr.client.solrj.impl.CommonsHttpSolrServer", VersionUtil.class.getClassLoader()); + private static final boolean IS_JODATIME_AVAILABLE = ClassUtils.isPresent("org.joda.time.DateTime", VersionUtil.class.getClassLoader()); + private static final boolean IS_SOLR_4_2_AVAILABLE = ClassUtils.isPresent("org.apache.solr.parser.ParseException", + VersionUtil.class.getClassLoader()); + + private static final boolean IS_SOLR_4_X_AVAILABLE = ClassUtils + .isPresent("org.apache.solr.client.solrj.impl.CloudSolrServer", VersionUtil.class.getClassLoader()); + + private static final boolean IS_SOLR_5_X_AVAILABLE = ClassUtils.isPresent("org.apache.solr.client.solrj.SolrClient", + VersionUtil.class.getClassLoader()); + /** * @return true if {@code org.joda.time.DateTime} is in path */ public static boolean isJodaTimeAvailable() { return IS_JODATIME_AVAILABLE; } + + /** + * @return true if {@link org.apache.solr.client.solrj.impl.CommonsHttpSolrServer} (removed in solr 4.0.0) is in path + */ + public static boolean isSolr3XAvailable() { + return IS_SOLR_3_X_AVAILABLE; + } + + /** + * @return true if {@link org.apache.solr.client.solrj.impl.CloudSolrServer} (introduced in solr 4.0.0) is in path + */ + public static boolean isSolr4XAvailable() { + return IS_SOLR_4_X_AVAILABLE; + } + + /** + * @return true if {@code org.apache.solr.parser.ParseException} is in path + */ + public static boolean isSolr420Available() { + return IS_SOLR_4_2_AVAILABLE; + } + + /** + * @return true if {@link org.apache.solr.client.solrj.SolrClient} (introduced in solr 5.0.0) is in path + */ + public static boolean isSolr5XAvailable() { + return IS_SOLR_5_X_AVAILABLE; + } + } diff --git a/src/main/java/org/springframework/data/solr/config/package-info.java b/src/main/java/org/springframework/data/solr/config/package-info.java index 7871fdd..52f1cac 100644 --- a/src/main/java/org/springframework/data/solr/config/package-info.java +++ b/src/main/java/org/springframework/data/solr/config/package-info.java @@ -1,6 +1,4 @@ /** * Spring XML namespace configuration for Solr specific repositories and SolrClient */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields package org.springframework.data.solr.config; \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/core/CollectionCallback.java b/src/main/java/org/springframework/data/solr/core/CollectionCallback.java new file mode 100644 index 0000000..4833694 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/CollectionCallback.java @@ -0,0 +1,41 @@ +/* + * 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.solr.core; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrServerException; + +/** + * Callback interface for data access code that works with {@link SolrClient}. To be used with {@link SolrOperations} to + * execute methods. + * + * @author Christoph Strobl + * @since 2.1 + * @param + */ +public interface CollectionCallback { + + /** + * @param solrClient execute + * @param collection the collection to operate on + * @return + * @throws SolrServerException + * @throws IOException + */ + T doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException; +} diff --git a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java index 6bc8ee2..e7b816f 100644 --- a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; import java.util.List; import java.util.Map.Entry; @@ -34,6 +35,7 @@ import org.slf4j.LoggerFactory; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; +import org.springframework.data.solr.VersionUtil; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.FacetOptions; import org.springframework.data.solr.core.query.FacetOptions.FacetParameter; @@ -55,7 +57,6 @@ import org.springframework.data.solr.core.query.SolrDataQuery; import org.springframework.data.solr.core.query.SpellcheckOptions; import org.springframework.data.solr.core.query.StatsOptions; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; @@ -89,7 +90,7 @@ public class DefaultQueryParser extends QueryParserBase { public final SolrQuery doConstructSolrQuery(SolrDataQuery query) { Assert.notNull(query, "Cannot construct solrQuery from null value."); Assert.notNull(query.getCriteria(), "Query has to have a criteria."); - + SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam(CommonParams.Q, getQueryString(query)); if (query instanceof Query) { @@ -114,30 +115,16 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { appendTimeAllowed(solrQuery, query.getTimeAllowed()); appendDefType(solrQuery, query.getDefType()); appendRequestHandler(solrQuery, query.getRequestHandler()); - appendReRankQueryHandler(solrQuery,query.getRqqValue()); processGroupOptions(solrQuery, query); processStatsOptions(solrQuery, query); processSpellcheckOptions(solrQuery, query); - LOGGER.info(solrQuery.toQueryString()); - if (LOGGER.isDebugEnabled()) { LOGGER.debug("Constructed SolrQuery:\r\n %s", solrQuery); } } - /** - * @param solrQuery - * @param rqqValue - */ - private void appendReRankQueryHandler(SolrQuery solrQuery, String rqqValue) { - if(StringUtils.isNotBlank(rqqValue)) { - solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); - solrQuery.set("rqq", rqqValue); - } - } - private void processFacetOptions(SolrQuery solrQuery, FacetQuery query) { if (enableFaceting(solrQuery, query)) { appendFacetingOnFields(solrQuery, (FacetQuery) query); @@ -265,7 +252,7 @@ private void processSpellcheckOptions(SolrQuery solrQuery, Query query) { SpellcheckOptions options = query.getSpellcheckOptions(); - if (options.getQuery() != null && options.getQuery().getCriteria() != null) { + if (options.getQuery() != null) { solrQuery.set(SpellingParams.SPELLCHECK_Q, createQueryStringFromCriteria(options.getQuery().getCriteria())); } @@ -274,8 +261,9 @@ private void processSpellcheckOptions(SolrQuery solrQuery, Query query) { for (Entry entry : options.getParams().entrySet()) { if (entry.getValue() instanceof Iterable) { - for (Object o : ((Iterable) entry.getValue())) { - params.add(entry.getKey(), o.toString()); + Iterator it = ((Iterable) entry.getValue()).iterator(); + while (it.hasNext()) { + params.add(entry.getKey(), it.next().toString()); } } else if (ObjectUtils.isArray(entry.getValue())) { for (Object o : ObjectUtils.toObjectArray(entry.getValue())) { @@ -357,8 +345,8 @@ private boolean enableFaceting(SolrQuery solrQuery, FacetQuery query) { solrQuery.setFacetMinCount(facetOptions.getFacetMinCount()); solrQuery.setFacetLimit(facetOptions.getPageable().getPageSize()); if (facetOptions.getPageable().getPageNumber() > 0) { - long offset = Math.max(0, facetOptions.getPageable().getOffset()); - solrQuery.set(FacetParams.FACET_OFFSET, "" + offset); + int offset = Math.max(0, facetOptions.getPageable().getOffset()); + solrQuery.set(FacetParams.FACET_OFFSET, offset); } if (FacetOptions.FacetSort.INDEX.equals(facetOptions.getFacetSort())) { solrQuery.setFacetSort(FacetParams.FACET_SORT_INDEX); @@ -447,6 +435,10 @@ private void appendFacetingQueries(SolrQuery solrQuery, FacetQuery query) { } private void appendFacetingOnPivot(SolrQuery solrQuery, FacetQuery query) { + if (VersionUtil.isSolr3XAvailable()) { + throw new UnsupportedOperationException( + "Pivot Facets are not available for solr version lower than 4.x - Please check your depdendencies."); + } FacetOptions facetOptions = query.getFacetOptions(); String[] pivotFields = convertFieldListToStringArray(facetOptions.getFacetOnPivots()); @@ -476,7 +468,7 @@ protected void appendFilterQuery(SolrQuery solrQuery, List filterQu * @param solrQuery * @param sort */ - protected void appendSort(SolrQuery solrQuery, @Nullable Sort sort) { + protected void appendSort(SolrQuery solrQuery, Sort sort) { if (sort == null) { return; } @@ -501,7 +493,7 @@ private String[] convertStringListToArray(List listOfString) { } private List getFilterQueryStrings(List filterQueries) { - List filterQueryStrings = new ArrayList<>(filterQueries.size()); + List filterQueryStrings = new ArrayList(filterQueries.size()); for (FilterQuery filterQuery : filterQueries) { String filterQueryString = getQueryString(filterQuery); diff --git a/src/main/java/org/springframework/data/solr/core/QueryParser.java b/src/main/java/org/springframework/data/solr/core/QueryParser.java index e96896e..3fe9356 100644 --- a/src/main/java/org/springframework/data/solr/core/QueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/QueryParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -27,14 +27,14 @@ * Will be parsed to a SolrQuery that outputs the following * q=field_1%3Avalue_1+AND+field_2%3Avalue_2*&fl=field_3&start=0&rows=10 * - * + * * @author Christoph Strobl */ public interface QueryParser { /** * Convert given Query into a SolrQuery executable via {@link SolrClient} - * + * * @param query * @return */ @@ -42,7 +42,7 @@ public interface QueryParser { /** * Get the queryString to use withSolrQuery.setParam(CommonParams.Q, "queryString"} - * + * * @param query * @return String representation of query without faceting, pagination, projection... */ @@ -50,7 +50,7 @@ public interface QueryParser { /** * Register an additional converter for transforming object values to solr readable format - * + * * @param converter */ void registerConverter(Converter converter); diff --git a/src/main/java/org/springframework/data/solr/core/QueryParserBase.java b/src/main/java/org/springframework/data/solr/core/QueryParserBase.java index bb0adeb..cf1bbff 100644 --- a/src/main/java/org/springframework/data/solr/core/QueryParserBase.java +++ b/src/main/java/org/springframework/data/solr/core/QueryParserBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -54,7 +54,6 @@ import org.springframework.data.solr.core.query.Query.Operator; import org.springframework.data.solr.core.query.QueryStringHolder; import org.springframework.data.solr.core.query.SolrDataQuery; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -75,7 +74,7 @@ public abstract class QueryParserBase implement protected static final String BOOST = "^"; protected final GenericConversionService conversionService = new GenericConversionService(); - private final List critieraEntryProcessors = new ArrayList<>(); + private final List critieraEntryProcessors = new ArrayList(); private final PredicateProcessor defaultProcessor = new DefaultProcessor(); { @@ -181,6 +180,7 @@ protected String createQueryStringFromCriteria(Criteria criteria) { /** * Creates query string representation of a single critiera * + * @param criteria * @return */ protected String createQueryFragmentForCriteria(Criteria part) { @@ -222,13 +222,13 @@ protected String createQueryFragmentForCriteria(Criteria part) { queryFragment.append(")"); } if (!Float.isNaN(criteria.getBoost())) { - queryFragment.append(BOOST).append(criteria.getBoost()); + queryFragment.append(BOOST + criteria.getBoost()); } return queryFragment.toString(); } - private String getNullsafeFieldName(@Nullable Field field) { + private String getNullsafeFieldName(Field field) { if (field == null || field.getName() == null) { return ""; } @@ -265,7 +265,7 @@ protected String createFunctionFragment(Function function, int level) { sb.append(function.getOperation()); sb.append('('); if (function.hasArguments()) { - List solrReadableArguments = new ArrayList<>(); + List solrReadableArguments = new ArrayList(); for (Object arg : function.getArguments()) { Assert.notNull(arg, "Unable to parse 'null' within function arguments."); if (arg instanceof Function) { @@ -295,7 +295,7 @@ protected String createFunctionFragment(Function function, int level) { * @param query * @return */ - protected String prependJoin(String queryString, @Nullable SolrDataQuery query) { + protected String prependJoin(String queryString, SolrDataQuery query) { if (query == null || query.getJoin() == null) { return queryString; } @@ -312,12 +312,12 @@ protected String prependJoin(String queryString, @Nullable SolrDataQuery query) * @param offset * @param rows */ - protected void appendPagination(SolrQuery query, @Nullable Long offset, @Nullable Integer rows) { + protected void appendPagination(SolrQuery query, Integer offset, Integer rows) { if (offset != null && offset.intValue() >= 0) { - query.setStart(offset.intValue()); + query.setStart(offset); } - if (rows != null && rows >= 0) { + if (rows != null && rows.intValue() >= 0) { query.setRows(rows); } } @@ -332,7 +332,7 @@ protected void appendProjectionOnFields(SolrQuery solrQuery, List fields) if (CollectionUtils.isEmpty(fields)) { return; } - List solrReadableFields = new ArrayList<>(); + List solrReadableFields = new ArrayList(); for (Field field : fields) { if (field instanceof CalculatedField) { solrReadableFields.add(createCalculatedFieldFragment((CalculatedField) field)); @@ -349,7 +349,7 @@ protected void appendProjectionOnFields(SolrQuery solrQuery, List fields) * @param solrQuery * @param defaultOperator */ - protected void appendDefaultOperator(SolrQuery solrQuery, @Nullable Operator defaultOperator) { + protected void appendDefaultOperator(SolrQuery solrQuery, Operator defaultOperator) { if (defaultOperator != null && !Query.Operator.NONE.equals(defaultOperator)) { solrQuery.set("q.op", defaultOperator.asQueryStringRepresentation()); } @@ -361,7 +361,7 @@ protected void appendDefaultOperator(SolrQuery solrQuery, @Nullable Operator def * @param solrQuery * @param timeAllowed */ - protected void appendTimeAllowed(SolrQuery solrQuery, @Nullable Integer timeAllowed) { + protected void appendTimeAllowed(SolrQuery solrQuery, Integer timeAllowed) { if (timeAllowed != null) { solrQuery.setTimeAllowed(timeAllowed); } @@ -373,7 +373,7 @@ protected void appendTimeAllowed(SolrQuery solrQuery, @Nullable Integer timeAllo * @param solrQuery * @param defType */ - protected void appendDefType(SolrQuery solrQuery, @Nullable String defType) { + protected void appendDefType(SolrQuery solrQuery, String defType) { if (StringUtils.isNotBlank(defType)) { solrQuery.set("defType", defType); } @@ -385,7 +385,7 @@ protected void appendDefType(SolrQuery solrQuery, @Nullable String defType) { * @param solrQuery * @param requestHandler */ - protected void appendRequestHandler(SolrQuery solrQuery, @Nullable String requestHandler) { + protected void appendRequestHandler(SolrQuery solrQuery, String requestHandler) { if (StringUtils.isNotBlank(requestHandler)) { solrQuery.add(CommonParams.QT, requestHandler); } @@ -421,7 +421,7 @@ public interface PredicateProcessor { * @param predicate * @return true if predicate can be processed by this parser */ - boolean canProcess(@Nullable Predicate predicate); + boolean canProcess(Predicate predicate); /** * Create query string representation of given {@link Predicate} @@ -430,7 +430,7 @@ public interface PredicateProcessor { * @param field * @return */ - Object process(@Nullable Predicate predicate, @Nullable Field field); + Object process(Predicate predicate, Field field); } @@ -450,7 +450,6 @@ class CriteriaQueryStringValueProvider implements Iterator { } @SuppressWarnings("unchecked") - @Nullable private T getPredicateValue(Predicate predicate) { PredicateProcessor processor = findMatchingProcessor(predicate); return (T) processor.process(predicate, criteria.getField()); @@ -474,7 +473,8 @@ public boolean hasNext() { @Override public String next() { Object o = getPredicateValue(this.delegate.next()); - return o != null ? o.toString() : null; + String s = o != null ? o.toString() : null; + return s; } @Override @@ -500,7 +500,7 @@ abstract class BasePredicateProcessor implements PredicateProcessor { "\\(", "\\)", "\\{", "\\}", "\\[", "\\]", "\\^", "\\~", "\\*", "\\?", "\\:", "\\\\" }; @Override - public Object process(@Nullable Predicate predicate, @Nullable Field field) { + public Object process(Predicate predicate, Field field) { if (predicate == null || predicate.getValue() == null) { return null; } @@ -529,8 +529,7 @@ private String processWhiteSpaces(String criteriaValue) { return criteriaValue; } - @Nullable - protected abstract Object doProcess(@Nullable Predicate predicate, Field field); + protected abstract Object doProcess(Predicate predicate, Field field); } @@ -542,15 +541,12 @@ private String processWhiteSpaces(String criteriaValue) { class DefaultProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { + public boolean canProcess(Predicate predicate) { return true; } @Override - public Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + public Object doProcess(Predicate predicate, Field field) { return filterCriteriaValue(predicate.getValue()); } @@ -564,14 +560,12 @@ public Object doProcess(@Nullable Predicate predicate, Field field) { class ExpressionProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.EXPRESSION.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.EXPRESSION.getKey().equals(predicate.getKey()); } @Override - public Object doProcess(@Nullable Predicate predicate, Field field) { - Assert.notNull(predicate, "Predicate must not be null!"); - + public Object doProcess(Predicate predicate, Field field) { return predicate.getValue().toString(); } @@ -587,20 +581,20 @@ class BetweenProcessor extends BasePredicateProcessor { private static final String RANGE_OPERATOR = " TO "; @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.BETWEEN.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.BETWEEN.getKey().equals(predicate.getKey()); } @Override - public Object doProcess(@Nullable Predicate predicate, Field field) { + public Object doProcess(Predicate predicate, Field field) { Object[] args = (Object[]) predicate.getValue(); - String rangeFragment = (Boolean) args[2] ? "[" : "{"; + String rangeFragment = ((Boolean) args[2]).booleanValue() ? "[" : "{"; rangeFragment += createRangeFragment(args[0], args[1]); - rangeFragment += (Boolean) args[3] ? "]" : "}"; + rangeFragment += ((Boolean) args[3]).booleanValue() ? "]" : "}"; return rangeFragment; } - protected String createRangeFragment(@Nullable Object rangeStart, @Nullable Object rangeEnd) { + protected String createRangeFragment(Object rangeStart, Object rangeEnd) { String rangeFragment = ""; rangeFragment += (rangeStart != null ? filterCriteriaValue(rangeStart) : Criteria.WILDCARD); rangeFragment += RANGE_OPERATOR; @@ -618,15 +612,12 @@ protected String createRangeFragment(@Nullable Object rangeStart, @Nullable Obje class NearProcessor extends BetweenProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.NEAR.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.NEAR.getKey().equals(predicate.getKey()); } @Override - public Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + public Object doProcess(Predicate predicate, Field field) { String nearFragment; Object[] args = (Object[]) predicate.getValue(); if (args[0] instanceof Box) { @@ -641,7 +632,7 @@ public Object doProcess(@Nullable Predicate predicate, Field field) { return nearFragment; } - protected String createSpatialFunctionFragment(@Nullable String fieldName, org.springframework.data.geo.Point location, + protected String createSpatialFunctionFragment(String fieldName, org.springframework.data.geo.Point location, Distance distance, String function) { String spatialFragment = "{!" + function + " " + SpatialParams.POINT + "="; spatialFragment += filterCriteriaValue(location); @@ -661,16 +652,12 @@ protected String createSpatialFunctionFragment(@Nullable String fieldName, org.s class WithinProcessor extends NearProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { + public boolean canProcess(Predicate predicate) { return OperationKey.WITHIN.getKey().equals(predicate.getKey()); } - @Nullable @Override - public Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + public Object doProcess(Predicate predicate, Field field) { Object[] args = (Object[]) predicate.getValue(); return createSpatialFunctionFragment(field.getName(), (org.springframework.data.geo.Point) args[0], (Distance) args[1], "geofilt"); @@ -686,16 +673,12 @@ public Object doProcess(@Nullable Predicate predicate, Field field) { class FuzzyProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.FUZZY.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.FUZZY.getKey().equals(predicate.getKey()); } - @Nullable @Override - protected Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + protected Object doProcess(Predicate predicate, Field field) { Object[] args = (Object[]) predicate.getValue(); Float distance = (Float) args[1]; return filterCriteriaValue(args[0]) + "~" + (distance.isNaN() ? "" : distance); @@ -711,16 +694,12 @@ protected Object doProcess(@Nullable Predicate predicate, Field field) { class SloppyProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.SLOPPY.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.SLOPPY.getKey().equals(predicate.getKey()); } - @Nullable @Override - protected Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + protected Object doProcess(Predicate predicate, Field field) { Object[] args = (Object[]) predicate.getValue(); Integer distance = (Integer) args[1]; return filterCriteriaValue(args[0]) + "~" + distance; @@ -737,17 +716,14 @@ protected Object doProcess(@Nullable Predicate predicate, Field field) { class WildcardProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && (OperationKey.CONTAINS.getKey().equals(predicate.getKey()) + public boolean canProcess(Predicate predicate) { + return OperationKey.CONTAINS.getKey().equals(predicate.getKey()) || OperationKey.STARTS_WITH.getKey().equals(predicate.getKey()) - || OperationKey.ENDS_WITH.getKey().equals(predicate.getKey())); + || OperationKey.ENDS_WITH.getKey().equals(predicate.getKey()); } @Override - protected Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + protected Object doProcess(Predicate predicate, Field field) { Object filteredValue = filterCriteriaValue(predicate.getValue()); if (OperationKey.CONTAINS.getKey().equals(predicate.getKey())) { return Criteria.WILDCARD + filteredValue + Criteria.WILDCARD; @@ -768,22 +744,18 @@ protected Object doProcess(@Nullable Predicate predicate, Field field) { class FunctionProcessor extends BasePredicateProcessor { @Override - public boolean canProcess(@Nullable Predicate predicate) { - return predicate != null && OperationKey.FUNCTION.getKey().equals(predicate.getKey()); + public boolean canProcess(Predicate predicate) { + return OperationKey.FUNCTION.getKey().equals(predicate.getKey()); } @Override - @Nullable - protected Object doProcess(@Nullable Predicate predicate, Field field) { - - Assert.notNull(predicate, "Predicate must not be null!"); - + protected Object doProcess(Predicate predicate, Field field) { return createFunctionFragment((Function) predicate.getValue(), 0); } } - private static void setObjectName(Map namesAssociation, Object object, String name) { + private static final void setObjectName(Map namesAssociation, Object object, String name) { namesAssociation.put(name, object); } @@ -805,7 +777,7 @@ interface NamedObjects { */ static class NamedObjectsQuery extends AbstractQueryDecorator implements NamedObjects { - private Map namesAssociation = new HashMap<>(); + private Map namesAssociation = new HashMap(); public NamedObjectsQuery(Query query) { super(query); @@ -830,7 +802,7 @@ public Map getNamesAssociation() { */ static class NamedObjectsFacetQuery extends AbstractFacetQueryDecorator implements NamedObjects { - private Map namesAssociation = new HashMap<>(); + private Map namesAssociation = new HashMap(); public NamedObjectsFacetQuery(FacetQuery query) { super(query); @@ -854,7 +826,7 @@ public Map getNamesAssociation() { */ static class NamedObjectsHighlightQuery extends AbstractHighlightQueryDecorator implements NamedObjects { - private Map namesAssociation = new HashMap<>(); + private Map namesAssociation = new HashMap(); public NamedObjectsHighlightQuery(HighlightQuery query) { super(query); @@ -879,7 +851,7 @@ public Map getNamesAssociation() { static class NamedObjectsFacetAndHighlightQuery extends AbstractFacetAndHighlightQueryDecorator implements NamedObjects { - private Map namesAssociation = new HashMap<>(); + private Map namesAssociation = new HashMap(); public NamedObjectsFacetAndHighlightQuery(FacetAndHighlightQuery query) { super(query); diff --git a/src/main/java/org/springframework/data/solr/core/QueryParsers.java b/src/main/java/org/springframework/data/solr/core/QueryParsers.java index 0d7d192..689c702 100644 --- a/src/main/java/org/springframework/data/solr/core/QueryParsers.java +++ b/src/main/java/org/springframework/data/solr/core/QueryParsers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -38,10 +38,10 @@ public class QueryParsers { private final List parserPairs; - private final Map, QueryParser> cache = new LinkedHashMap<>(); + private final Map, QueryParser> cache = new LinkedHashMap, QueryParser>(); public QueryParsers() { - this.parserPairs = new ArrayList<>(4); + this.parserPairs = new ArrayList(4); parserPairs.add(new QueryParserPair(TermsQuery.class, new TermsQueryParser())); parserPairs.add(new QueryParserPair(FacetQuery.class, DEFAULT_QUERY_PARSER)); @@ -86,6 +86,7 @@ public void registerParser(Class clazz, QueryParser par * QueryParserPair holds reference form the {@link SolrQuery} to the {@link QueryParser} suitable for it * * @author Christoph Strobl + * */ private static class QueryParserPair { @@ -106,6 +107,7 @@ public QueryParser getParser() { } /** + * * @param clazz * @return true if {@link ClassUtils#isAssignable(Class, Class)} */ diff --git a/src/main/java/org/springframework/data/solr/core/RequestMethod.java b/src/main/java/org/springframework/data/solr/core/RequestMethod.java index 0e6e62d..b5b4395 100644 --- a/src/main/java/org/springframework/data/solr/core/RequestMethod.java +++ b/src/main/java/org/springframework/data/solr/core/RequestMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-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. @@ -26,6 +26,6 @@ */ public enum RequestMethod { - GET, POST, PUT + GET, POST, PUT; } diff --git a/src/main/java/org/springframework/data/solr/core/ResultHelper.java b/src/main/java/org/springframework/data/solr/core/ResultHelper.java index 631fced..b21fe1d 100644 --- a/src/main/java/org/springframework/data/solr/core/ResultHelper.java +++ b/src/main/java/org/springframework/data/solr/core/ResultHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -44,16 +44,33 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; -import org.springframework.data.mapping.MappingException; +import org.springframework.data.mapping.model.MappingException; import org.springframework.data.repository.util.ClassUtils; +import org.springframework.data.solr.VersionUtil; import org.springframework.data.solr.core.query.FacetQuery; import org.springframework.data.solr.core.query.Field; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SimpleField; import org.springframework.data.solr.core.query.SimplePivotField; -import org.springframework.data.solr.core.query.result.*; +import org.springframework.data.solr.core.query.result.FacetFieldEntry; +import org.springframework.data.solr.core.query.result.FacetPivotFieldEntry; +import org.springframework.data.solr.core.query.result.FacetQueryEntry; +import org.springframework.data.solr.core.query.result.FieldStatsResult; +import org.springframework.data.solr.core.query.result.GroupEntry; +import org.springframework.data.solr.core.query.result.GroupResult; +import org.springframework.data.solr.core.query.result.HighlightEntry; +import org.springframework.data.solr.core.query.result.SimpleFacetFieldEntry; +import org.springframework.data.solr.core.query.result.SimpleFacetPivotEntry; +import org.springframework.data.solr.core.query.result.SimpleFacetQueryEntry; +import org.springframework.data.solr.core.query.result.SimpleFieldStatsResult; +import org.springframework.data.solr.core.query.result.SimpleGroupEntry; +import org.springframework.data.solr.core.query.result.SimpleGroupResult; +import org.springframework.data.solr.core.query.result.SimpleStatsResult; +import org.springframework.data.solr.core.query.result.SimpleTermsFieldEntry; +import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; -import org.springframework.lang.Nullable; +import org.springframework.data.solr.core.query.result.StatsResult; +import org.springframework.data.solr.core.query.result.TermsFieldEntry; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -61,7 +78,7 @@ /** * Use Result Helper to extract various parameters from the QueryResponse and convert it into a proper Format taking * care of non existent and null elements with the response. - * + * * @author Christoph Strobl * @author Francisco Spaeth * @author Venil Noronha @@ -70,16 +87,17 @@ final class ResultHelper { private ResultHelper() {} - static Map> convertTermsQueryResponseToTermsMap(@Nullable QueryResponse response) { + static Map> convertTermsQueryResponseToTermsMap(QueryResponse response) { if (response == null || response.getTermsResponse() == null || response.getTermsResponse().getTermMap() == null) { return Collections.emptyMap(); } TermsResponse termsResponse = response.getTermsResponse(); - Map> result = new LinkedHashMap<>(termsResponse.getTermMap().size()); + Map> result = new LinkedHashMap>( + termsResponse.getTermMap().size()); for (Map.Entry> entry : termsResponse.getTermMap().entrySet()) { - List terms = new ArrayList<>(entry.getValue().size()); + List terms = new ArrayList(entry.getValue().size()); for (Term term : entry.getValue()) { SimpleTermsFieldEntry termsEntry = new SimpleTermsFieldEntry(term.getTerm(), term.getFrequency()); termsEntry.setField(entry.getKey()); @@ -98,7 +116,7 @@ static Map> convertFacetQueryResponseToFacetPageMap if (!hasFacets(query, response)) { return Collections.emptyMap(); } - Map> facetResult = new LinkedHashMap<>(); + Map> facetResult = new LinkedHashMap>(); if (!CollectionUtils.isEmpty(response.getFacetFields())) { int initalPageSize = Math.max(1, query.getFacetOptions().getPageable().getPageSize()); @@ -106,16 +124,16 @@ static Map> convertFacetQueryResponseToFacetPageMap if (facetField != null && StringUtils.hasText(facetField.getName())) { Field field = new SimpleField(facetField.getName()); if (!CollectionUtils.isEmpty(facetField.getValues())) { - List pageEntries = new ArrayList<>(initalPageSize); + List pageEntries = new ArrayList(initalPageSize); for (Count count : facetField.getValues()) { if (count != null) { pageEntries.add(new SimpleFacetFieldEntry(field, count.getName(), count.getCount())); } } - facetResult.put(field, new SolrResultPage<>(pageEntries, query.getFacetOptions().getPageable(), - facetField.getValueCount(), null)); + facetResult.put(field, new SolrResultPage(pageEntries, + query.getFacetOptions().getPageable(), facetField.getValueCount(), null)); } else { - facetResult.put(field, new SolrResultPage<>(Collections. emptyList(), + facetResult.put(field, new SolrResultPage(Collections. emptyList(), query.getFacetOptions().getPageable(), 0, null)); } } @@ -127,7 +145,12 @@ static Map> convertFacetQueryResponseToFacetPageMap static Map> convertFacetQueryResponseToFacetPivotMap( FacetQuery query, QueryResponse response) { - Map> facetResult = new LinkedHashMap<>(); + if (VersionUtil.isSolr3XAvailable()) { + // pivot facets are a solr 4+ Feature + return Collections.emptyMap(); + } + + Map> facetResult = new LinkedHashMap>(); NamedList> facetPivot = response.getFacetPivot(); if (facetPivot != null && facetPivot.size() > 0) { for (int i = 0; i < facetPivot.size(); i++) { @@ -145,7 +168,7 @@ private static List convertPivotResult(List pi return Collections.emptyList(); } - ArrayList pivotFieldEntries = new ArrayList<>(); + ArrayList pivotFieldEntries = new ArrayList(); for (PivotField pivotField : pivotResult) { SimpleFacetPivotEntry pivotFieldEntry = new SimpleFacetPivotEntry(new SimpleField(pivotField.getField()), @@ -175,7 +198,7 @@ static Map> convertFacetQueryResponseToRangeFacetPa if (!hasFacets(query, response) || CollectionUtils.isEmpty(response.getFacetRanges())) { return Collections.emptyMap(); } - Map> facetResult = new LinkedHashMap<>(); + Map> facetResult = new LinkedHashMap>(); Pageable pageable = query.getFacetOptions().getPageable(); int initalPageSize = pageable.getPageSize(); @@ -190,7 +213,7 @@ static Map> convertFacetQueryResponseToRangeFacetPa List entries; long total; if (!CollectionUtils.isEmpty(rangeFacet.getCounts())) { - entries = new ArrayList<>(initalPageSize); + entries = new ArrayList(initalPageSize); for (RangeFacet.Count count : rangeFacet.getCounts()) { entries.add(new SimpleFacetFieldEntry(field, count.getValue(), count.getCount())); } @@ -200,7 +223,7 @@ static Map> convertFacetQueryResponseToRangeFacetPa total = 0; } - facetResult.put(field, new SolrResultPage<>(entries, pageable, total, null)); + facetResult.put(field, new SolrResultPage(entries, pageable, total, null)); } @@ -214,7 +237,7 @@ static List convertFacetQueryResponseToFacetQueryResult(FacetQu return Collections.emptyList(); } - List facetResult = new ArrayList<>(); + List facetResult = new ArrayList(); if (!CollectionUtils.isEmpty(response.getFacetQuery())) { for (Entry entry : response.getFacetQuery().entrySet()) { @@ -224,13 +247,13 @@ static List convertFacetQueryResponseToFacetQueryResult(FacetQu return facetResult; } - static List> convertAndAddHighlightQueryResponseToResultPage(@Nullable QueryResponse response, - @Nullable SolrResultPage page) { + static List> convertAndAddHighlightQueryResponseToResultPage(QueryResponse response, + SolrResultPage page) { if (response == null || CollectionUtils.isEmpty(response.getHighlighting()) || page == null) { return Collections.emptyList(); } - List> mappedHighlights = new ArrayList<>(page.getSize()); + List> mappedHighlights = new ArrayList>(page.getSize()); Map>> highlighting = response.getHighlighting(); for (T item : page) { @@ -243,7 +266,7 @@ static List> convertAndAddHighlightQueryResponseToResultPa private static HighlightEntry processHighlightingForPageEntry( Map>> highlighting, T pageEntry) { - HighlightEntry highlightEntry = new HighlightEntry<>(pageEntry); + HighlightEntry highlightEntry = new HighlightEntry(pageEntry); Object itemId = getMappedId(pageEntry); Map> highlights = highlighting.get(itemId.toString()); @@ -269,7 +292,9 @@ private static Object getMappedId(Object o) { if (annotation != null) { try { return FieldUtils.readField(field, o, true); - } catch (IllegalArgumentException | IllegalAccessException e) { + } catch (IllegalArgumentException e) { + throw new MappingException("Id property could not be accessed!", e); + } catch (IllegalAccessException e) { throw new MappingException("Id property could not be accessed!", e); } } @@ -290,19 +315,19 @@ static Map> convertGroupQueryResponseToGroupResultMap return Collections.emptyMap(); } - Map> result = new LinkedHashMap<>(); + Map> result = new LinkedHashMap>(); List values = groupResponse.getValues(); for (GroupCommand groupCommand : values) { - List> groupEntries = new ArrayList<>(); + List> groupEntries = new ArrayList>(); for (Group group : groupCommand.getValues()) { SolrDocumentList documentList = group.getResult(); List beans = solrTemplate.convertSolrDocumentListToBeans(documentList, clazz); - Page page = new PageImpl<>(beans, query.getGroupOptions().getPageRequest(), documentList.getNumFound()); - groupEntries.add(new SimpleGroupEntry<>(group.getGroupValue(), page)); + Page page = new PageImpl(beans, query.getGroupOptions().getPageRequest(), documentList.getNumFound()); + groupEntries.add(new SimpleGroupEntry(group.getGroupValue(), page)); } int matches = groupCommand.getMatches(); @@ -311,12 +336,12 @@ static Map> convertGroupQueryResponseToGroupResultMap PageImpl> page; if (ngroups != null) { - page = new PageImpl<>(groupEntries, query.getPageRequest(), ngroups); + page = new PageImpl>(groupEntries, query.getPageRequest(), ngroups.intValue()); } else { - page = new PageImpl<>(groupEntries); + page = new PageImpl>(groupEntries); } - SimpleGroupResult groupResult = new SimpleGroupResult<>(matches, ngroups, name, page); + SimpleGroupResult groupResult = new SimpleGroupResult(matches, ngroups, name, page); result.put(name, groupResult); if (objectNames.containsKey(name)) { result.put(objectNames.get(name), groupResult); @@ -333,7 +358,7 @@ static Map convertFieldStatsInfoToFieldStatsResultMap( return Collections.emptyMap(); } - Map result = new LinkedHashMap<>(); + Map result = new LinkedHashMap(); for (Entry entry : fieldStatsInfo.entrySet()) { FieldStatsInfo value = entry.getValue(); @@ -363,10 +388,10 @@ static Map convertFieldStatsInfoToFieldStatsResultMap( private static Map> convertFieldStatsInfoToStatsResultMap( Map> statsInfo) { - Map> result = new LinkedHashMap<>(); + Map> result = new LinkedHashMap>(); for (Entry> entry : statsInfo.entrySet()) { - Map facetStatsValues = new LinkedHashMap<>(); + Map facetStatsValues = new LinkedHashMap(); for (FieldStatsInfo fieldStatsInfo : entry.getValue()) { @@ -389,8 +414,16 @@ private static T populateStatsResultWithFieldStats statsResult.setMissing(value.getMissing()); statsResult.setStddev(value.getStddev()); statsResult.setSumOfSquares((Double) new DirectFieldAccessor(value).getPropertyValue("sumOfSquares")); - statsResult.setMean(value.getMean()); - statsResult.setSum(value.getSum()); + + Object mean = value.getMean(); + if (mean instanceof Double) { + statsResult.setMean((Double) mean); + } + + Object sum = value.getSum(); + if (sum instanceof Double) { + statsResult.setSum((Double) sum); + } return statsResult; } @@ -402,12 +435,12 @@ static Map> extreactSuggestions(QueryResponse response return Collections.emptyMap(); } - Map> alternativesMap = new LinkedHashMap<>(); + Map> alternativesMap = new LinkedHashMap>(); SpellCheckResponse scr = response.getSpellCheckResponse(); if (scr != null && scr.getSuggestions() != null) { for (SpellCheckResponse.Suggestion suggestion : scr.getSuggestions()) { - List alternatives = new ArrayList<>(); + List alternatives = new ArrayList(); if (!CollectionUtils.isEmpty(suggestion.getAlternatives())) { for (int i = 0; i < suggestion.getAlternatives().size(); i++) { diff --git a/src/main/java/org/springframework/data/solr/core/SolrCallback.java b/src/main/java/org/springframework/data/solr/core/SolrCallback.java index 17557c8..401de11 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrCallback.java +++ b/src/main/java/org/springframework/data/solr/core/SolrCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -23,7 +23,7 @@ /** * Callback interface for data access code that works with SolrClient. To be used with {@link SolrOperations} to execute * methods. - * + * * @param * @author Christoph Strobl */ diff --git a/src/main/java/org/springframework/data/solr/core/SolrExceptionTranslator.java b/src/main/java/org/springframework/data/solr/core/SolrExceptionTranslator.java index 5c86bd3..55f4733 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrExceptionTranslator.java +++ b/src/main/java/org/springframework/data/solr/core/SolrExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -18,7 +18,6 @@ import java.net.ConnectException; import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrClient.RemoteSolrException; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.springframework.dao.DataAccessException; @@ -33,7 +32,7 @@ * Implementation of {@link org.springframework.dao.support.PersistenceExceptionTranslator} capable of translating * {@link org.apache.solr.client.solrj.SolrServerException} instances to Spring's * {@link org.springframework.dao.DataAccessException} hierarchy. - * + * * @author Christoph Strobl */ public class SolrExceptionTranslator implements PersistenceExceptionTranslator { @@ -46,7 +45,6 @@ public DataAccessException translateExceptionIfPossible(RuntimeException ex) { } if (ex.getCause() instanceof SolrServerException) { - SolrServerException solrServerException = (SolrServerException) ex.getCause(); if (solrServerException.getCause() instanceof SolrException) { SolrException solrException = (SolrException) solrServerException.getCause(); @@ -79,11 +77,6 @@ public DataAccessException translateExceptionIfPossible(RuntimeException ex) { solrServerException.getCause()); } } - - if (ex instanceof RemoteSolrException) { - return new DataAccessResourceFailureException(ex.getMessage(), ex); - } - return null; } } diff --git a/src/main/java/org/springframework/data/solr/core/SolrOperations.java b/src/main/java/org/springframework/data/solr/core/SolrOperations.java index 44d23ca..4a68b99 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrOperations.java +++ b/src/main/java/org/springframework/data/solr/core/SolrOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,9 +15,8 @@ */ package org.springframework.data.solr.core; -import java.time.Duration; +import java.io.Serializable; import java.util.Collection; -import java.util.Optional; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.response.SolrPingResponse; @@ -43,7 +42,7 @@ /** * Interface that specifies a basic set of Solr operations. - * + * * @author Christoph Strobl * @author Joachim Uhrlass * @author Francisco Spaeth @@ -55,435 +54,749 @@ public interface SolrOperations { /** * Get the underlying SolrClient instance * - * @return the {@link SolrClient} in use. Never {@literal null}. + * @return */ SolrClient getSolrClient(); /** * Execute ping against SolrClient and return duration in msec * - * @return {@link SolrPingResponse} containing ping result. - * @throws org.springframework.dao.DataAccessResourceFailureException if ping fails. + * @return */ SolrPingResponse ping(); /** - * Execute ping against SolrClient and return duration in msec + * return number of elements found by for given query * - * @param collection must not be {@literal null}. - * @return {@link SolrPingResponse} containing ping result. - * @throws org.springframework.dao.DataAccessResourceFailureException if ping fails. - * @since 3.0 + * @param query must not be {@literal null}. + * @return */ - SolrPingResponse ping(String collection); + long count(SolrDataQuery query); /** - * return number of elements found by for given query + * Return number of elements found in given collection by for given query * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @param query must not be {@literal null}. - * @return total number of documents matching given query. - * @since 3.0 + * @return + * @since 2.1 */ - long count(String collection, SolrDataQuery query); + long count(String collectionName, SolrDataQuery query); /** * return number of elements found by for given query * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param method must not be {@literal null}. - * @return total number of documents matching given query. - * @since 3.0 + * @return + * @since 2.0 */ - long count(String collection, SolrDataQuery query, RequestMethod method); + long count(SolrDataQuery query, RequestMethod method); /** - * Execute add operation against solr, which will do either insert or update. + * Return number of elements found in collection by for given query. * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 + */ + long count(String collectionName, SolrDataQuery query, RequestMethod method); + + /** + * Execute add operation against solr, which will do either insert or update + * + * @param obj + * @return + */ + UpdateResponse saveBean(Object obj); + + /** + * Execute add operation against specific collection, which will do either insert or update + * + * @param collectionName must not be {@literal null}. * @param obj must not be {@literal null}. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @return + * @since 2.1 */ - default UpdateResponse saveBean(String collection, Object obj) { - return saveBean(collection, obj, Duration.ZERO); - } + UpdateResponse saveBean(String collectionName, Object obj); /** - * Execute add operation against solr, which will do either insert or update with support for commitWithin strategy. + * Execute add operation against solr, which will do either insert or update with support for commitWithin strategy * - * @param collection must not be {@literal null}. * @param obj must not be {@literal null}. - * @param commitWithin max time within server performs commit. - * @return {@link UpdateResponse} containing update result. + * @param commitWithinMs + * @return */ - UpdateResponse saveBean(String collection, Object obj, Duration commitWithin); + UpdateResponse saveBean(Object obj, int commitWithinMs); + + /** + * Execute add operation against specific collection, which will do either insert or update with support for + * commitWithin strategy. + * + * @param collectionName must not be {@literal null}. + * @param objectToAdd must not be {@literal null}. + * @param commitWithinMs + * @return + * @since 2.1 + */ + UpdateResponse saveBean(String collectionName, Object objectToAdd, int commitWithinMs); /** * Add a collection of beans to solr, which will do either insert or update. * - * @param collection must not be {@literal null}. * @param beans must not be {@literal null}. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @return */ - default UpdateResponse saveBeans(String collection, Collection beans) { - return saveBeans(collection, beans, Duration.ZERO); - } + UpdateResponse saveBeans(Collection beans); /** - * Add a collection of beans to solr, which will do either insert or update with support for commitWithin strategy. + * Add a collection of beans to specific collection, which will do either insert or update. + * + * @param collectionName must not be {@literal null}. + * @param beans must not be {@literal null}. + * @return + * @since 2.1 + */ + UpdateResponse saveBeans(String collectionName, Collection beans); + + /** + * Add a collection of beans to solr, which will do either insert or update with support for commitWithin strategy * - * @param collection must not be {@literal null}. * @param beans must not be {@literal null}. - * @param commitWithin max time within server performs commit. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @param commitWithinMs + * @return */ - UpdateResponse saveBeans(String collection, Collection beans, Duration commitWithin); + UpdateResponse saveBeans(Collection beans, int commitWithinMs); + + /** + * Add a collection of beans to specific collection, which will do either insert or update with support for + * commitWithin strategy. + * + * @param collectionName must not be {@literal null}. + * @param beansToAdd must not be {@literal null}. + * @param commitWithinMs + * @return + * @since 2.1 + */ + UpdateResponse saveBeans(String collectionName, Collection beansToAdd, int commitWithinMs); /** * Add a solrj input document to solr, which will do either insert or update * - * @param collection must not be {@literal null}. * @param document must not be {@literal null}. - * @return {@link UpdateResponse} containing update result. + * @return + */ + UpdateResponse saveDocument(SolrInputDocument document); + + /** + * Add a solrj input document to specific collection, which will do either insert or update. + * + * @param collectionName must not be {@literal null}. + * @param document must not be {@literal null}. + * @return + * @since 2.1 */ - default UpdateResponse saveDocument(String collection, SolrInputDocument document) { - return saveDocument(collection, document, Duration.ZERO); - } + UpdateResponse saveDocument(String collectionName, SolrInputDocument document); /** * Add a solrj input document to solr, which will do either insert or update with support for commitWithin strategy * * @param document must not be {@literal null}. - * @param commitWithin must not be {@literal null}. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @param commitWithinMs + * @return */ - UpdateResponse saveDocument(String collection, SolrInputDocument document, Duration commitWithin); + UpdateResponse saveDocument(SolrInputDocument document, int commitWithinMs); + + /** + * Add a solrj input document to specific collection, which will do either insert or update with support for + * commitWithin strategy + * + * @param collectionName must not be {@literal null}. + * @param documentToAdd must not be {@literal null}. + * @param commitWithinMs + * @return + * @since 2.1 + */ + UpdateResponse saveDocument(String collectionName, SolrInputDocument documentToAdd, int commitWithinMs); /** * Add multiple solrj input documents to solr, which will do either insert or update * - * @param collection must not be {@literal null}. * @param documents must not be {@literal null}. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @return */ - default UpdateResponse saveDocuments(String collection, Collection documents) { - return saveDocuments(collection, documents, Duration.ZERO); - } + UpdateResponse saveDocuments(Collection documents); + + /** + * Add multiple solrj input documents to specific collection, which will do either insert or update. + * + * @param collectionName must not be {@literal null}. + * @param documents must not be {@literal null}. + * @return + * @since 2.1 + */ + UpdateResponse saveDocuments(String collectionName, Collection documents); /** * Add multiple solrj input documents to solr, which will do either insert or update with support for commitWithin - * strategy. + * strategy * - * @param collection must not be {@literal null}. * @param documents must not be {@literal null}. - * @param commitWithin max time within server performs commit. - * @return {@link UpdateResponse} containing update result. - * @since 3.0 + * @return */ - UpdateResponse saveDocuments(String collection, Collection documents, Duration commitWithin); + UpdateResponse saveDocuments(Collection documents, int commitWithinMs); /** - * Find and delete all objects matching the provided Query. + * Add multiple solrj input documents to specific collection, which will do either insert or update with support for + * commitWithin strategy. + * + * @param collectionName must not be {@literal null}. + * @param documents must not be {@literal null}. + * @param commitWithinMs + * @return + * @since 2.1 + */ + UpdateResponse saveDocuments(String collectionName, Collection documents, int commitWithinMs); + + /** + * Find and delete all objects matching the provided Query * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. - * @return {@link UpdateResponse} containing delete result. - * @since 3.0 + * @return */ - UpdateResponse delete(String collection, SolrDataQuery query); + UpdateResponse delete(SolrDataQuery query); /** - * Detele the one object with provided id. + * Find and delete all objects matching the provided Query in specific collection. * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @return + * @since 2.1 + */ + UpdateResponse delete(String collectionName, SolrDataQuery query); + + /** + * Delete the one object with provided id + * + * @param id must not be {@literal null}. + * @return + */ + UpdateResponse deleteById(String id); + + /** + * Delete the one object with provided id in collection. + * + * @param collectionName must not be {@literal null}. * @param id must not be {@literal null}. - * @return {@link UpdateResponse} containing delete result. - * @since 3.0 + * @return + * @since 2.1 */ - UpdateResponse deleteByIds(String collection, String id); + UpdateResponse deleteById(String collectionName, String id); /** * Delete objects with given ids * - * @param collection must not be {@literal null}. * @param id must not be {@literal null}. - * @return {@link UpdateResponse} containing delete result. - * @since 3.0 + * @return + */ + UpdateResponse deleteById(Collection id); + + /** + * Delete objects with given ids in collection. + * + * @param collectionName must not be {@literal null}. + * @param ids must not be {@literal null}. + * @return + * @since 2.1 */ - UpdateResponse deleteByIds(String collection, Collection id); + UpdateResponse deleteById(String collectionName, Collection ids); /** * Execute the query against solr and return the first returned object * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @return the first matching object - * @since 3.0 */ - Optional queryForObject(String collection, Query query, Class clazz); + T queryForObject(Query query, Class clazz); + + /** + * Execute the query against specific collection and return the first returned object. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + T queryForObject(String collectionName, Query query, Class clazz); /** * Execute the query against solr and return the first returned object * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. * @return the first matching object - * @since 3.0 + * @since 2.0 */ - Optional queryForObject(String collection, Query query, Class clazz, RequestMethod method); + T queryForObject(Query query, Class clazz, RequestMethod method); /** - * Execute the query against solr and retrun result as {@link Page} + * Execute the query against specific collection and return the first returned object. * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @param method must not be {@literal null}. + * @return + * @since 2.1 */ - ScoredPage queryForPage(String collection, Query query, Class clazz); + T queryForObject(String collectionName, Query query, Class clazz, RequestMethod method); /** - * Execute the query against solr and retrun result as {@link Page} + * Execute the query against solr and return result as {@link Page}. + * + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + */ + ScoredPage queryForPage(Query query, Class clazz); + + /** + * Execute the query against specific collection and return result as {@link Page}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + ScoredPage queryForPage(String collectionName, Query query, Class clazz); + + /** + * Execute the query against solr and return result as {@link Page} * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.0 */ - ScoredPage queryForPage(String collection, Query query, Class clazz, RequestMethod method); + ScoredPage queryForPage(Query query, Class clazz, RequestMethod method); /** - * Execute a facet query against solr facet result will be returned along with query result within the FacetPage + * Execute the query against specific collection and return result as {@link Page} * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @param method must not be {@literal null}. + * @return + * @since 2.1 */ - FacetPage queryForFacetPage(String collection, FacetQuery query, Class clazz); + ScoredPage queryForPage(String collectionName, Query query, Class clazz, RequestMethod method); /** * Execute a facet query against solr facet result will be returned along with query result within the FacetPage * - * @param collection must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + */ + FacetPage queryForFacetPage(FacetQuery query, Class clazz); + + /** + * Execute a facet query against specific collection. The facet result will be returned along with query result within + * the {@link FacetPage}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + FacetPage queryForFacetPage(String collectionName, FacetQuery query, Class clazz); + + /** + * Execute a facet query against solr facet result will be returned along with query result within the + * {@link FacetPage#} + * * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.0 + */ + FacetPage queryForFacetPage(FacetQuery query, Class clazz, RequestMethod method); + + /** + * Execute a facet query against specific collection. The facet result will be returned along with query result within + * the {@link FacetPage}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 */ - FacetPage queryForFacetPage(String collection, FacetQuery query, Class clazz, RequestMethod method); + FacetPage queryForFacetPage(String collectionName, FacetQuery query, Class clazz, RequestMethod method); /** * Execute a query and highlight matches in result * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return */ - HighlightPage queryForHighlightPage(String collection, HighlightQuery query, Class clazz); + HighlightPage queryForHighlightPage(HighlightQuery query, Class clazz); /** - * Execute a query and highlight matches in result + * Execute a query and highlight matches in result within a specific collection. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + HighlightPage queryForHighlightPage(String collectionName, HighlightQuery query, Class clazz); + + /** + * Execute a query and highlight matches in result. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.0 */ - HighlightPage queryForHighlightPage(String collection, HighlightQuery query, Class clazz, + HighlightPage queryForHighlightPage(HighlightQuery query, Class clazz, RequestMethod method); + + /** + * Execute a query and highlight matches in result + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 + */ + HighlightPage queryForHighlightPage(String collectionName, HighlightQuery query, Class clazz, RequestMethod method); /** * Execute a query and highlight matches in result * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.1 + */ + FacetAndHighlightPage queryForFacetAndHighlightPage(FacetAndHighlightQuery query, Class clazz); + + /** + * Execute a query against specific collection and highlight matches in result. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 */ - FacetAndHighlightPage queryForFacetAndHighlightPage(String collection, FacetAndHighlightQuery query, + FacetAndHighlightPage queryForFacetAndHighlightPage(String collectionName, FacetAndHighlightQuery query, Class clazz); /** * Execute a query and highlight matches in result * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.1 */ - FacetAndHighlightPage queryForFacetAndHighlightPage(String collection, FacetAndHighlightQuery query, + FacetAndHighlightPage queryForFacetAndHighlightPage(FacetAndHighlightQuery query, Class clazz, + RequestMethod method); + + /** + * Execute a query against specific collection and highlight matches in result. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 + */ + FacetAndHighlightPage queryForFacetAndHighlightPage(String collectionName, FacetAndHighlightQuery query, Class clazz, RequestMethod method); /** * Execute query using terms handler * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + */ + TermsPage queryForTermsPage(TermsQuery query); + + /** + * Execute query using terms handler against given collection. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @return + * @since 2.1 */ - TermsPage queryForTermsPage(String collection, TermsQuery query); + TermsPage queryForTermsPage(String collectionName, TermsQuery query); /** * Execute query using terms handler * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.0 + */ + TermsPage queryForTermsPage(TermsQuery query, RequestMethod method); + + /** + * Execute query using terms handler against given collection. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 */ - TermsPage queryForTermsPage(String collection, TermsQuery query, RequestMethod method); + TermsPage queryForTermsPage(String collectionName, TermsQuery query, RequestMethod method); /** * Executes the given {@link Query} and returns an open {@link Cursor} allowing to iterate of results, dynamically * fetching additional ones if required. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 1.3 */ - Cursor queryForCursor(String collection, Query query, Class clazz); + Cursor queryForCursor(Query query, Class clazz); /** * Execute the query against solr and return result as {@link GroupPage} * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 1.4 */ - GroupPage queryForGroupPage(String collection, Query query, Class clazz); + GroupPage queryForGroupPage(Query query, Class clazz); /** - * Execute the query against solr and return result as {@link GroupPage} + * Execute the query against specific collection and return result as {@link GroupPage}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + GroupPage queryForGroupPage(String collectionName, Query query, Class clazz); + + /** + * Execute the query against solr and return result as {@link GroupPage}. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. - * @return never {@literal null}. - * @since 3.0 + * @return + * @since 2.0 */ - GroupPage queryForGroupPage(String collection, Query query, Class clazz, RequestMethod method); + GroupPage queryForGroupPage(Query query, Class clazz, RequestMethod method); + + /** + * Execute the query against specific collection and return result as {@link GroupPage} + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + */ + GroupPage queryForGroupPage(String collectionName, Query query, Class clazz, RequestMethod method); /** * Execute the query against Solr and return result as {@link StatsPage}. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. - * @return never {@literal null}. - * @size 3.0 + * @return + * @size 1.4 */ - StatsPage queryForStatsPage(String collection, Query query, Class clazz); + StatsPage queryForStatsPage(Query query, Class clazz); + + /** + * Execute the query against specific collection and return result as {@link StatsPage}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + StatsPage queryForStatsPage(String collectionName, Query query, Class clazz); /** * Execute the query against Solr and return result as {@link StatsPage}. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. + * @return + * @since 2.0 + */ + StatsPage queryForStatsPage(Query query, Class clazz, RequestMethod method); + + /** + * Execute the query against specific collection and return result as {@link StatsPage}. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.1 + */ + StatsPage queryForStatsPage(String collectionName, Query query, Class clazz, RequestMethod method); + + /** + * Execute the query against Solr and return result as page. + * + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. * @return never {@literal null}. - * @since 3.0 + * @since 2.1 */ - StatsPage queryForStatsPage(String collection, Query query, Class clazz, RequestMethod method); + > S query(Query query, Class clazz); /** * Execute the query against Solr and return result as page. * - * @param collection must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @return never {@literal null}. - * @since 3.0 + * @since 2.1 */ - > S query(String collection, Query query, Class clazz); + > S query(String collectionName, Query query, Class clazz); + /** * Execute the query against Solr and return result as page. * - * @param collection must not be {@literal null}. * @param query must not be {@literal null}. * @param clazz must not be {@literal null}. * @param method must not be {@literal null}. * @return never {@literal null}. - * @since 3.0 + * @since 2.1 */ - > S query(String collection, Query query, Class clazz, RequestMethod method); + > S query(Query query, Class clazz, RequestMethod method); + + /** + * Execute the query against Solr and return result as page. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @param method must not be {@literal null}. + * @return never {@literal null}. + * @since 2.1 + */ + > S query(String collectionName, Query query, Class clazz, RequestMethod method); /** * Executes a realtime get using given id. * - * @param collection must not be {@literal null}. * @param id must not be {@literal null}. * @param clazz must not be {@literal null}. * @return - * @since 3.0 + * @since 1.4 */ - Optional getById(String collection, Object id, Class clazz); + T getById(Serializable id, Class clazz); + + /** + * Executes a realtime get on given collection using given id. + * + * @param collectionName must not be {@literal null}. + * @param id must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 + */ + T getById(String collectionName, Serializable id, Class clazz); /** * Executes a realtime get using given ids. * - * @param collection must not be {@literal null}. * @param ids must not be {@literal null}. * @param clazz must not be {@literal null}. * @return - * @since 3.0 + * @since 1.4 + */ + Collection getById(Collection ids, Class clazz); + + /** + * Executes a realtime get on given collection using given ids. + * + * @param collectionName must not be {@literal null}. + * @param ids must not be {@literal null}. + * @param clazz must not be {@literal null}. + * @return + * @since 2.1 */ - Collection getByIds(String collection, Collection ids, Class clazz); + Collection getById(String collectionName, Collection ids, Class clazz); /** * Send commit command {@link SolrClient#commit()} - * - * @since 3.0 */ - void commit(String collection); + void commit(); + + /** + * @param collectionName must not be {@literal null}. + * @since 2.1 + */ + void commit(String collectionName); /** * Send soft commmit command {@link SolrClient#commit(boolean, boolean, boolean)} - * - * @since 3.9 */ - void softCommit(String collection); + void softCommit(); + + /** + * @param collectionName must not be {@literal null}. + * @since 2.1 + */ + void softCommit(String collectionName); /** * send rollback command {@link SolrClient#rollback()} - * - * @since 3.0 */ - void rollback(String collection); + void rollback(); + + /** + * @param collectionName must not be {@literal null}. + * @since 2.1 + */ + void rollback(String collectionName); /** * Convert given bean into a solrj InputDocument - * + * * @param bean * @return */ @@ -496,12 +809,22 @@ FacetAndHighlightPage queryForFacetAndHighlightPage(String collection, Fa /** * Execute action within callback - * + * * @param action * @return */ T execute(SolrCallback action); + /** + * Execute action within callback on a given collection. + * + * @param collection must not be {@literal null}. + * @param action must not be {@literal null}. + * @return + * @since 2.1 + */ + T execute(String collection, CollectionCallback action); + /** * Get the {@link SchemaOperations} executable. * diff --git a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java index 9d7db21..5827fa3 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java @@ -15,7 +15,8 @@ */ package org.springframework.data.solr.core; -import java.time.Duration; +import java.io.IOException; +import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -24,14 +25,12 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; -import org.apache.solr.client.solrj.request.SolrPing; +import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.SolrPingResponse; import org.apache.solr.client.solrj.response.UpdateResponse; @@ -45,7 +44,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.dao.DataAccessException; -import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -61,51 +59,58 @@ import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; +import org.springframework.data.solr.core.query.AbstractQueryDecorator; import org.springframework.data.solr.core.query.FacetAndHighlightQuery; import org.springframework.data.solr.core.query.FacetQuery; import org.springframework.data.solr.core.query.HighlightQuery; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SolrDataQuery; import org.springframework.data.solr.core.query.TermsQuery; -import org.springframework.data.solr.core.query.result.*; +import org.springframework.data.solr.core.query.result.Cursor; +import org.springframework.data.solr.core.query.result.DelegatingCursor; +import org.springframework.data.solr.core.query.result.FacetAndHighlightPage; +import org.springframework.data.solr.core.query.result.FacetPage; +import org.springframework.data.solr.core.query.result.GroupPage; +import org.springframework.data.solr.core.query.result.HighlightPage; +import org.springframework.data.solr.core.query.result.ScoredPage; +import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; +import org.springframework.data.solr.core.query.result.StatsPage; +import org.springframework.data.solr.core.query.result.TermsPage; +import org.springframework.data.solr.core.query.result.TermsResultPage; import org.springframework.data.solr.core.schema.DefaultSchemaOperations; import org.springframework.data.solr.core.schema.SchemaOperations; import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator; import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator.Feature; import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.data.solr.server.support.HttpSolrClientFactory; -import org.springframework.lang.Nullable; +import org.springframework.data.solr.server.support.MulticoreSolrClientFactory; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; /** * Implementation of {@link SolrOperations} - * + * * @author Christoph Strobl * @author Joachim Uhrlass * @author Francisco Spaeth * @author Shiradwade Sateesh Krishna * @author David Webb * @author Petar Tahchiev - * @author Mark Paluch */ public class SolrTemplate implements SolrOperations, InitializingBean, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(SolrTemplate.class); private static final PersistenceExceptionTranslator EXCEPTION_TRANSLATOR = new SolrExceptionTranslator(); private final QueryParsers queryParsers = new QueryParsers(); - private @Nullable MappingContext, SolrPersistentProperty> mappingContext; + private MappingContext, SolrPersistentProperty> mappingContext; - private @Nullable ApplicationContext applicationContext; + private ApplicationContext applicationContext; + private String solrCore; private final RequestMethod defaultRequestMethod; - private @Nullable SolrClientFactory solrClientFactory; - - private @Nullable SolrConverter solrConverter; - - private Set schemaCreationFeatures = Collections.emptySet(); - @SuppressWarnings("serial") // private static final List ITERABLE_CLASSES = new ArrayList() { { @@ -115,23 +120,46 @@ public class SolrTemplate implements SolrOperations, InitializingBean, Applicati } }; + private SolrClientFactory solrClientFactory; + + private SolrConverter solrConverter; + + private Set schemaCreationFeatures; + public SolrTemplate(SolrClient solrClient) { - this(new HttpSolrClientFactory(solrClient)); + this(solrClient, null); } - public SolrTemplate(SolrClient solrClient, RequestMethod requestMethod) { - this(new HttpSolrClientFactory(solrClient), requestMethod); + public SolrTemplate(SolrClient solrClient, String core) { + this(new HttpSolrClientFactory(solrClient, core)); + this.solrCore = core; + } + + public SolrTemplate(SolrClient solrClient, String core, RequestMethod requestMethod) { + this(new HttpSolrClientFactory(solrClient, core), requestMethod); + this.solrCore = core; + } public SolrTemplate(SolrClientFactory solrClientFactory) { this(solrClientFactory, (SolrConverter) null); } + /** + * @param solrClientFactory must not be {@literal null}. + * @param defaultCore can be {@literal null}. + * @since 2.1 + */ + public SolrTemplate(SolrClientFactory solrClientFactory, String defaultCore) { + this(solrClientFactory, (SolrConverter) null); + this.solrCore = defaultCore; + } + public SolrTemplate(SolrClientFactory solrClientFactory, RequestMethod requestMethod) { this(solrClientFactory, null, requestMethod); } - public SolrTemplate(SolrClientFactory solrClientFactory, @Nullable SolrConverter solrConverter) { + public SolrTemplate(SolrClientFactory solrClientFactory, SolrConverter solrConverter) { this(solrClientFactory, solrConverter, RequestMethod.GET); } @@ -141,14 +169,13 @@ public SolrTemplate(SolrClientFactory solrClientFactory, @Nullable SolrConverter * @param defaultRequestMethod can be {@literal null}. Will be defaulted to {@link RequestMethod#GET} * @since 2.0 */ - public SolrTemplate(SolrClientFactory solrClientFactory, @Nullable SolrConverter solrConverter, - @Nullable RequestMethod defaultRequestMethod) { + public SolrTemplate(SolrClientFactory solrClientFactory, SolrConverter solrConverter, + RequestMethod defaultRequestMethod) { Assert.notNull(solrClientFactory, "SolrClientFactory must not be 'null'."); this.solrClientFactory = solrClientFactory; this.defaultRequestMethod = defaultRequestMethod != null ? defaultRequestMethod : RequestMethod.GET; - this.solrConverter = solrConverter; } /* @@ -162,6 +189,35 @@ public T execute(SolrCallback action) { try { SolrClient solrClient = this.getSolrClient(); return action.doInSolr(solrClient); + } catch (Exception e) { + DataAccessException resolved = getExceptionTranslator() + .translateExceptionIfPossible(new RuntimeException(e.getMessage(), e)); + throw resolved == null ? new UncategorizedSolrException(e.getMessage(), e) : resolved; + } + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#execute(java.lang.String, org.springframework.data.solr.core.CollectionCallback) + */ + @Override + public T execute(String collection, CollectionCallback action) { + + Assert.notNull(action, "Action must not be null!"); + + try { + + SolrClient solrClient = null; + if(StringUtils.hasText(collection)) { + if(this.solrClientFactory instanceof MulticoreSolrClientFactory) { + solrClient = this.solrClientFactory.getSolrClient(); + } else { + solrClient = this.solrClientFactory.getSolrClient(collection); + } + } else { + solrClient = this.getSolrClient(); + } + return action.doInSolr(solrClient, collection); } catch (Exception e) { DataAccessException resolved = getExceptionTranslator().translateExceptionIfPossible( e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e.getMessage(), e)); @@ -175,95 +231,351 @@ public T execute(SolrCallback action) { */ @Override public SolrPingResponse ping() { - return execute(SolrClient::ping); + return execute(new SolrCallback() { + @Override + public SolrPingResponse doInSolr(SolrClient solrClient) throws SolrServerException, IOException { + return solrClient.ping(); + } + }); } /* * (non-Javadoc) - * @see org.springframework.data.solr.core.SolrOperations#ping(java.lang.String) + * @see org.springframework.data.solr.core.SolrOperations#count(org.springframework.data.solr.core.query.SolrDataQuery) */ @Override - public SolrPingResponse ping(String collection) { - return execute(client -> new SolrPing().process(client, collection)); + public long count(SolrDataQuery query) { + return count(query, getDefaultRequestMethod()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#count(java.lang.String, org.springframework.data.solr.core.query.SolrDataQuery) + */ + public long count(String collectionName, SolrDataQuery query) { + return count(collectionName, query, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#count(org.springframework.data.solr.core.query.SolrDataQuery, org.springframework.data.solr.core.RequestMethod) + */ @Override - public long count(String collection, SolrDataQuery query) { - return count(collection, query, getDefaultRequestMethod()); + public long count(final SolrDataQuery query, final RequestMethod method) { + return count(null, query, method); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#count(java.lang.String, org.springframework.data.solr.core.query.SolrDataQuery, org.springframework.data.solr.core.RequestMethod) + */ @Override - public long count(String collection, SolrDataQuery query, RequestMethod method) { + public long count(String collectionName, final SolrDataQuery query, final RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(method, "Method must not be 'null'."); - return execute(solrClient -> { + return execute(collectionName, new CollectionCallback() { - SolrQuery solrQuery = queryParsers.getForClass(query.getClass()).constructSolrQuery(query); - solrQuery.setStart(0); - solrQuery.setRows(0); + @Override + public Long doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + + SolrQuery solrQuery = queryParsers.getForClass(query.getClass()).constructSolrQuery(query); + solrQuery.setStart(0); + solrQuery.setRows(0); - return solrClient.query(collection, solrQuery, getSolrRequestMethod(method)).getResults().getNumFound(); + return StringUtils.hasText(collection) + ? solrClient.query(collection, solrQuery, getSolrRequestMethod(method)).getResults().getNumFound() + : solrClient.query(solrQuery, getSolrRequestMethod(method)).getResults().getNumFound(); + } }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBean(java.lang.Object) + */ @Override - public UpdateResponse saveBean(String collection, Object obj, Duration commitWithin) { + public UpdateResponse saveBean(Object obj) { + return saveBean(obj, -1); + } - assertNoCollection(obj); + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBean(java.lang.String, java.lang.Object) + */ + @Override + public UpdateResponse saveBean(String collectionName, Object obj) { + return saveBean(collectionName, obj, -1); + } - return execute(solrClient -> solrClient.add(collection, convertBeanToSolrInputDocument(obj), - getCommitWithinTimeout(commitWithin))); + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBean(java.lang.Object, int) + */ + @Override + public UpdateResponse saveBean(final Object objectToAdd, final int commitWithinMs) { + return saveBean(getSolrCoreOrBeanCollection(ClassUtils.getUserClass(objectToAdd)), objectToAdd, commitWithinMs); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBean(java.lang.String, java.lang.Object, int) + */ @Override - public UpdateResponse saveBeans(String collection, Collection beans, Duration commitWithin) { - return execute(solrClient -> solrClient.add(collection, convertBeansToSolrInputDocuments(beans), - getCommitWithinTimeout(commitWithin))); + public UpdateResponse saveBean(String collectionName, final Object objectToAdd, final int commitWithinMs) { + + assertNoCollection(objectToAdd); + + return execute(collectionName, new CollectionCallback() { + + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) + ? solrClient.add(collection, convertBeanToSolrInputDocument(objectToAdd), commitWithinMs) + : solrClient.add(convertBeanToSolrInputDocument(objectToAdd), commitWithinMs); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBeans(java.util.Collection) + */ @Override - public UpdateResponse saveDocument(String collection, SolrInputDocument document, Duration commitWithin) { - return execute(solrClient -> solrClient.add(collection, document, getCommitWithinTimeout(commitWithin))); + public UpdateResponse saveBeans(Collection beans) { + return saveBeans(beans, -1); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBeans(java.lang.String, java.util.Collection) + */ @Override - public UpdateResponse saveDocuments(String collection, Collection documents, - Duration commitWithin) { - return execute(solrClient -> solrClient.add(collection, documents, getCommitWithinTimeout(commitWithin))); + public UpdateResponse saveBeans(String collectionName, Collection beans) { + return saveBeans(collectionName, beans, -1); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBeans(java.util.Collection, int) + */ @Override - public UpdateResponse delete(String collection, SolrDataQuery query) { + public UpdateResponse saveBeans(final Collection beansToAdd, final int commitWithinMs) { + return saveBeans(getSolrCoreOrBeanCollection(ClassUtils.getUserClass(beansToAdd.iterator().next())), beansToAdd, + commitWithinMs); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveBeans(java.lang.String, java.util.Collection, int) + */ + @Override + public UpdateResponse saveBeans(String collectionName, final Collection beansToAdd, final int commitWithinMs) { + + return execute(collectionName, new CollectionCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) + ? solrClient.add(collection, convertBeansToSolrInputDocuments(beansToAdd), commitWithinMs) + : solrClient.add(convertBeansToSolrInputDocuments(beansToAdd), commitWithinMs); + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocument(org.apache.solr.common.SolrInputDocument) + */ + @Override + public UpdateResponse saveDocument(SolrInputDocument document) { + return saveDocument(document, -1); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocument(java.lang.String, org.apache.solr.common.SolrInputDocument) + */ + @Override + public UpdateResponse saveDocument(String collectionName, SolrInputDocument document) { + return saveDocument(collectionName, document, -1); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocument(org.apache.solr.common.SolrInputDocument, int) + */ + @Override + public UpdateResponse saveDocument(final SolrInputDocument documentToAdd, final int commitWithinMs) { + return saveDocument(null, documentToAdd, commitWithinMs); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocument(java.lang.String, org.apache.solr.common.SolrInputDocument, int) + */ + @Override + public UpdateResponse saveDocument(String collectionName, final SolrInputDocument documentToAdd, + final int commitWithinMs) { + + return execute(collectionName, new CollectionCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.add(collection, documentToAdd, commitWithinMs) + : solrClient.add(documentToAdd, commitWithinMs); + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocuments(java.util.Collection) + */ + @Override + public UpdateResponse saveDocuments(Collection documents) { + return saveDocuments(documents, -1); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocuments(java.lang.String, java.util.Collection) + */ + @Override + public UpdateResponse saveDocuments(String collectionName, Collection documents) { + return saveDocuments(collectionName, documents, -1); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocuments(java.util.Collection, int) + */ + @Override + public UpdateResponse saveDocuments(final Collection documentsToAdd, final int commitWithinMs) { + return execute(new SolrCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient) throws SolrServerException, IOException { + return solrClient.add(documentsToAdd, commitWithinMs); + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#saveDocuments(java.lang.String, java.util.Collection, int) + */ + @Override + public UpdateResponse saveDocuments(String collectionName, final Collection documentsToAdd, + final int commitWithinMs) { + + return execute(collectionName, new CollectionCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.add(collection, documentsToAdd, commitWithinMs) + : solrClient.add(documentsToAdd, commitWithinMs); + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#delete(org.springframework.data.solr.core.query.SolrDataQuery) + */ + @Override + public UpdateResponse delete(SolrDataQuery query) { + return delete(null, query); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#delete(java.lang.String, org.springframework.data.solr.core.query.SolrDataQuery) + */ + @Override + public UpdateResponse delete(String collectionName, SolrDataQuery query) { Assert.notNull(query, "Query must not be 'null'."); final String queryString = this.queryParsers.getForClass(query.getClass()).getQueryString(query); - return execute(solrClient -> solrClient.deleteByQuery(collection, queryString)); + return execute(collectionName, new CollectionCallback() { + + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.deleteByQuery(collection, queryString) + : solrClient.deleteByQuery(queryString); + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#deleteById(java.lang.String) + */ + @Override + public UpdateResponse deleteById(final String id) { + return deleteById(null, id); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#deleteById(java.lang.String, java.lang.String) + */ @Override - public UpdateResponse deleteByIds(String collection, String id) { + public UpdateResponse deleteById(String collectionName, final String id) { Assert.notNull(id, "Cannot delete 'null' id."); - return execute(solrClient -> solrClient.deleteById(collection, id)); + return execute(collectionName, new CollectionCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.deleteById(collection, id) : solrClient.deleteById(id); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#deleteById(java.util.Collection) + */ @Override - public UpdateResponse deleteByIds(String collection, Collection ids) { + public UpdateResponse deleteById(Collection ids) { + return deleteById(null, ids); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#deleteById(java.lang.String, java.util.Collection) + */ + @Override + public UpdateResponse deleteById(String collectionName, Collection ids) { Assert.notNull(ids, "Cannot delete 'null' collection."); - return execute(solrClient -> solrClient.deleteById(collection, ids.stream().collect(Collectors.toList()))); + final List toBeDeleted = new ArrayList(ids); + + return execute(collectionName, new CollectionCallback() { + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.deleteById(collection, toBeDeleted) + : solrClient.deleteById(toBeDeleted); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForObject(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ @Override - public Optional queryForObject(String collection, Query query, Class clazz) { - return queryForObject(collection, query, clazz, getDefaultRequestMethod()); + public T queryForObject(Query query, Class clazz) { + return queryForObject(query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForObject(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + public T queryForObject(String collectionName, Query query, Class clazz) { + return queryForObject(collectionName, query, clazz, getDefaultRequestMethod()); } /* @@ -271,148 +583,319 @@ public Optional queryForObject(String collection, Query query, Class c * @see org.springframework.data.solr.core.SolrOperations#queryForObject(org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) */ @Override - public Optional queryForObject(String collection, Query query, Class clazz, RequestMethod method) { + public T queryForObject(Query query, Class clazz, RequestMethod method) { + return queryForObject(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForObject(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public T queryForObject(String collectionName, Query query, Class clazz, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); - query.setPageRequest(PageRequest.of(0, 1)); - QueryResponse response = querySolr(collection, query, clazz, method); + query.setPageRequest(new PageRequest(0, 1)); + QueryResponse response = querySolr(collectionName, query, clazz, method); if (response.getResults().size() > 0) { if (response.getResults().size() > 1) { LOGGER.warn("More than 1 result found for singe result query ('{}'), returning first entry in list"); } - return Optional.ofNullable(convertSolrDocumentListToBeans(response.getResults(), clazz).get(0)); + return convertSolrDocumentListToBeans(response.getResults(), clazz).get(0); } - return Optional.empty(); + return null; + } - private SolrResultPage doQueryForPage(String collection, Query query, Class clazz, - @Nullable RequestMethod requestMethod) { + private SolrResultPage doQueryForPage(String collectionName, Query query, Class clazz, + RequestMethod requestMethod) { QueryResponse response = null; NamedObjectsQuery namedObjectsQuery = new NamedObjectsQuery(query); - response = querySolr(collection, namedObjectsQuery, clazz, + response = querySolr(collectionName, namedObjectsQuery, clazz, requestMethod != null ? requestMethod : getDefaultRequestMethod()); Map objectsName = namedObjectsQuery.getNamesAssociation(); return createSolrResultPage(query, clazz, response, objectsName); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForPage(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ @Override - public ScoredPage queryForPage(String collection, Query query, Class clazz) { + public ScoredPage queryForPage(Query query, Class clazz) { + return queryForPage(getSolrCoreOrBeanCollection(clazz), query, clazz); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + public ScoredPage queryForPage(String collectionName, Query query, Class clazz) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); - return doQueryForPage(collection, query, clazz, getDefaultRequestMethod()); + return doQueryForPage(collectionName, query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryFor(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + @Override + public > S query(Query query, Class clazz) { + return query(query, clazz, getDefaultRequestMethod()); } @Override - public > S query(String collection, Query query, Class clazz) { - return query(collection, query, clazz, getDefaultRequestMethod()); + public > S query(String collectionName, Query query, Class clazz) { + return query(collectionName, query, clazz, getDefaultRequestMethod()); } - public > S query(String collection, Query query, Class clazz, RequestMethod method) { + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#query(org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + @Override + public > S query(Query query, Class clazz, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); Assert.notNull(clazz, "Method must not be 'null'."); - return (S) doQueryForPage(collection, query, clazz, method); + return (S) doQueryForPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); } + public > S query(String collectionName, Query query, Class clazz, RequestMethod method) { + + Assert.notNull(query, "Query must not be 'null'."); + Assert.notNull(clazz, "Target class must not be 'null'."); + Assert.notNull(clazz, "Method must not be 'null'."); + + return (S) doQueryForPage(collectionName, query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForPage(org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ @Override - public ScoredPage queryForPage(String collection, Query query, Class clazz, RequestMethod method) { + public ScoredPage queryForPage(Query query, Class clazz, RequestMethod method) { + return queryForPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public ScoredPage queryForPage(String collectionName, Query query, Class clazz, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); Assert.notNull(method, "Method class must not be 'null'."); - return doQueryForPage(collection, query, clazz, method); + return doQueryForPage(collectionName, query, clazz, method); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForGroupPage(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ @Override - public GroupPage queryForGroupPage(String collection, Query query, Class clazz) { - return queryForGroupPage(collection, query, clazz, getDefaultRequestMethod()); + public GroupPage queryForGroupPage(Query query, Class clazz) { + return queryForGroupPage(query, clazz, RequestMethod.GET); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForGroupPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + public GroupPage queryForGroupPage(String collectionName, Query query, Class clazz) { + return queryForGroupPage(collectionName, query, clazz, RequestMethod.GET); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForGroupPage(org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ @Override - public GroupPage queryForGroupPage(String collection, Query query, Class clazz, RequestMethod method) { + public GroupPage queryForGroupPage(Query query, Class clazz, RequestMethod method) { + return queryForGroupPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForGroupPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public GroupPage queryForGroupPage(String collectionName, Query query, Class clazz, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); Assert.notNull(method, "Method class must not be 'null'."); - return doQueryForPage(collection, query, clazz, method); + return doQueryForPage(collectionName, query, clazz, method); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForStatsPage(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ @Override - public StatsPage queryForStatsPage(String collection, Query query, Class clazz) { - return queryForStatsPage(collection, query, clazz, getDefaultRequestMethod()); + public StatsPage queryForStatsPage(Query query, Class clazz) { + return queryForStatsPage(query, clazz, getDefaultRequestMethod()); } - public StatsPage queryForStatsPage(String collection, Query query, Class clazz, RequestMethod method) { + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForStatsPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + public StatsPage queryForStatsPage(String collectionName, Query query, Class clazz) { + return queryForStatsPage(collectionName, query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForStatsPage(org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + @Override + public StatsPage queryForStatsPage(Query query, Class clazz, RequestMethod method) { + return queryForStatsPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForStatsPage(java.lang.String, org.springframework.data.solr.core.query.Query, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public StatsPage queryForStatsPage(String collectionName, Query query, Class clazz, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); Assert.notNull(method, "Method class must not be 'null'."); - return doQueryForPage(collection, query, clazz, method); + return doQueryForPage(collectionName, query, clazz, method); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetPage(org.springframework.data.solr.core.query.FacetQuery, java.lang.Class) + */ @Override - public FacetPage queryForFacetPage(String collection, FacetQuery query, Class clazz) { - return queryForFacetPage(collection, query, clazz, getDefaultRequestMethod()); + public FacetPage queryForFacetPage(FacetQuery query, Class clazz) { + return queryForFacetPage(query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetPage(java.lang.String, org.springframework.data.solr.core.query.FacetQuery, java.lang.Class) + */ + public FacetPage queryForFacetPage(String collectionName, FacetQuery query, Class clazz) { + return queryForFacetPage(collectionName, query, clazz, getDefaultRequestMethod()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetPage(org.springframework.data.solr.core.query.FacetQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ @Override - public FacetPage queryForFacetPage(String collection, FacetQuery query, Class clazz, RequestMethod method) { + public FacetPage queryForFacetPage(FacetQuery query, Class clazz, RequestMethod method) { + return queryForFacetPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetPage(java.lang.String, org.springframework.data.solr.core.query.FacetQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public FacetPage queryForFacetPage(String collectionName, FacetQuery query, Class clazz, + RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); NamedObjectsFacetQuery namedObjectsQuery = new NamedObjectsFacetQuery(query); - return createSolrResultPage(query, clazz, querySolr(collection, namedObjectsQuery, clazz, method), + return createSolrResultPage(query, clazz, querySolr(collectionName, namedObjectsQuery, clazz, method), namedObjectsQuery.getNamesAssociation()); - } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForHighlightPage(org.springframework.data.solr.core.query.HighlightQuery, java.lang.Class) + */ @Override - public HighlightPage queryForHighlightPage(String collection, HighlightQuery query, Class clazz) { - return queryForHighlightPage(collection, query, clazz, getDefaultRequestMethod()); + public HighlightPage queryForHighlightPage(HighlightQuery query, Class clazz) { + return queryForHighlightPage(query, clazz, getDefaultRequestMethod()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForHighlightPage(java.lang.String, org.springframework.data.solr.core.query.HighlightQuery, java.lang.Class) + */ + public HighlightPage queryForHighlightPage(String collectionName, HighlightQuery query, Class clazz) { + return queryForHighlightPage(collectionName, query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForHighlightPage(org.springframework.data.solr.core.query.HighlightQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ @Override - public HighlightPage queryForHighlightPage(String collection, HighlightQuery query, Class clazz, + public HighlightPage queryForHighlightPage(HighlightQuery query, Class clazz, RequestMethod method) { + return queryForHighlightPage(getSolrCoreOrBeanCollection(clazz), query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForHighlightPage(java.lang.String, org.springframework.data.solr.core.query.HighlightQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public HighlightPage queryForHighlightPage(String collectionName, HighlightQuery query, Class clazz, RequestMethod method) { Assert.notNull(query, "Query must not be 'null'."); Assert.notNull(clazz, "Target class must not be 'null'."); NamedObjectsHighlightQuery namedObjectsQuery = new NamedObjectsHighlightQuery(query); - QueryResponse response = querySolr(collection, namedObjectsQuery, clazz, getDefaultRequestMethod()); + QueryResponse response = querySolr(collectionName, namedObjectsQuery, clazz, getDefaultRequestMethod()); return createSolrResultPage(query, clazz, response, namedObjectsQuery.getNamesAssociation()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetAndHighlightPage(org.springframework.data.solr.core.query.FacetAndHighlightQuery, java.lang.Class) + */ @Override - public FacetAndHighlightPage queryForFacetAndHighlightPage(String collection, FacetAndHighlightQuery query, + public FacetAndHighlightPage queryForFacetAndHighlightPage(FacetAndHighlightQuery query, Class clazz) { + return queryForFacetAndHighlightPage(query, clazz, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetAndHighlightPage(java.lang.String, org.springframework.data.solr.core.query.FacetAndHighlightQuery, java.lang.Class) + */ + public FacetAndHighlightPage queryForFacetAndHighlightPage(String collectionName, FacetAndHighlightQuery query, Class clazz) { - return queryForFacetAndHighlightPage(collection, query, clazz, getDefaultRequestMethod()); + return queryForFacetAndHighlightPage(collectionName, query, clazz, getDefaultRequestMethod()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetAndHighlightPage(org.springframework.data.solr.core.query.FacetAndHighlightQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ @Override - public FacetAndHighlightPage queryForFacetAndHighlightPage(String collection, FacetAndHighlightQuery query, + public FacetAndHighlightPage queryForFacetAndHighlightPage(FacetAndHighlightQuery query, Class clazz, + RequestMethod method) { + return queryForFacetAndHighlightPage(getSolrCoreOrBeanCollection(clazz), query, clazz, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForFacetAndHighlightPage(java.lang.String, org.springframework.data.solr.core.query.FacetAndHighlightQuery, java.lang.Class, org.springframework.data.solr.core.RequestMethod) + */ + public FacetAndHighlightPage queryForFacetAndHighlightPage(String collectionName, FacetAndHighlightQuery query, Class clazz, RequestMethod method) { Assert.notNull(query, "Query must not be 'null'."); @@ -421,7 +904,7 @@ public FacetAndHighlightPage queryForFacetAndHighlightPage(String collect NamedObjectsFacetAndHighlightQuery namedObjectsFacetAndHighlightQuery = new NamedObjectsFacetAndHighlightQuery( query); - QueryResponse response = querySolr(collection, namedObjectsFacetAndHighlightQuery, clazz, method); + QueryResponse response = querySolr(collectionName, namedObjectsFacetAndHighlightQuery, clazz, method); Map objectsName = namedObjectsFacetAndHighlightQuery.getNamesAssociation(); return createSolrResultPage(query, clazz, response, objectsName); @@ -437,7 +920,7 @@ private SolrResultPage createSolrResultPage(Query query, Class clazz, Pageable pageRequest = query.getPageRequest(); - SolrResultPage page = new SolrResultPage<>(beans, pageRequest, numFound, maxScore); + SolrResultPage page = new SolrResultPage(beans, pageRequest, numFound, maxScore); page.setFieldStatsResults(ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(response.getFieldStatsInfo())); page.setGroupResults( @@ -469,33 +952,67 @@ private SolrResultPage createSolrResultPage(Query query, Class clazz, return page; } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForTermsPage(org.springframework.data.solr.core.query.TermsQuery) + */ @Override - public TermsPage queryForTermsPage(String collection, TermsQuery query) { - return queryForTermsPage(collection, query, getDefaultRequestMethod()); + public TermsPage queryForTermsPage(TermsQuery query) { + return queryForTermsPage(query, getDefaultRequestMethod()); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForTermsPage(java.lang.String, org.springframework.data.solr.core.query.TermsQuery) + */ + public TermsPage queryForTermsPage(String collectionName, TermsQuery query) { + return queryForTermsPage(collectionName, query, getDefaultRequestMethod()); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForTermsPage(org.springframework.data.solr.core.query.TermsQuery, org.springframework.data.solr.core.RequestMethod) + */ @Override - public TermsPage queryForTermsPage(String collection, TermsQuery query, RequestMethod method) { + public TermsPage queryForTermsPage(TermsQuery query, RequestMethod method) { + return queryForTermsPage(null, query, method); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForTermsPage(java.lang.String, org.springframework.data.solr.core.query.TermsQuery, org.springframework.data.solr.core.RequestMethod) + */ + public TermsPage queryForTermsPage(String collectionName, TermsQuery query, RequestMethod method) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(query, "Query must not be 'null'."); - QueryResponse response = querySolr(collection, query, null, method); + QueryResponse response = querySolr(collectionName, query, null, method); TermsResultPage page = new TermsResultPage(); page.addAllTerms(ResultHelper.convertTermsQueryResponseToTermsMap(response)); return page; } - final QueryResponse querySolr(String collection, SolrDataQuery query, @Nullable Class clazz, - @Nullable RequestMethod requestMethod) { + final QueryResponse querySolr(String collectionName, SolrDataQuery query, Class clazz) { + return querySolr(collectionName, query, clazz, defaultRequestMethod); + } + + final QueryResponse querySolr(String collectionName, SolrDataQuery query, Class clazz, RequestMethod requestMethod) { Assert.notNull(query, "Query must not be 'null'"); + Assert.notNull(requestMethod, "RequestMethod must not be 'null'"); - SolrQuery solrQuery = queryParsers.getForClass(query.getClass()).constructSolrQuery(query); + QueryParser parser = null; + if(query instanceof AbstractQueryDecorator) { + parser = queryParsers.getForClass((Class) ((AbstractQueryDecorator) query).getQueryType()); + } else { + parser = queryParsers.getForClass(query.getClass()); + } + + SolrQuery solrQuery =parser.constructSolrQuery(query); if (clazz != null) { - SolrPersistentEntity persistedEntity = mappingContext.getRequiredPersistentEntity(clazz); + SolrPersistentEntity persistedEntity = mappingContext.getPersistentEntity(clazz); if (persistedEntity.hasScoreProperty()) { solrQuery.setIncludeScore(true); } @@ -503,32 +1020,102 @@ final QueryResponse querySolr(String collection, SolrDataQuery query, @Nullable LOGGER.debug("Executing query '" + solrQuery + "' against solr."); - return executeSolrQuery(collection, solrQuery, getSolrRequestMethod(requestMethod)); + return executeSolrQuery(collectionName, solrQuery, getSolrRequestMethod(requestMethod)); } final QueryResponse executeSolrQuery(final SolrQuery solrQuery, final SolrRequest.METHOD method) { - return executeSolrQuery(null, solrQuery, method); + + return execute(new SolrCallback() { + @Override + public QueryResponse doInSolr(SolrClient solrClient) throws SolrServerException, IOException { + return solrClient.query(solrQuery, method); + } + }); } - final QueryResponse executeSolrQuery(String collection, final SolrQuery solrQuery, final SolrRequest.METHOD method) { + final QueryResponse executeSolrQuery(String collectionName, final SolrQuery solrQuery, + final SolrRequest.METHOD method) { - return execute(solrServer -> solrServer.query(collection, solrQuery, method)); + return execute(collectionName, new CollectionCallback() { + + @Override + public QueryResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return solrClient.query(collection, solrQuery, method); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#commit() + */ @Override - public void commit(String collection) { - execute(solrClient -> solrClient.commit(collection)); + public void commit() { + commit(null); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#commit(java.lang.String) + */ + public void commit(String collectionName) { + + execute(collectionName, new CollectionCallback() { + + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.commit(collection) : solrClient.commit(); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#softCommit() + */ @Override - public void softCommit(String collection) { + public void softCommit() { + softCommit(null); + } - execute(solrClient -> solrClient.commit(collection, true, true, true)); + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#softCommit(java.lang.String) + */ + public void softCommit(String collectionName) { + + execute(collectionName, new CollectionCallback() { + + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.commit(collection, true, true, true) + : solrClient.commit(true, true, true); + } + }); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#rollback() + */ @Override - public void rollback(String collection) { - execute(SolrClient::rollback); + public void rollback() { + rollback(null); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#rollback(java.lang.String) + */ + public void rollback(String collectionName) { + + execute(collectionName, new CollectionCallback() { + + @Override + public UpdateResponse doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return StringUtils.hasText(collection) ? solrClient.rollback(collection) : solrClient.rollback(); + } + }); } /* @@ -555,7 +1142,13 @@ public String getSchemaName(final String collectionName) { return getSchemaOperations(collectionName).getSchemaName(); } - public Cursor queryForCursor(String collection, Query query, final Class clazz) { + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#queryForCursor(org.springframework.data.solr.core.query.Query, java.lang.Class) + */ + @Override + @SuppressWarnings("resource") + public Cursor queryForCursor(Query query, final Class clazz) { return new DelegatingCursor(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) { @@ -563,39 +1156,73 @@ public Cursor queryForCursor(String collection, Query query, final Class< protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult doLoad( SolrQuery nativeQuery) { - QueryResponse response = executeSolrQuery(collection, nativeQuery, - getSolrRequestMethod(getDefaultRequestMethod())); + QueryResponse response = executeSolrQuery(nativeQuery, getSolrRequestMethod(getDefaultRequestMethod())); if (response == null) { - return new PartialResult<>("", Collections. emptyList()); + return new PartialResult("", Collections. emptyList()); } - return new PartialResult<>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz)); + return new PartialResult(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz)); } }.open(); } + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#getById(java.util.Collection, java.lang.Class) + */ @Override - public Collection getByIds(String collection, final Collection ids, final Class clazz) { + public Collection getById(final Collection ids, final Class clazz) { + return getById(getSolrCoreOrBeanCollection(clazz), ids, clazz); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#getById(java.lang.String, java.util.Collection, java.lang.Class) + */ + public Collection getById(String collectionName, final Collection ids, + final Class clazz) { if (CollectionUtils.isEmpty(ids)) { return Collections.emptyList(); } - return execute(solrClient -> convertSolrDocumentListToBeans( - solrClient.getById(collection, ids.stream().map(Object::toString).collect(Collectors.toList())), clazz)); + final List stringIds = new ArrayList(ids.size()); + for (Serializable id : ids) { + stringIds.add(id.toString()); + } + + return execute(collectionName, new CollectionCallback>() { + + @Override + public Collection doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return convertSolrDocumentListToBeans(solrClient.getById(collection, stringIds), clazz); + } + }); } - public Optional getById(String collection, Object id, Class clazz) { + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#getById(java.io.Serializable, java.lang.Class) + */ + @Override + public T getById(Serializable id, Class clazz) { + return getById(getSolrCoreOrBeanCollection(clazz), id, clazz); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.SolrOperations#getById(java.lang.String, java.io.Serializable, java.lang.Class) + */ + public T getById(String collectionName, Serializable id, Class clazz) { - Assert.notNull(collection, "Collection must not be null!"); Assert.notNull(id, "Id must not be 'null'."); - Collection result = getByIds(collection, Collections.singletonList(id), clazz); + Collection result = getById(collectionName, Collections.singletonList(id), clazz); if (result.isEmpty()) { - return Optional.empty(); + return null; } - return Optional.of(result.iterator().next()); + return result.iterator().next(); } /* @@ -612,7 +1239,7 @@ private Collection convertBeansToSolrInputDocuments(Iterable< return Collections.emptyList(); } - List resultList = new ArrayList<>(); + List resultList = new ArrayList(); for (Object bean : beans) { resultList.add(convertBeanToSolrInputDocument(bean)); } @@ -641,7 +1268,7 @@ protected void assertNoCollection(Object o) { } } - private SolrConverter getDefaultSolrConverter() { + private final SolrConverter getDefaultSolrConverter() { MappingSolrConverter converter = new MappingSolrConverter(this.mappingContext); converter.afterPropertiesSet(); // have to call this one to initialize default converters return converter; @@ -653,7 +1280,7 @@ private SolrConverter getDefaultSolrConverter() { */ @Override public final SolrClient getSolrClient() { - return solrClientFactory.getSolrClient(); + return solrClientFactory.getSolrClient(this.solrCore); } /* @@ -669,6 +1296,10 @@ public static PersistenceExceptionTranslator getExceptionTranslator() { return EXCEPTION_TRANSLATOR; } + private String getSolrCoreOrBeanCollection(Class clazz) { + return StringUtils.hasText(solrCore) ? solrCore : mappingContext.getPersistentEntity(clazz).getSolrCoreName(); + } + /* * (non-Javadoc) * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) @@ -686,6 +1317,14 @@ public void setSolrConverter(SolrConverter solrConverter) { this.solrConverter = solrConverter; } + public String getSolrCore() { + return solrCore; + } + + public void setSolrCore(String solrCore) { + this.solrCore = solrCore; + } + /* * (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() @@ -714,7 +1353,7 @@ private void registerPersistenceExceptionTranslator() { } } - private SolrRequest.METHOD getSolrRequestMethod(@Nullable RequestMethod requestMethod) { + private SolrRequest.METHOD getSolrRequestMethod(RequestMethod requestMethod) { RequestMethod rm = requestMethod != null ? requestMethod : getDefaultRequestMethod(); @@ -730,20 +1369,6 @@ private SolrRequest.METHOD getSolrRequestMethod(@Nullable RequestMethod requestM throw new IllegalArgumentException("Unsupported request method type"); } - private int getCommitWithinTimeout(Duration duration) { - - if (duration == null || duration.isZero() || duration.isNegative()) { - return -1; - } - - if (duration.toMillis() > Integer.MAX_VALUE) { - throw new InvalidDataAccessApiUsageException( - String.format("CommitWithin must must not exceed int range but was %s", duration.toMillis())); - } - - return (int) duration.toMillis(); - } - /** * @since 1.3 * @param mappingContext @@ -758,7 +1383,7 @@ public void setMappingContext( * @param schemaCreationFeatures */ public void setSchemaCreationFeatures(Collection schemaCreationFeatures) { - this.schemaCreationFeatures = new HashSet<>(schemaCreationFeatures); + this.schemaCreationFeatures = new HashSet(schemaCreationFeatures); } /** diff --git a/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapter.java b/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapter.java index d0b7e86..fd3374b 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapter.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -27,7 +27,7 @@ */ public class SolrTransactionSynchronizationAdapter extends TransactionSynchronizationAdapter { - private Map delegates = new HashMap<>(2); + private Map delegates = new HashMap(2); private final SolrOperations solrOperations; SolrTransactionSynchronizationAdapter(SolrOperations solrOperations) { @@ -42,7 +42,7 @@ public class SolrTransactionSynchronizationAdapter extends TransactionSynchroniz @Override public void afterCompletion(int status) { - CompletionDelegate delegate = this.delegates.get(status); + CompletionDelegate delegate = this.delegates.get(Integer.valueOf(status)); if (delegate != null) { delegate.execute(this.solrOperations); } @@ -53,10 +53,10 @@ public void register() { } public void registerCompletionDelegate(int transactionStatus, CompletionDelegate completionDelegate) { - this.delegates.put(transactionStatus, completionDelegate); + this.delegates.put(Integer.valueOf(transactionStatus), completionDelegate); } - public interface CompletionDelegate { + public static interface CompletionDelegate { void execute(SolrOperations solrOperations); @@ -64,30 +64,18 @@ public interface CompletionDelegate { public static class CommitTransaction implements CompletionDelegate { - private final String collectionName; - - CommitTransaction(String collectionName) { - this.collectionName = collectionName; - } - @Override public void execute(SolrOperations solrOperations) { - solrOperations.commit(collectionName); + solrOperations.commit(); } } public static class RollbackTransaction implements CompletionDelegate { - private final String collectionName; - - RollbackTransaction(String collectionName) { - this.collectionName = collectionName; - } - @Override public void execute(SolrOperations solrOperations) { - solrOperations.rollback(collectionName); + solrOperations.rollback(); } } diff --git a/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapterBuilder.java b/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapterBuilder.java index d8effdb..cb29a43 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapterBuilder.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTransactionSynchronizationAdapterBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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,7 +15,6 @@ */ package org.springframework.data.solr.core; -import org.springframework.lang.Nullable; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.util.Assert; @@ -25,8 +24,7 @@ */ public class SolrTransactionSynchronizationAdapterBuilder { - @Nullable SolrTransactionSynchronizationAdapter adapter; - @Nullable private String collectionName; + SolrTransactionSynchronizationAdapter adapter; /** * @param solrOperations must not be {@literal null} @@ -40,16 +38,6 @@ public static SolrTransactionSynchronizationAdapterBuilder forOperations(SolrOpe return builder; } - /** - * @param collection - * @return - */ - public SolrTransactionSynchronizationAdapterBuilder onCollection(String collection) { - - this.collectionName = collection; - return this; - } - /** * Creates a {@link SolrTransactionSynchronizationAdapter} reacting on * {@link TransactionSynchronization#STATUS_COMMITTED} and {@link TransactionSynchronization#STATUS_ROLLED_BACK}. @@ -59,9 +47,9 @@ public SolrTransactionSynchronizationAdapterBuilder onCollection(String collecti public SolrTransactionSynchronizationAdapter withDefaultBehaviour() { this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_COMMITTED, - new SolrTransactionSynchronizationAdapter.CommitTransaction(this.collectionName)); + new SolrTransactionSynchronizationAdapter.CommitTransaction()); this.adapter.registerCompletionDelegate(TransactionSynchronization.STATUS_ROLLED_BACK, - new SolrTransactionSynchronizationAdapter.RollbackTransaction(this.collectionName)); + new SolrTransactionSynchronizationAdapter.RollbackTransaction()); return this.adapter; } diff --git a/src/main/java/org/springframework/data/solr/core/TermsQueryParser.java b/src/main/java/org/springframework/data/solr/core/TermsQueryParser.java index 4bc92d8..0d53593 100644 --- a/src/main/java/org/springframework/data/solr/core/TermsQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/TermsQueryParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -25,7 +25,7 @@ /** * TermsQueryParser is capable of building {@link SolrQuery} for {@link TermsQuery} - * + * * @author Christoph Strobl */ public class TermsQueryParser extends QueryParserBase { @@ -90,7 +90,7 @@ private void processTermsFields(SolrQuery solrQuery, TermsQuery query) { } protected void appendTermsFieldToSolrQuery(Field field, SolrQuery solrQuery) { - if (StringUtils.hasText(field.getName())) { + if (field != null && StringUtils.hasText(field.getName())) { solrQuery.addTermsField(field.getName()); } } diff --git a/src/main/java/org/springframework/data/solr/core/convert/CustomConversions.java b/src/main/java/org/springframework/data/solr/core/convert/CustomConversions.java index 3eda77f..0b297e0 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/CustomConversions.java +++ b/src/main/java/org/springframework/data/solr/core/convert/CustomConversions.java @@ -16,38 +16,280 @@ package org.springframework.data.solr.core.convert; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import org.springframework.core.GenericTypeResolver; import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair; +import org.springframework.core.convert.support.GenericConversionService; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; +import org.springframework.data.mapping.model.SimpleTypeHolder; +import org.springframework.data.solr.VersionUtil; +import org.springframework.data.solr.core.geo.GeoConverters.Point3DToStringConverter; +import org.springframework.data.solr.core.geo.GeoConverters.StringToPointConverter; +import org.springframework.data.solr.core.mapping.SolrSimpleTypes; +import org.springframework.util.Assert; /** * CustomConversions holds basically a list of {@link Converter} that can be used for mapping objects to ( * {@link WritingConverter}) and from ({@link ReadingConverter}) solr representation. - * + * * @author Christoph Strobl * @author Rias A. Sherzad - * @author Mark Paluch - * @deprecated since 2.0, use {@link SolrCustomConversions}. */ -@Deprecated -public class CustomConversions extends SolrCustomConversions { +public class CustomConversions { + + private final Set> customSimpleTypes; + private final List converters; + private final Set readingPairs; + private final Set writingPairs; + private SimpleTypeHolder simpleTypeHolder; + + private ConcurrentMap> cache = new ConcurrentHashMap>(36, 0.9f, 1); /** * Create new instance */ public CustomConversions() { - this(new ArrayList<>()); + this(new ArrayList()); } /** * Create new instance registering given converters - * + * * @param converters */ @SuppressWarnings({ "unchecked", "rawtypes" }) public CustomConversions(List converters) { - super(converters); + this.converters = (converters != null ? new ArrayList(converters) : new ArrayList()); + this.readingPairs = new HashSet(); + this.writingPairs = new HashSet(); + this.customSimpleTypes = new HashSet>(); + + this.simpleTypeHolder = new SimpleTypeHolder(customSimpleTypes, SolrSimpleTypes.HOLDER); + + this.converters.add(StringToPointConverter.INSTANCE); + this.converters.add(Point3DToStringConverter.INSTANCE); + this.converters.add(new SolrjConverters.UpdateToSolrInputDocumentConverter()); + + // Register Joda-Time converters only if Joda-Time was found in the classpath. + if (VersionUtil.isJodaTimeAvailable()) { + this.converters.add(DateTimeConverters.DateToJodaDateTimeConverter.INSTANCE); + this.converters.add(DateTimeConverters.JodaDateTimeToDateConverter.INSTANCE); + this.converters.add(DateTimeConverters.DateToLocalDateTimeConverter.INSTANCE); + this.converters.add(DateTimeConverters.JodaLocalDateTimeToDateConverter.INSTANCE); + } + + for (Object converter : this.converters) { + registerConversion(converter); + } + } + + /** + * Register custom converters within given {@link GenericConversionService} + * + * @param conversionService must not be null + */ + public void registerConvertersIn(GenericConversionService conversionService) { + Assert.notNull(conversionService, "ConversionService must not be null!"); + + for (Object converter : converters) { + if (converter instanceof Converter) { + conversionService.addConverter((Converter) converter); + } else if (converter instanceof ConverterFactory) { + conversionService.addConverterFactory((ConverterFactory) converter); + } else if (converter instanceof GenericConverter) { + conversionService.addConverter((GenericConverter) converter); + } else { + throw new IllegalArgumentException("Given object '" + converter + + "' expected to be a Converter, ConverterFactory or GenericeConverter!"); + } + } + } + + /** + * @param clazz + * @return true if given class is considered a simple type + */ + public boolean isSimpleType(Class clazz) { + return simpleTypeHolder.isSimpleType(clazz); + } + + /** + * find most recent write target for given class + * + * @param source must not be null + * @return + */ + public Class getCustomWriteTarget(Class source) { + return getCustomWriteTarget(source, null); + } + + /** + * find most recent write target for given source and targetType + * + * @param sourceType + * @param targetType + * @return + */ + public Class getCustomWriteTarget(Class sourceType, Class targetType) { + Assert.notNull(sourceType, "SourceType must not be null!"); + return getCustomTarget(sourceType, targetType, writingPairs); + } + + Class getCustomTarget(Class sourceType, Class expectedTargetType, Iterable pairs) { + Assert.notNull(sourceType, "SourceType must not be null!"); + Assert.notNull(pairs, "Pairs of ConvertiblePairs must not be null!"); + + ConvertiblePair expectedTypePair = new ConvertiblePair(sourceType, expectedTargetType != null ? expectedTargetType + : Any.class); + + if (cache.containsKey(expectedTypePair)) { + Class cachedTargetType = cache.get(expectedTypePair); + return cachedTargetType != Any.class ? cachedTargetType : null; + } + + for (ConvertiblePair typePair : pairs) { + if (typePair.getSourceType().isAssignableFrom(sourceType)) { + Class targetType = typePair.getTargetType(); + if (expectedTargetType == null || targetType.isAssignableFrom(expectedTargetType)) { + cache.putIfAbsent(expectedTypePair, targetType); + return targetType; + } + } + } + + cache.putIfAbsent(expectedTypePair, Any.class); + return null; + } + + /** + * check if custom read target available for given types + * + * @param sourceType + * @param targetType + * @return true if custom converter registered for source/target type + */ + public boolean hasCustomReadTarget(Class sourceType, Class targetType) { + Assert.notNull(sourceType, "SourceType must not be null!"); + Assert.notNull(targetType, "TargetType must not be null!"); + + return getCustomReadTarget(sourceType, targetType) != null; + } + + /** + * check if custom write target available for given types + * + * @param sourceType + * @param targetType + * @return + */ + public boolean hasCustomWriteTarget(Class sourceType, Class targetType) { + return getCustomTarget(sourceType, targetType, writingPairs) != null; + } + + private Class getCustomReadTarget(Class sourceType, Class targetType) { + return getCustomTarget(sourceType, targetType, readingPairs); + } + + private void registerConversion(Object converter) { + Class type = converter.getClass(); + boolean isWriting = type.isAnnotationPresent(WritingConverter.class); + boolean isReading = type.isAnnotationPresent(ReadingConverter.class); + + if (!isReading && !isWriting) { + isReading = true; + isWriting = true; + } + + if (converter instanceof GenericConverter) { + GenericConverter genericConverter = (GenericConverter) converter; + for (ConvertiblePair pair : genericConverter.getConvertibleTypes()) { + register(new ConvertibleContext(pair, isReading, isWriting)); + } + } else if (converter instanceof Converter) { + Class[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class); + register(new ConvertibleContext(arguments[0], arguments[1], isReading, isWriting)); + } else { + throw new IllegalArgumentException("Unsupported Converter type! Expected either GenericConverter if Converter."); + } + } + + private void register(ConvertibleContext context) { + ConvertiblePair pair = context.getConvertible(); + if (context.isReading()) { + readingPairs.add(pair); + } + if (context.isWriting()) { + writingPairs.add(pair); + customSimpleTypes.add(pair.getSourceType()); + } + } + + /** + * ConvertibleContext is a holder for {@link ConvertiblePair} and read/write information + * + * @author Christoph Strobl + */ + static class ConvertibleContext { + + private final ConvertiblePair convertible; + private final boolean reading; + private final boolean writing; + + /** + * Create new instance + * + * @param convertible + * @param isReading + * @param isWriting + */ + public ConvertibleContext(ConvertiblePair convertible, boolean isReading, boolean isWriting) { + Assert.notNull(convertible, "ConvertiblePair must not be null!"); + this.convertible = convertible; + this.reading = isReading; + this.writing = isWriting; + } + + /** + * Create new instance wrapping source/target into {@link ConvertiblePair} + * + * @param source + * @param target + * @param isReading + * @param isWriting + */ + public ConvertibleContext(Class source, Class target, boolean isReading, boolean isWriting) { + this(new ConvertiblePair(source, target), isReading, isWriting); + } + + public ConvertiblePair getConvertible() { + return convertible; + } + + public boolean isReading() { + return reading; + } + + public boolean isWriting() { + return writing; + } + + } + + /** + * Simple placeholder as {@link ConvertiblePair} will not allow null values + * + * @author Christoph Strobl + */ + private static class Any { + } } diff --git a/src/main/java/org/springframework/data/solr/core/convert/DateTimeConverters.java b/src/main/java/org/springframework/data/solr/core/convert/DateTimeConverters.java index d14ad82..7d6aafa 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/DateTimeConverters.java +++ b/src/main/java/org/springframework/data/solr/core/convert/DateTimeConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -27,7 +27,6 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; -import org.springframework.util.Assert; /** * Converts a Date values into a solr readable String that can be directly used within the {@code q} parameter. Note @@ -35,7 +34,9 @@ * * Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); * calendar.set(2012, 7, 23, 6, 10, 0); - * will be formatted as + * + * + * will be formatted as * *
  * 2012-08-23T06:10:00.000Z
@@ -53,6 +54,7 @@ public final class DateTimeConverters {
 	 * {@link org.apache.solr.client.solrj.SolrQuery} query string values
 	 * 
 	 * @author Christoph Strobl
+	 * 
 	 */
 	@WritingConverter
 	public enum JodaDateTimeConverter implements Converter {
@@ -60,9 +62,9 @@ public enum JodaDateTimeConverter implements Converter
 
 		@Override
 		public String convert(ReadableInstant source) {
-
-			Assert.notNull(source, "Source must not be null!");
-
+			if (source == null) {
+				return null;
+			}
 			return (ClientUtils.escapeQueryChars(FORMATTER.print(source.getMillis())));
 		}
 
@@ -74,9 +76,9 @@ public enum StringToJodaDateTimeConverter implements Converter
 
 		@Override
 		public DateTime convert(String source) {
-
-			Assert.notNull(source, "Source must not be null!");
-
+			if (source == null) {
+				return null;
+			}
 			return DateTime.parse(source, FORMATTER_WITHOUT_MILLIS);
 		}
 	}
@@ -85,6 +87,7 @@ public DateTime convert(String source) {
 	 * Reading {@link Converter} parses {@link Date} from {@link org.apache.solr.common.SolrDocument} to {@link DateTime}
 	 * 
 	 * @author Christoph Strobl
+	 * 
 	 */
 	@ReadingConverter
 	public enum DateToJodaDateTimeConverter implements Converter {
@@ -92,9 +95,9 @@ public enum DateToJodaDateTimeConverter implements Converter {
 
 		@Override
 		public DateTime convert(Date source) {
-
-			Assert.notNull(source, "Source must not be null!");
-
+			if (source == null) {
+				return null;
+			}
 			return new DateTime(source.getTime());
 		}
 	}
@@ -104,6 +107,7 @@ public DateTime convert(Date source) {
 	 * {@link org.apache.solr.common.SolrInputDocument}
 	 * 
 	 * @author Christoph Strobl
+	 * 
 	 */
 	@WritingConverter
 	public enum JodaDateTimeToDateConverter implements Converter {
@@ -111,9 +115,9 @@ public enum JodaDateTimeToDateConverter implements Converter {
 
 		@Override
 		public Date convert(DateTime source) {
-
-			Assert.notNull(source, "Source must not be null!");
-
+			if (source == null) {
+				return null;
+			}
 			return source.toDate();
 		}
 
@@ -124,6 +128,7 @@ public Date convert(DateTime source) {
 	 * {@link org.apache.solr.client.solrj.SolrQuery} query string values
 	 * 
 	 * @author Christoph Strobl
+	 * 
 	 */
 	@WritingConverter
 	public enum JodaLocalDateTimeConverter implements Converter {
@@ -131,9 +136,9 @@ public enum JodaLocalDateTimeConverter implements Converter {
@@ -151,9 +157,9 @@ public enum JodaLocalDateTimeToDateConverter implements Converter {
@@ -171,9 +178,9 @@ public enum DateToLocalDateTimeConverter implements Converter {
@@ -191,8 +199,9 @@ public enum JavaDateConverter implements Converter {
 
 		@Override
 		public String convert(Date source) {
-
-			Assert.notNull(source, "Source must not be null!");
+			if (source == null) {
+				return null;
+			}
 
 			return ClientUtils.escapeQueryChars(FORMATTER.print(source.getTime()));
 		}
diff --git a/src/main/java/org/springframework/data/solr/core/convert/MappingSolrConverter.java b/src/main/java/org/springframework/data/solr/core/convert/MappingSolrConverter.java
index 25a39cb..58e2c41 100644
--- a/src/main/java/org/springframework/data/solr/core/convert/MappingSolrConverter.java
+++ b/src/main/java/org/springframework/data/solr/core/convert/MappingSolrConverter.java
@@ -19,13 +19,12 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 
 import org.apache.commons.lang3.StringUtils;
-import org.apache.solr.common.SolrDocument;
-import org.apache.solr.common.SolrDocumentBase;
 import org.apache.solr.common.SolrDocumentList;
 import org.apache.solr.common.SolrInputDocument;
 import org.apache.solr.common.SolrInputField;
@@ -36,11 +35,11 @@
 import org.springframework.core.CollectionFactory;
 import org.springframework.data.convert.EntityInstantiator;
 import org.springframework.data.convert.EntityInstantiators;
-import org.springframework.data.mapping.MappingException;
 import org.springframework.data.mapping.PersistentPropertyAccessor;
 import org.springframework.data.mapping.PropertyHandler;
 import org.springframework.data.mapping.context.MappingContext;
 import org.springframework.data.mapping.model.ConvertingPropertyAccessor;
+import org.springframework.data.mapping.model.MappingException;
 import org.springframework.data.mapping.model.ParameterValueProvider;
 import org.springframework.data.mapping.model.PersistentEntityParameterValueProvider;
 import org.springframework.data.mapping.model.PropertyValueProvider;
@@ -49,7 +48,6 @@
 import org.springframework.data.solr.core.query.Criteria;
 import org.springframework.data.util.ClassTypeInformation;
 import org.springframework.data.util.TypeInformation;
-import org.springframework.lang.Nullable;
 import org.springframework.util.Assert;
 import org.springframework.util.ClassUtils;
 import org.springframework.util.CollectionUtils;
@@ -57,10 +55,9 @@
 /**
  * Implementation of {@link SolrConverter} to read/write {@link org.apache.solr.common.SolrDocument}/
  * {@link SolrInputDocument}. 
- * + * * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ public class MappingSolrConverter extends SolrConverterBase implements SolrConverter, ApplicationContextAware, InitializingBean { @@ -128,7 +125,7 @@ String removeWildcard(String fieldName) { private final EntityInstantiators instantiators = new EntityInstantiators(); @SuppressWarnings("unused") // - private @Nullable ApplicationContext applicationContext; + private ApplicationContext applicationContext; public MappingSolrConverter( MappingContext, SolrPersistentProperty> mappingContext) { @@ -143,14 +140,14 @@ public MappingContext, SolrPersistentProperty> } @Override - public List read(@Nullable SolrDocumentList source, Class type) { - if (source == null) { + public List read(SolrDocumentList source, Class type) { + if (CollectionUtils.isEmpty(source)) { return Collections.emptyList(); } - List resultList = new ArrayList<>(source.size()); + List resultList = new ArrayList(source.size()); TypeInformation typeInformation = ClassTypeInformation.from(type); - for (SolrDocumentBase item : source) { + for (Map item : source) { resultList.add(read(typeInformation, item)); } @@ -158,13 +155,12 @@ public List read(@Nullable SolrDocumentList source, Class type) { } @Override - public R read(Class type, SolrDocumentBase source) { + public R read(Class type, Map source) { return read(ClassTypeInformation.from(type), source); } @SuppressWarnings("unchecked") - @Nullable - protected S read(TypeInformation targetTypeInformation, @Nullable SolrDocumentBase source) { + protected S read(TypeInformation targetTypeInformation, Map source) { if (source == null) { return null; } @@ -176,11 +172,11 @@ protected S read(TypeInformation targetTypeInformation, @Nullable SolrDoc return convert(source, rawType); } - SolrPersistentEntity entity = (SolrPersistentEntity) mappingContext.getRequiredPersistentEntity(rawType); + SolrPersistentEntity entity = (SolrPersistentEntity) mappingContext.getPersistentEntity(rawType); return read(entity, source, null); } - private S read(final SolrPersistentEntity entity, final SolrDocumentBase source, @Nullable Object parent) { + private S read(final SolrPersistentEntity entity, final Map source, Object parent) { ParameterValueProvider parameterValueProvider = getParameterValueProvider(entity, source, parent); @@ -189,68 +185,44 @@ private S read(final SolrPersistentEntity entity, final SolrDocumentBase final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance), getConversionService()); - entity.doWithProperties((PropertyHandler) persistentProperty -> { - if (entity.isConstructorArgument(persistentProperty)) { - return; - } - - Object val = getValue(persistentProperty, source, instance); - - if (val == null) { - return; - } - - if (persistentProperty.isChildProperty()) { + entity.doWithProperties(new PropertyHandler() { - List childDocuments = source.getChildDocuments(); - List target = new ArrayList<>(childDocuments.size()); - for (SolrDocument childDocument : childDocuments) { - target.add(read(persistentProperty.getActualType(), childDocument)); + @Override + public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) { + if (entity.isConstructorArgument(persistentProperty)) { + return; } - if (persistentProperty.isCollectionLike()) { + Object o = getValue(persistentProperty, source, instance); + if (o != null) { - if (persistentProperty.getActualType().isArray()) { - accessor.setProperty(persistentProperty, - convertItemsToArrayOfType(persistentProperty.getTypeInformation(), target)); - } else { - accessor.setProperty(persistentProperty, target); - } - } else { - accessor.setProperty(persistentProperty, target.iterator().next()); - } - } + if (o instanceof Collection && !persistentProperty.isCollectionLike()) { - else if (val instanceof Collection && !persistentProperty.isCollectionLike()) { + Collection c = (Collection) o; - Collection c = (Collection) val; + if (!c.isEmpty()) { - if (!c.isEmpty()) { + if (c.size() == 1) { + accessor.setProperty(persistentProperty, c.iterator().next()); + } else { + throw new MappingException(String.format( + "Cannot set multiple values %s read from '%s' to non collection property '%s'. Please check your mapping / schema defintion!", + c, persistentProperty.getFieldName(), persistentProperty.getName())); + } + } - if (c.size() == 1) { - accessor.setProperty(persistentProperty, c.iterator().next()); } else { - throw new MappingException(String.format( - "Cannot set multiple values %s read from '%s' to non collection property '%s'. Please check your mapping / schema defintion!", - c, persistentProperty.getFieldName(), persistentProperty.getName())); + accessor.setProperty(persistentProperty, o); } + } - } else { - accessor.setProperty(persistentProperty, val); } }); return instance; } - @Nullable protected Object getValue(SolrPersistentProperty property, Object source, Object parent) { - - if (property.isChildProperty() && source instanceof SolrDocumentBase - && ((SolrDocumentBase) source).hasChildDocuments()) { - return ((SolrDocumentBase) source).getChildDocuments(); - } - SolrPropertyValueProvider provider = new SolrPropertyValueProvider(source, parent); return provider.getPropertyValue(property); } @@ -259,14 +231,21 @@ private ParameterValueProvider getParameterValueProvider Map source, Object parent) { SolrPropertyValueProvider provider = new SolrPropertyValueProvider(source, parent); - return new PersistentEntityParameterValueProvider<>(entity, provider, parent); + PersistentEntityParameterValueProvider parameterProvider = new PersistentEntityParameterValueProvider( + entity, provider, parent); + + return parameterProvider; } @SuppressWarnings("unchecked") @Override - public void write(Object source, @SuppressWarnings("rawtypes") SolrDocumentBase target) { + public void write(Object source, @SuppressWarnings("rawtypes") Map target) { - Class sourceClass = source.getClass(); + if (source == null) { + return; + } + + Class sourceClass = source.getClass(); if (hasCustomWriteTarget(sourceClass, SolrInputDocument.class) && canConvert(sourceClass, SolrInputDocument.class)) { @@ -275,58 +254,45 @@ && canConvert(sourceClass, SolrInputDocument.class)) { target.putAll(convertedDocument); } else { - SolrPersistentEntity entity = mappingContext.getRequiredPersistentEntity(sourceClass); + SolrPersistentEntity entity = mappingContext.getPersistentEntity(sourceClass); write(source, target, entity); } } @SuppressWarnings("rawtypes") - protected void write(Object source, final SolrDocumentBase target, SolrPersistentEntity entity) { + protected void write(Object source, final Map target, SolrPersistentEntity entity) { final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(source), getConversionService()); - entity.doWithProperties((PropertyHandler) persistentProperty -> { - - Object value = accessor.getProperty(persistentProperty); - if (value == null || persistentProperty.isReadonly()) { - return; - } - - if (persistentProperty.containsWildcard() && !persistentProperty.isMap()) { - throw new IllegalArgumentException("Field '" + persistentProperty.getFieldName() - + "' must not contain wildcards. Consider excluding Field from beeing indexed."); - } + entity.doWithProperties(new PropertyHandler() { - Collection fields = null; - if (persistentProperty.isMap() && persistentProperty.containsWildcard()) { - fields = writeWildcardMapPropertyToTarget(target, persistentProperty, (Map) value); - } else if (persistentProperty.isEntity() && persistentProperty.isChildProperty()) { + @SuppressWarnings("unchecked") + @Override + public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) { - List nestedDocs = new ArrayList<>(); + Object value = accessor.getProperty(persistentProperty); + if (value == null || persistentProperty.isReadonly()) { + return; + } - if (persistentProperty.isCollectionLike()) { + if (persistentProperty.containsWildcard() && !persistentProperty.isMap()) { + throw new IllegalArgumentException("Field '" + persistentProperty.getFieldName() + + "' must not contain wildcards. Consider excluding Field from beeing indexed."); + } - for (Object obj : asCollection(value)) { - SolrInputDocument nested = new SolrInputDocument(); - write(obj, nested, mappingContext.getRequiredPersistentEntity(persistentProperty.getActualType())); - nestedDocs.add(nested); - } + Collection fields; + if (persistentProperty.isMap() && persistentProperty.containsWildcard()) { + fields = writeWildcardMapPropertyToTarget(target, persistentProperty, (Map) value); } else { - SolrInputDocument nested = new SolrInputDocument(); - write(value, nested, mappingContext.getRequiredPersistentEntity(persistentProperty.getActualType())); - nestedDocs.add(nested); + fields = writeRegularPropertyToTarget(target, persistentProperty, value); } - target.addChildDocuments(nestedDocs); - } else { - fields = writeRegularPropertyToTarget(target, persistentProperty, value); - } - - if (fields != null && persistentProperty.isBoosted()) { - for (SolrInputField field : fields) { - field.setBoost(persistentProperty.getBoost()); + if (persistentProperty.isBoosted()) { + for (SolrInputField field : fields) { + field.setBoost(persistentProperty.getBoost()); + } } } }); @@ -337,14 +303,14 @@ protected void write(Object source, final SolrDocumentBase target, SolrPersisten } - private Collection writeWildcardMapPropertyToTarget(SolrDocumentBase target, + private Collection writeWildcardMapPropertyToTarget(Map target, SolrPersistentProperty persistentProperty, Map fieldValue) { - TypeInformation mapTypeInformation = persistentProperty.getTypeInformation().getRequiredMapValueType(); + TypeInformation mapTypeInformation = persistentProperty.getTypeInformation().getMapValueType(); Class rawMapType = mapTypeInformation.getType(); String fieldName = persistentProperty.getFieldName(); - Collection fields = new ArrayList<>(); + Collection fields = new ArrayList(); for (Map.Entry entry : fieldValue.entrySet()) { @@ -381,7 +347,7 @@ private Collection writeWildcardMapPropertyToTarget(SolrDocument return fields; } - private Collection writeRegularPropertyToTarget(final SolrDocumentBase target, + private Collection writeRegularPropertyToTarget(final Map target, SolrPersistentProperty persistentProperty, Object fieldValue) { SolrInputField field = new SolrInputField(persistentProperty.getFieldName()); @@ -390,16 +356,18 @@ private Collection writeRegularPropertyToTarget(final SolrDocume Collection collection = asCollection(fieldValue); for (Object o : collection) { if (o != null) { - if (o instanceof Enum) { + if(o instanceof Enum) { field.addValue(this.getConversionService().convert(o, String.class), 1f); } else { field.addValue(convertToSolrType(persistentProperty.getType(), o), 1f); } } } - } else if (fieldValue instanceof Enum) { + } + else if (fieldValue instanceof Enum) { field.setValue(this.getConversionService().convert(fieldValue, String.class), 1f); - } else { + } + else { field.setValue(convertToSolrType(persistentProperty.getType(), fieldValue), 1f); } @@ -409,16 +377,21 @@ private Collection writeRegularPropertyToTarget(final SolrDocume } - private Object convertToSolrType(@Nullable Class type, @Nullable Object value) { - + private Object convertToSolrType(Class type, Object value) { if (type == null || value == null) { return value; } - return getCustomWriteTargetType(value.getClass()) // - .filter(targetType -> canConvert(value.getClass(), targetType)) // - .map(targetType -> (Object) convert(value, targetType)) // - .orElse(value); + if (isSimpleType(type)) { + return value; + } else if (hasCustomWriteTarget(value.getClass())) { + Class targetType = getCustomWriteTargetType(value.getClass()); + if (canConvert(value.getClass(), targetType)) { + return convert(value, targetType); + } + } + + return value; } private static Collection asCollection(Object source) { @@ -445,22 +418,18 @@ public SolrPropertyValueProvider(Object source, Object parent) { this.parent = parent; } - @Override @SuppressWarnings("unchecked") - @Nullable + @Override public T getPropertyValue(SolrPersistentProperty property) { - if (source instanceof Map) { - return readValue((Map) source, property, parent); + return (T) readValue((Map) source, property, parent); } return readValue(source, property.getTypeInformation(), this.parent); } @SuppressWarnings("unchecked") - @Nullable - private T readValue(@Nullable Map value, SolrPersistentProperty property, Object parent) { - + private T readValue(Map value, SolrPersistentProperty property, Object parent) { if (value == null) { return null; } @@ -470,7 +439,6 @@ private T readValue(@Nullable Map value, SolrPersistentProperty p if (property.isScoreProperty()) { return (T) readScore(value, property, parent); } - return readValue(value.get(property.getFieldName()), property.getTypeInformation(), parent); } @@ -480,9 +448,7 @@ private T readScore(Map value, SolrPersistentProperty property, O } @SuppressWarnings("unchecked") - @Nullable - private T readValue(@Nullable Object value, TypeInformation type, Object parent) { - + private T readValue(Object value, TypeInformation type, Object parent) { if (value == null) { return null; } @@ -510,7 +476,6 @@ private T readValue(@Nullable Object value, TypeInformation type, Object } - @Nullable private Object readWildcard(Map source, SolrPersistentProperty property, Object parent) { WildcardPosition wildcardPosition = WildcardPosition.getAppropriate(property.getFieldName()); @@ -532,13 +497,12 @@ private Object readWildcard(Map source, SolrPersistentProperty proper return null; } - @Nullable private Object readWildcardCollectionLike(Map source, SolrPersistentProperty property, Object parent, WildcardPosition wildcardPosition) { Class genericTargetType = property.getComponentType() != null ? property.getComponentType() : Object.class; - List values = new ArrayList<>(); + List values = new ArrayList(); for (Map.Entry potentialMatch : source.entrySet()) { @@ -567,11 +531,10 @@ private Object readWildcardCollectionLike(Map source, SolrPersistentP return values.isEmpty() ? null : (property.isArray() ? values.toArray() : values); } - @Nullable private Object readWildcardMap(Map source, SolrPersistentProperty property, Object parent, WildcardPosition wildcardPosition) { - TypeInformation mapTypeInformation = property.getTypeInformation().getRequiredMapValueType(); + TypeInformation mapTypeInformation = property.getTypeInformation().getMapValueType(); Class rawMapType = mapTypeInformation.getType(); Class genericTargetType; @@ -583,9 +546,9 @@ private Object readWildcardMap(Map source, SolrPersistentProperty pro Map values; if (LinkedHashMap.class.isAssignableFrom(property.getActualType())) { - values = new LinkedHashMap<>(); + values = new LinkedHashMap(); } else { - values = new HashMap<>(); + values = new HashMap(); } for (Map.Entry potentialMatch : source.entrySet()) { @@ -604,7 +567,7 @@ private Object readWildcardMap(Map source, SolrPersistentProperty pro if (value instanceof Iterable) { if (rawMapType.isArray() || ClassUtils.isAssignable(rawMapType, value.getClass())) { - List nestedValues = new ArrayList<>(); + List nestedValues = new ArrayList(); for (Object o : (Iterable) value) { nestedValues.add(readValue(property, o, parent, genericTargetType)); } @@ -616,7 +579,7 @@ private Object readWildcardMap(Map source, SolrPersistentProperty pro } else { if (rawMapType.isArray() || ClassUtils.isAssignable(rawMapType, List.class)) { - ArrayList singletonArrayList = new ArrayList<>(1); + ArrayList singletonArrayList = new ArrayList(1); Object read = readValue(property, value, parent, genericTargetType); singletonArrayList.add(read); values.put(key, (rawMapType.isArray() ? singletonArrayList.toArray() : singletonArrayList)); @@ -630,11 +593,9 @@ private Object readWildcardMap(Map source, SolrPersistentProperty pro return values.isEmpty() ? null : values; } - @Nullable - private Object readValue(SolrPersistentProperty property, Object o, Object parent, @Nullable Class target) { + private Object readValue(SolrPersistentProperty property, Object o, Object parent, Class target) { Object value = getValue(property, o, parent); - if (value == null || target == null || target.equals(Object.class)) { return value; } @@ -646,7 +607,6 @@ private Object readValue(SolrPersistentProperty property, Object o, Object paren return value; } - @Nullable private Object readCollection(Collection source, TypeInformation type, Object parent) { Assert.notNull(type, "Type must not be null!"); @@ -659,27 +619,29 @@ private Object readCollection(Collection source, TypeInformation type, Obj Collection items; if (type.getType().isArray()) { - items = new ArrayList<>(); + items = new ArrayList(); } else { items = CollectionFactory.createCollection(collectionType, source.size()); } - TypeInformation componentType = type.isCollectionLike() ? type.getRequiredComponentType() : type; + TypeInformation componentType = type.isCollectionLike() ? type.getComponentType() : type; - for (Object aSource : source) { - items.add(readValue(aSource, componentType, parent)); + Iterator it = source.iterator(); + while (it.hasNext()) { + items.add(readValue(it.next(), componentType, parent)); } return type.getType().isArray() ? convertItemsToArrayOfType(type, items) : items; } - } - - private Object convertItemsToArrayOfType(TypeInformation type, Collection items) { + private Object convertItemsToArrayOfType(TypeInformation type, Collection items) { - Object[] newArray = (Object[]) java.lang.reflect.Array.newInstance(type.getActualType().getType(), items.size()); - Object[] itemsArray = items.toArray(); - System.arraycopy(itemsArray, 0, newArray, 0, itemsArray.length); - return newArray; + Object[] newArray = (Object[]) java.lang.reflect.Array.newInstance(type.getActualType().getType(), items.size()); + Object[] itemsArray = items.toArray(); + for (int i = 0; i < itemsArray.length; i++) { + newArray[i] = itemsArray[i]; + } + return newArray; + } } } diff --git a/src/main/java/org/springframework/data/solr/core/convert/NumberConverters.java b/src/main/java/org/springframework/data/solr/core/convert/NumberConverters.java index 7f0d43d..5e90c7d 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/NumberConverters.java +++ b/src/main/java/org/springframework/data/solr/core/convert/NumberConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -17,7 +17,6 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; -import org.springframework.util.Assert; /** * Converts a Number values into a solr readable String that can be directly used within the {@code q} parameter. @@ -33,8 +32,9 @@ public enum NumberConverter implements Converter { @Override public String convert(Number source) { - - Assert.notNull(source, "Source must not be null!"); + if (source == null) { + return null; + } if (source.doubleValue() < 0d) { return "\\" + source.toString(); diff --git a/src/main/java/org/springframework/data/solr/core/convert/SolrConverter.java b/src/main/java/org/springframework/data/solr/core/convert/SolrConverter.java index 3c5f9fb..ca6dec6 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/SolrConverter.java +++ b/src/main/java/org/springframework/data/solr/core/convert/SolrConverter.java @@ -18,7 +18,6 @@ import java.util.List; import java.util.Map; -import org.apache.solr.common.SolrDocumentBase; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.springframework.data.convert.EntityConverter; @@ -26,15 +25,14 @@ import org.springframework.data.convert.EntityWriter; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; -import org.springframework.lang.Nullable; /** * @author Christoph Strobl */ public interface SolrConverter extends -EntityConverter, SolrPersistentProperty, Object, SolrDocumentBase>, - EntityWriter, EntityReader { +EntityConverter, SolrPersistentProperty, Object, Map>, + EntityWriter>, EntityReader> { /** * Read {@link SolrDocumentList} and convert to {@link List} of given type @@ -43,7 +41,7 @@ public interface SolrConverter extends * @param type * @return empty list if {@code source == null || source.isEmpty()} */ - List read(@Nullable SolrDocumentList source, Class type); + List read(SolrDocumentList source, Class type); /** * Write values to {@link List} of {@link SolrInputDocument} diff --git a/src/main/java/org/springframework/data/solr/core/convert/SolrConverterBase.java b/src/main/java/org/springframework/data/solr/core/convert/SolrConverterBase.java index 71facb0..3a7e706 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/SolrConverterBase.java +++ b/src/main/java/org/springframework/data/solr/core/convert/SolrConverterBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -19,31 +19,27 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Optional; import org.apache.solr.common.SolrInputDocument; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; -import org.springframework.data.convert.CustomConversions; -import org.springframework.lang.Nullable; -import org.springframework.util.Assert; /** * @author Christoph Strobl - * @author Mark Paluch */ public abstract class SolrConverterBase implements SolrConverter, InitializingBean { private final GenericConversionService conversionService = new DefaultConversionService(); - private CustomConversions customConversions = new SolrCustomConversions(Collections.emptyList()); + private CustomConversions customConversions = new CustomConversions(); @Override - public Collection write(@Nullable Iterable source) { - - Assert.notNull(source, "Source must not be null!"); + public Collection write(Iterable source) { + if (source == null) { + return Collections.emptyList(); + } - List resultList = new ArrayList<>(); + List resultList = new ArrayList(); for (Object bean : source) { if (bean instanceof SolrInputDocument) { resultList.add((SolrInputDocument) bean); @@ -57,7 +53,7 @@ public Collection write(@Nullable Iterable source) { /** * create a new {@link SolrInputDocument} for given source and write values to it - * + * * @param source * @return */ @@ -88,7 +84,7 @@ protected boolean hasCustomReadTarget(Class sourceType, Class targetType) * @return true if custom write target defined in {@link #customConversions} */ protected boolean hasCustomWriteTarget(Class sourceType) { - return this.customConversions.hasCustomWriteTarget(sourceType); + return this.customConversions.hasCustomWriteTarget(sourceType, null); } /** @@ -110,20 +106,20 @@ protected boolean isSimpleType(Class type) { /** * get the target conversion type - * + * * @param type * @return */ - protected Optional> getCustomWriteTargetType(Class type) { + protected Class getCustomWriteTargetType(Class type) { return customConversions.getCustomWriteTarget(type); } /** * register {@link #customConversions} with {@link #conversionService} - * + * * @param conversionService */ - protected void registerCustomConverters(GenericConversionService conversionService) { + protected void registerCutomConverters(GenericConversionService conversionService) { if (customConversions != null) { customConversions.registerConvertersIn(conversionService); } @@ -132,8 +128,8 @@ protected void registerCustomConverters(GenericConversionService conversionServi /** * @param customConversions */ - public void setCustomConversions(@Nullable CustomConversions customConversions) { - this.customConversions = customConversions != null ? customConversions : new SolrCustomConversions(Collections.emptyList()); + public void setCustomConversions(CustomConversions customConversions) { + this.customConversions = customConversions != null ? customConversions : new CustomConversions(); } @Override @@ -152,19 +148,18 @@ protected boolean canConvert(Class sourceType, Class targetType) { /** * Convert given object into target type - * + * * @param source * @param targetType * @return */ - @Nullable protected T convert(Object source, Class targetType) { return this.conversionService.convert(source, targetType); } @Override public void afterPropertiesSet() { - registerCustomConverters(this.conversionService); + registerCutomConverters(this.conversionService); } } diff --git a/src/main/java/org/springframework/data/solr/core/convert/SolrCustomConversions.java b/src/main/java/org/springframework/data/solr/core/convert/SolrCustomConversions.java deleted file mode 100644 index c20172c..0000000 --- a/src/main/java/org/springframework/data/solr/core/convert/SolrCustomConversions.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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.solr.core.convert; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.springframework.data.solr.core.geo.GeoConverters.Point3DToStringConverter; -import org.springframework.data.solr.core.geo.GeoConverters.StringToPointConverter; -import org.springframework.data.solr.core.mapping.SolrSimpleTypes; - -/** - * Value object to capture custom conversion. {@link SolrCustomConversions} also act as factory for - * {@link org.springframework.data.mapping.model.SimpleTypeHolder} - * - * @author Mark Paluch - * @since 2.0 - * @see org.springframework.data.convert.CustomConversions - * @see org.springframework.data.mapping.model.SimpleTypeHolder - */ -public class SolrCustomConversions extends org.springframework.data.convert.CustomConversions { - - private static final StoreConversions STORE_CONVERSIONS; - - private static final List STORE_CONVERTERS; - - static { - - List converters = new ArrayList<>(); - - converters.add(StringToPointConverter.INSTANCE); - converters.add(Point3DToStringConverter.INSTANCE); - converters.add(new SolrjConverters.UpdateToSolrInputDocumentConverter()); - - STORE_CONVERTERS = Collections.unmodifiableList(converters); - STORE_CONVERSIONS = StoreConversions.of(SolrSimpleTypes.HOLDER, STORE_CONVERTERS); - } - - /** - * Create a new {@link SolrCustomConversions} instance registering the given converters. - * - * @param converters must not be {@literal null}. - */ - public SolrCustomConversions(List converters) { - super(STORE_CONVERSIONS, converters); - } -} diff --git a/src/main/java/org/springframework/data/solr/core/convert/SolrJConverter.java b/src/main/java/org/springframework/data/solr/core/convert/SolrJConverter.java index 99cd83d..9ccd921 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/SolrJConverter.java +++ b/src/main/java/org/springframework/data/solr/core/convert/SolrJConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -22,7 +22,6 @@ import org.apache.solr.client.solrj.beans.DocumentObjectBinder; import org.apache.solr.common.SolrDocument; -import org.apache.solr.common.SolrDocumentBase; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.springframework.data.mapping.context.MappingContext; @@ -30,7 +29,6 @@ import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; import org.springframework.data.solr.core.query.Update; -import org.springframework.lang.Nullable; /** * Trivial implementation of {@link SolrConverter} delegating conversion to {@link DocumentObjectBinder} @@ -52,13 +50,13 @@ public MappingContext, SolrPersistentProperty> } @Override - public List read(@Nullable SolrDocumentList source, Class type) { + public List read(SolrDocumentList source, Class type) { if (source == null) { return Collections.emptyList(); } - List resultList = new ArrayList<>(source.size()); - for (SolrDocumentBase item : source) { + List resultList = new ArrayList(source.size()); + for (Map item : source) { resultList.add(read(type, item)); } @@ -66,7 +64,7 @@ public List read(@Nullable SolrDocumentList source, Class type) { } @Override - public R read(Class type, SolrDocumentBase source) { + public R read(Class type, Map source) { if (!canConvert(SolrDocument.class, type)) { initializeTypedConverter(source, type); } @@ -75,17 +73,16 @@ public R read(Class type, SolrDocumentBase source) { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void write(@Nullable Object source, SolrDocumentBase sink) { + public void write(Object source, Map sink) { if (source == null) { return; } SolrInputDocument convertedDocument = convert(source, SolrInputDocument.class); - sink.putAll(convertedDocument); - if (convertedDocument.hasChildDocuments() && sink instanceof SolrInputDocument) { ((SolrInputDocument) sink).addChildDocuments(convertedDocument.getChildDocuments()); } + sink.putAll(convertedDocument); } private void initializeConverters() { @@ -93,15 +90,15 @@ private void initializeConverters() { getConversionService().addConverter(new SolrjConverters.UpdateToSolrInputDocumentConverter()); } if (!canConvert(Object.class, SolrInputDocument.class)) { - getConversionService() - .addConverter(new SolrjConverters.ObjectToSolrInputDocumentConverter(new DocumentObjectBinder())); + getConversionService().addConverter( + new SolrjConverters.ObjectToSolrInputDocumentConverter(new DocumentObjectBinder())); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void initializeTypedConverter(Map source, Class rawType) { getConversionService().addConverter((Class) source.getClass(), (Class) rawType, - new SolrjConverters.SolrInputDocumentToObjectConverter<>((Class) rawType)); + new SolrjConverters.SolrInputDocumentToObjectConverter((Class) rawType)); } } diff --git a/src/main/java/org/springframework/data/solr/core/convert/SolrjConverters.java b/src/main/java/org/springframework/data/solr/core/convert/SolrjConverters.java index 6d77571..30a11f5 100644 --- a/src/main/java/org/springframework/data/solr/core/convert/SolrjConverters.java +++ b/src/main/java/org/springframework/data/solr/core/convert/SolrjConverters.java @@ -28,7 +28,6 @@ import org.springframework.data.solr.core.query.Update; import org.springframework.data.solr.core.query.UpdateField; import org.springframework.data.solr.core.query.ValueHoldingField; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -45,7 +44,7 @@ private SolrjConverters() { abstract static class DocumentBinderConverter { protected final DocumentObjectBinder documentObjectBinder; - public DocumentBinderConverter(@Nullable DocumentObjectBinder binder) { + public DocumentBinderConverter(DocumentObjectBinder binder) { this.documentObjectBinder = binder != null ? binder : new DocumentObjectBinder(); } @@ -57,15 +56,14 @@ public DocumentBinderConverter(@Nullable DocumentObjectBinder binder) { * @author Christoph Strobl */ @WritingConverter - public static class ObjectToSolrInputDocumentConverter extends DocumentBinderConverter - implements Converter { + public static class ObjectToSolrInputDocumentConverter extends DocumentBinderConverter implements Converter { public ObjectToSolrInputDocumentConverter(DocumentObjectBinder binder) { super(binder); } @Override - public SolrInputDocument convert(@Nullable Object source) { + public SolrInputDocument convert(Object source) { if (source == null) { return null; } @@ -78,6 +76,7 @@ public SolrInputDocument convert(@Nullable Object source) { * Converts any {@link Update} to {@link SolrInputDocument} for atomic update. * * @author Christoph Strobl + * */ @WritingConverter public static class UpdateToSolrInputDocumentConverter implements Converter { @@ -89,7 +88,7 @@ public UpdateToSolrInputDocumentConverter() { } @Override - public SolrInputDocument convert(@Nullable Update source) { + public SolrInputDocument convert(Update source) { if (source == null) { return null; } @@ -103,7 +102,7 @@ public SolrInputDocument convert(@Nullable Update source) { } for (UpdateField field : source.getUpdates()) { - HashMap mapValue = new HashMap<>(1); + HashMap mapValue = new HashMap(1); mapValue.put(field.getAction().getSolrOperation(), getUpdateValue(field)); solrInputDocument.addField(field.getName(), mapValue); } @@ -111,10 +110,9 @@ public SolrInputDocument convert(@Nullable Update source) { return solrInputDocument; } - @Nullable private Object getUpdateValue(ValueHoldingField field) { - // Solr removes all values from document in case of empty colleciton - // therefore those values have to be set to null. + //Solr removes all values from document in case of empty colleciton + //therefore those values have to be set to null. if (field.getValue() instanceof Collection) { if (((Collection) field.getValue()).isEmpty()) { return null; @@ -130,11 +128,11 @@ private Object getUpdateValue(ValueHoldingField field) { * Convert any {@link SolrDocument} to object of given {@link Class} using {@link DocumentObjectBinder} * * @author Christoph Strobl + * * @param */ @ReadingConverter - public static class SolrInputDocumentToObjectConverter extends DocumentBinderConverter - implements Converter, T> { + public static class SolrInputDocumentToObjectConverter extends DocumentBinderConverter implements Converter, T> { private Class clazz; @@ -152,9 +150,9 @@ public T convert(Map source) { if (source == null) { return null; } - SolrDocument document = new SolrDocument(); document.putAll(source); + if (source instanceof SolrDocument && ((SolrDocument) source).hasChildDocuments()) { document.addChildDocuments(((SolrDocument) source).getChildDocuments()); } diff --git a/src/main/java/org/springframework/data/solr/core/convert/package-info.java b/src/main/java/org/springframework/data/solr/core/convert/package-info.java deleted file mode 100644 index 831e659..0000000 --- a/src/main/java/org/springframework/data/solr/core/convert/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * All the {@link org.springframework.core.convert.converter.Converter}s go here. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.core.convert; diff --git a/src/main/java/org/springframework/data/solr/core/geo/GeoConverters.java b/src/main/java/org/springframework/data/solr/core/geo/GeoConverters.java index e049d2d..73744f7 100644 --- a/src/main/java/org/springframework/data/solr/core/geo/GeoConverters.java +++ b/src/main/java/org/springframework/data/solr/core/geo/GeoConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -20,7 +20,6 @@ import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; import org.springframework.data.geo.Metrics; -import org.springframework.util.Assert; /** * @author Christoph Strobl @@ -36,7 +35,9 @@ public enum Point2DToStringConverter implements Converter, SolrPersistentProperty> { +public class SimpleSolrMappingContext extends + AbstractMappingContext, SolrPersistentProperty> { public SimpleSolrMappingContext() { this(null); } - public SimpleSolrMappingContext(@Nullable SolrPersistentEntitySchemaCreator schemaCreator) { + public SimpleSolrMappingContext(SolrPersistentEntitySchemaCreator schemaCreator) { if (schemaCreator != null) { setApplicationEventPublisher(new SolrMappingEventPublisher(schemaCreator)); } @@ -42,13 +43,13 @@ public SimpleSolrMappingContext(@Nullable SolrPersistentEntitySchemaCreator sche @Override protected SimpleSolrPersistentEntity createPersistentEntity(TypeInformation typeInformation) { - return new SimpleSolrPersistentEntity<>(typeInformation); + return new SimpleSolrPersistentEntity(typeInformation); } @Override - protected SolrPersistentProperty createPersistentProperty(Property property, SimpleSolrPersistentEntity owner, - SimpleTypeHolder simpleTypeHolder) { - return new SimpleSolrPersistentProperty(property, owner, simpleTypeHolder); + protected SolrPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, + SimpleSolrPersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { + return new SimpleSolrPersistentProperty(field, descriptor, owner, simpleTypeHolder); } } diff --git a/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntity.java b/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntity.java index 731af25..dd5535e 100644 --- a/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntity.java +++ b/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntity.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -17,43 +17,46 @@ import java.util.Locale; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.expression.BeanFactoryAccessor; import org.springframework.context.expression.BeanFactoryResolver; -import org.springframework.data.mapping.MappingException; +import org.springframework.data.annotation.Reference; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PropertyHandler; import org.springframework.data.mapping.model.BasicPersistentEntity; +import org.springframework.data.mapping.model.MappingException; import org.springframework.data.solr.repository.Score; import org.springframework.data.util.TypeInformation; import org.springframework.expression.spel.support.StandardEvaluationContext; -import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; /** * Solr specific {@link PersistentEntity} implementation holding eg. name of solr core. - * + * * @param * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ public class SimpleSolrPersistentEntity extends BasicPersistentEntity implements SolrPersistentEntity, ApplicationContextAware { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSolrPersistentEntity.class); + private final TypeInformation typeInformation; private final StandardEvaluationContext context; - private String collectionName; - private @Nullable Float boost; + private String solrCoreName; + private Float boost; public SimpleSolrPersistentEntity(TypeInformation typeInformation) { super(typeInformation); this.context = new StandardEvaluationContext(); this.typeInformation = typeInformation; - this.collectionName = derivateSolrCollectionName(); + this.solrCoreName = derivateSolrCoreName(); this.boost = derivateDocumentBoost(); } @@ -69,16 +72,18 @@ public void setApplicationContext(ApplicationContext applicationContext) throws context.setRootObject(applicationContext); } - private String derivateSolrCollectionName() { + private String derivateSolrCoreName() { + String derivativeSolrCoreName = this.typeInformation.getType().getSimpleName().toLowerCase(Locale.ENGLISH); SolrDocument solrDocument = findAnnotation(SolrDocument.class); - if (solrDocument != null && StringUtils.hasText(solrDocument.solrCoreName())) { - return solrDocument.collection(); + if (solrDocument != null) { + if (StringUtils.hasText(solrDocument.solrCoreName())) { + derivativeSolrCoreName = solrDocument.solrCoreName(); + } } - return this.typeInformation.getType().getSimpleName().toLowerCase(Locale.ENGLISH); + return derivativeSolrCoreName; } - @Nullable private Float derivateDocumentBoost() { SolrDocument solrDocument = findAnnotation(SolrDocument.class); @@ -90,11 +95,11 @@ private Float derivateDocumentBoost() { /* * (non-Javadoc) - * @see org.springframework.data.solr.core.mapping.SolrPersistentEntity#getCollectionName() + * @see org.springframework.data.solr.core.mapping.SolrPersistentEntity#getSolrCoreName() */ @Override - public String getCollectionName() { - return this.collectionName; + public String getSolrCoreName() { + return this.solrCoreName; } /* @@ -110,7 +115,6 @@ public boolean isBoosted() { * (non-Javadoc) * @see org.springframework.data.solr.core.mapping.SolrPersistentEntity#getBoost() */ - @Nullable @Override public Float getBoost() { return boost; @@ -129,7 +133,6 @@ public boolean hasScoreProperty() { * (non-Javadoc) * @see org.springframework.data.solr.core.mapping.SolrPersistentEntity#getScoreProperty() */ - @Nullable @Override public SolrPersistentProperty getScoreProperty() { return getPersistentProperty(Score.class); @@ -145,6 +148,7 @@ public void verify() { super.verify(); verifyScoreFieldUniqueness(); verifyDynamicPropertyMapping(); + verifyAssociations(); } private void verifyScoreFieldUniqueness() { @@ -155,17 +159,21 @@ private void verifyDynamicPropertyMapping() { doWithProperties(DynamicFieldMappingHandler.INSTANCE); } + private void verifyAssociations() { + doWithProperties(AssociationFieldMappingHandler.INSTANCE); + } + /** * Handler to inspect {@link SolrPersistentProperty} instances and check that max one can be mapped as {@link Score} * property. - * + * * @author Christpoh Strobl * @since 1.4 */ private static class ScoreFieldUniquenessHandler implements PropertyHandler { private static final String AMBIGUOUS_FIELD_MAPPING = "Ambiguous score field mapping detected! Both %s and %s marked as target for score value. Disambiguate using @Score annotation!"; - private @Nullable SolrPersistentProperty scoreProperty; + private SolrPersistentProperty scoreProperty; /* * (non-Javadoc) @@ -191,11 +199,11 @@ private void assertUniqueness(SolrPersistentProperty property) { /** * Handler to inspect {@link SolrPersistentProperty} instances and check usage of {@link Dynamic}. - * + * * @author Christoph Strobl * @since 1.5 */ - private enum DynamicFieldMappingHandler implements PropertyHandler { + private static enum DynamicFieldMappingHandler implements PropertyHandler { INSTANCE; @@ -220,4 +228,26 @@ public void doWithPersistentProperty(SolrPersistentProperty property) { } } + /** + * Handler to inspect {@link SolrPersistentProperty} instances and check usage of {@link Dynamic}. + * + * @author Christoph Strobl + * @since 2.1 + */ + private static enum AssociationFieldMappingHandler implements PropertyHandler { + + INSTANCE; + + @Override + public void doWithPersistentProperty(SolrPersistentProperty property) { + + if (property.isAnnotationPresent(Reference.class)) { + + LOGGER.warn( + "Associations via @Reference are not supported and will be ignored by Spring Data for Apache Solr. Please check property '%s' in %s", + property.getName(), property.getOwner().getName()); + } + } + } + } diff --git a/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentProperty.java b/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentProperty.java index 58d4b01..8e575ec 100644 --- a/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentProperty.java +++ b/src/main/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,37 +15,35 @@ */ package org.springframework.data.solr.core.mapping; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.apache.solr.client.solrj.beans.Field; import org.springframework.data.mapping.Association; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty; -import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.repository.Score; -import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * Solr specific {@link org.springframework.data.mapping.PersistentProperty} implementation processing taking * {@link org.apache.solr.client.solrj.beans.Field} into account - * + * * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ -public class SimpleSolrPersistentProperty extends AnnotationBasedPersistentProperty - implements SolrPersistentProperty { +public class SimpleSolrPersistentProperty extends AnnotationBasedPersistentProperty implements + SolrPersistentProperty { private static final String SOLRJ_FIELD_ANNOTATION_DEFAULT_VALUE = "#default"; - private static final Set> SUPPORTED_ID_TYPES = new HashSet<>(3); - private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet<>(1); + private static final Set> SUPPORTED_ID_TYPES = new HashSet>(3); + private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet(1); static { SUPPORTED_ID_TYPES.add(String.class); @@ -55,9 +53,9 @@ public class SimpleSolrPersistentProperty extends AnnotationBasedPersistentPrope SUPPORTED_ID_PROPERTY_NAMES.add("id"); } - public SimpleSolrPersistentProperty(Property property, PersistentEntity owner, - SimpleTypeHolder simpleTypeHolder) { - super(property, owner, simpleTypeHolder); + public SimpleSolrPersistentProperty(Field field, PropertyDescriptor propertyDescriptor, + PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { + super(field, propertyDescriptor, owner, simpleTypeHolder); } @Override @@ -67,7 +65,7 @@ public String getFieldName() { if (StringUtils.hasText(fieldName) && !SOLRJ_FIELD_ANNOTATION_DEFAULT_VALUE.equals(fieldName)) { return fieldName; } - return getName(); + return this.name; } private String readAnnotatedFieldName() { @@ -76,12 +74,9 @@ private String readAnnotatedFieldName() { fieldName = findAnnotation(org.apache.solr.client.solrj.beans.Field.class).value(); } else if (isAnnotationPresent(Indexed.class)) { Indexed indexedAnnotation = findAnnotation(Indexed.class); - - if (indexedAnnotation != null) { - fieldName = indexedAnnotation.value(); - if (!StringUtils.hasText(fieldName)) { - fieldName = indexedAnnotation.name(); - } + fieldName = indexedAnnotation.value(); + if (!StringUtils.hasText(fieldName)) { + fieldName = indexedAnnotation.name(); } } return fieldName; @@ -108,13 +103,22 @@ public boolean isReadonly() { return false; } + @Override + public boolean isAssociation() { + return false; + } + /* * (non-Javadoc) * @see org.springframework.data.mapping.model.AnnotationBasedPersistentProperty#isIdProperty() */ @Override public boolean isIdProperty() { - return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName()); + if (super.isIdProperty()) { + return true; + } + + return SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName()); } /* @@ -137,12 +141,10 @@ public boolean containsWildcard() { : false; } - @Nullable private org.apache.solr.client.solrj.beans.Field getFieldAnnotation() { return findAnnotation(org.apache.solr.client.solrj.beans.Field.class); } - @Nullable private Indexed getIndexAnnotation() { return findAnnotation(Indexed.class); } @@ -162,7 +164,6 @@ public boolean isBoosted() { * (non-Javadoc) * @see org.springframework.data.solr.core.mapping.SolrPersistentProperty#getBoost() */ - @Nullable @Override public Float getBoost() { @@ -219,10 +220,11 @@ public boolean isMultiValued() { */ @Override public String getSolrTypeName() { - Indexed indexedAnnotation = getIndexAnnotation(); - if (indexedAnnotation != null && StringUtils.hasText(indexedAnnotation.type())) { - return indexedAnnotation.type(); + if (indexedAnnotation != null) { + if (StringUtils.hasText(indexedAnnotation.type())) { + return indexedAnnotation.type(); + } } return getActualType().getSimpleName().toLowerCase(); } @@ -235,8 +237,10 @@ public String getSolrTypeName() { public Object getDefaultValue() { Indexed indexedAnnotation = getIndexAnnotation(); - if (indexedAnnotation != null && StringUtils.hasText(indexedAnnotation.defaultValue())) { - return indexedAnnotation.defaultValue(); + if (indexedAnnotation != null) { + if (StringUtils.hasText(indexedAnnotation.defaultValue())) { + return indexedAnnotation.defaultValue(); + } } return null; } @@ -248,10 +252,11 @@ public Object getDefaultValue() { @SuppressWarnings("unchecked") @Override public Collection getCopyFields() { - Indexed indexedAnnotation = getIndexAnnotation(); - if (indexedAnnotation != null && indexedAnnotation.copyTo().length > 0) { - return CollectionUtils.arrayToList(indexedAnnotation.copyTo()); + if (indexedAnnotation != null) { + if (indexedAnnotation.copyTo().length > 0) { + return CollectionUtils.arrayToList(indexedAnnotation.copyTo()); + } } return Collections.emptyList(); } @@ -285,8 +290,7 @@ public boolean isScoreProperty() { return findAnnotation(Score.class) != null; } - /* - * (non-Javadoc) + /* (non-Javadoc) * @see org.springframework.data.solr.core.mapping.SolrPersistentProperty#isDynamicProperty() */ @Override @@ -294,19 +298,4 @@ public boolean isDynamicProperty() { return findAnnotation(Dynamic.class) != null; } - /* - * (non-Javadoc) - * @see org.springframework.data.solr.core.mapping.SolrPersistentProperty#isChildProperty() - */ - @Override - public boolean isChildProperty() { - - Field fieldAnnotation = getFieldAnnotation(); - - if (fieldAnnotation != null && fieldAnnotation.child()) { - return true; - } - - return findAnnotation(ChildDocument.class) != null; - } } diff --git a/src/main/java/org/springframework/data/solr/core/mapping/SolrDocument.java b/src/main/java/org/springframework/data/solr/core/mapping/SolrDocument.java index 749abe2..0c72462 100644 --- a/src/main/java/org/springframework/data/solr/core/mapping/SolrDocument.java +++ b/src/main/java/org/springframework/data/solr/core/mapping/SolrDocument.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2014 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. @@ -21,8 +21,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.apache.solr.common.params.SolrParams; -import org.springframework.core.annotation.AliasFor; import org.springframework.data.annotation.Persistent; /** @@ -38,10 +36,7 @@ * Defines the {@literal collectionname} the document is persisted in. * * @return - * @deprecated since 3.0. Please use {@link #collection()}. */ - @Deprecated - @AliasFor(attribute = "collection") String solrCoreName() default ""; /** @@ -52,11 +47,4 @@ */ float boost() default Float.NaN; - /** - * @return - * @since 3.0 - */ - @AliasFor(attribute = "solrCoreName") - String collection() default ""; - } diff --git a/src/main/java/org/springframework/data/solr/core/mapping/SolrPersistentEntity.java b/src/main/java/org/springframework/data/solr/core/mapping/SolrPersistentEntity.java index 60b9399..3c3edf1 100644 --- a/src/main/java/org/springframework/data/solr/core/mapping/SolrPersistentEntity.java +++ b/src/main/java/org/springframework/data/solr/core/mapping/SolrPersistentEntity.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -16,22 +16,20 @@ package org.springframework.data.solr.core.mapping; import org.springframework.data.mapping.PersistentEntity; -import org.springframework.lang.Nullable; /** * @param * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ public interface SolrPersistentEntity extends PersistentEntity { /** * Get the core's name for this entity. - * + * * @return */ - String getCollectionName(); + String getSolrCoreName(); /** * @return true if this entity is boosted @@ -41,13 +39,12 @@ public interface SolrPersistentEntity extends PersistentEntity extends PersistentEntitypotential score property of the owning {@link PersistentEntity}. This * method is mainly used by {@link PersistentEntity} implementation to discover score property candidates on - * {@link PersistentEntity} creation you should rather call to determine whether the current property is the score + * {@link PersistentEntity} creation you should rather call + * {@link PersistentEntity#isScoreProperty(PersistentProperty)} to determine whether the current property is the score * property of that {@link PersistentEntity} under consideration. * * @return @@ -128,14 +124,7 @@ public interface SolrPersistentProperty extends PersistentProperty { + public enum PropertyToFieldNameConverter implements Converter { INSTANCE; diff --git a/src/main/java/org/springframework/data/solr/core/mapping/SolrSimpleTypes.java b/src/main/java/org/springframework/data/solr/core/mapping/SolrSimpleTypes.java index 5193c84..30bc41c 100644 --- a/src/main/java/org/springframework/data/solr/core/mapping/SolrSimpleTypes.java +++ b/src/main/java/org/springframework/data/solr/core/mapping/SolrSimpleTypes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -35,11 +35,11 @@ private SolrSimpleTypes() { } static { - Set> classes = new HashSet<>(); + Set> classes = new HashSet>(); classes.add(BigInteger.class); classes.add(SolrInputDocument.class); - Set> simpleTypes = new HashSet<>(); + Set> simpleTypes = new HashSet>(); SOLR_SIMPLE_TYPES = Collections.unmodifiableSet(simpleTypes); } diff --git a/src/main/java/org/springframework/data/solr/core/mapping/package-info.java b/src/main/java/org/springframework/data/solr/core/mapping/package-info.java deleted file mode 100644 index 2237dcc..0000000 --- a/src/main/java/org/springframework/data/solr/core/mapping/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * All the mapping things! - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.core.mapping; diff --git a/src/main/java/org/springframework/data/solr/core/package-info.java b/src/main/java/org/springframework/data/solr/core/package-info.java index 6c104f4..d989ac9 100644 --- a/src/main/java/org/springframework/data/solr/core/package-info.java +++ b/src/main/java/org/springframework/data/solr/core/package-info.java @@ -2,6 +2,4 @@ * Provides the classes necessary for Solr support. * {@link org.springframework.data.solr.core.SolrTemplate} is the main entry point for accessing solr. */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields package org.springframework.data.solr.core; \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQuery.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQuery.java index 780aacf..66f7dcb 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,7 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -26,9 +25,9 @@ */ class AbstractQuery { - private @Nullable Criteria criteria; - private @Nullable Join join; - private @Nullable String requestHandler; + private Criteria criteria; + private Join join; + private String requestHandler; AbstractQuery() {} @@ -39,12 +38,11 @@ class AbstractQuery { /** * Add an criteria to the query. The criteria will be connected using 'AND'. * - * @param criteria must not be {@literal null}. + * @param criteria * @return */ @SuppressWarnings("unchecked") public final T addCriteria(Criteria criteria) { - Assert.notNull(criteria, "Cannot add null criteria."); if (this.criteria == null) { @@ -65,13 +63,15 @@ public final T addCriteria(Criteria criteria) { /** * @return null if not set */ - @Nullable public Criteria getCriteria() { return this.criteria; } /** * Set values for join {@code !join from=inner_id to=outer_id} + * + * @param from + * @param to */ public void setJoin(Join join) { this.join = join; @@ -80,12 +80,10 @@ public void setJoin(Join join) { /** * @return null if not set */ - @Nullable public Join getJoin() { return join; } - @Nullable public String getRequestHandler() { return requestHandler; } diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java index 2e34f9f..11c13a9 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -19,8 +19,8 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; /** * General purpose {@link Query} abstract decorator. @@ -44,7 +44,6 @@ public T addCriteria(Criteria criteria) { return this.query.addCriteria(criteria); } - @Nullable @Override public Criteria getCriteria() { return this.query.getCriteria(); @@ -111,23 +110,15 @@ public T addSort(Sort sort) { return this.query.addSort(sort); } - @Nullable @Override public Sort getSort() { return this.query.getSort(); } - @Nullable @Override public Integer getTimeAllowed() { return this.query.getTimeAllowed(); } - - @Nullable - @Override - public String getRqqValue() { - return this.query.getRqqValue(); - } @Override public void setDefaultOperator(Operator operator) { @@ -160,14 +151,9 @@ public void setRequestHandler(String requestHandler) { } @Override - public T setOffset(Long offset) { + public T setOffset(Integer offset) { return this.query.setOffset(offset); } - - @Override - public T setReRank(String rqqValue) { - return this.query.setReRank(rqqValue); - } @Override public T setRows(Integer rows) { @@ -175,7 +161,7 @@ public T setRows(Integer rows) { } @Override - public Long getOffset() { + public Integer getOffset() { return this.query.getOffset(); } @@ -230,4 +216,14 @@ public SpellcheckOptions getSpellcheckOptions() { return query.getSpellcheckOptions(); } + /** + * Get the {@link Class} of the originally decorated query. + * + * @return never {@literal null}. + * @since 2.1 + */ + public Class getQueryType() { + return ClassUtils.getUserClass(query.getClass()); + } + } diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractValueHoldingField.java b/src/main/java/org/springframework/data/solr/core/query/AbstractValueHoldingField.java index 93baa8d..820d85e 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractValueHoldingField.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractValueHoldingField.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Base implementation of {@link ValueHoldingField}
* @@ -24,7 +22,7 @@ */ class AbstractValueHoldingField extends SimpleField implements ValueHoldingField { - private @Nullable Object value; + private Object value; protected AbstractValueHoldingField(String fieldName) { super(fieldName); @@ -35,13 +33,12 @@ protected AbstractValueHoldingField(String fieldName, Object fieldValue) { this.value = fieldValue; } - @Nullable @Override public Object getValue() { return this.value; } - public void setValue(@Nullable Object value) { + public void setValue(Object value) { this.value = value; } diff --git a/src/main/java/org/springframework/data/solr/core/query/AnyCriteria.java b/src/main/java/org/springframework/data/solr/core/query/AnyCriteria.java index 49d50af..378c9a9 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AnyCriteria.java +++ b/src/main/java/org/springframework/data/solr/core/query/AnyCriteria.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -46,7 +46,11 @@ public String toString() { @Override public boolean equals(Object obj) { - return obj instanceof AnyCriteria && ObjectUtils.nullSafeEquals(QUERY_STRING, ((AnyCriteria) obj).getQueryString()); + if (obj instanceof AnyCriteria) { + return ObjectUtils.nullSafeEquals(QUERY_STRING, ((AnyCriteria) obj).getQueryString()); + } + + return false; } @Override diff --git a/src/main/java/org/springframework/data/solr/core/query/Criteria.java b/src/main/java/org/springframework/data/solr/core/query/Criteria.java index 92dc295..a9602ce 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Criteria.java +++ b/src/main/java/org/springframework/data/solr/core/query/Criteria.java @@ -27,7 +27,6 @@ import org.springframework.data.geo.Circle; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -43,10 +42,10 @@ public class Criteria extends Node { public static final String WILDCARD = "*"; public static final String CRITERIA_VALUE_SEPERATOR = " "; - private @Nullable Field field; + private Field field; private float boost = Float.NaN; - private Set predicates = new LinkedHashSet<>(); + private Set predicates = new LinkedHashSet(); public Criteria() {} @@ -118,7 +117,7 @@ public static Criteria where(Field field) { * @param o * @return */ - public Criteria is(@Nullable Object o) { + public Criteria is(Object o) { if (o == null) { return isNull(); } @@ -398,7 +397,7 @@ public Criteria boost(float boost) { * @param upperBound * @return */ - public Criteria between(@Nullable Object lowerBound, @Nullable Object upperBound) { + public Criteria between(Object lowerBound, Object upperBound) { return between(lowerBound, upperBound, true, true); } @@ -411,9 +410,9 @@ public Criteria between(@Nullable Object lowerBound, @Nullable Object upperBound * @param includeUppderBound * @return */ - public Criteria between(@Nullable Object lowerBound, @Nullable Object upperBound, boolean includeLowerBound, boolean includeUppderBound) { - predicates.add(new Predicate(OperationKey.BETWEEN, - new Object[] { lowerBound, upperBound, includeLowerBound, includeUppderBound })); + public Criteria between(Object lowerBound, Object upperBound, boolean includeLowerBound, boolean includeUppderBound) { + predicates.add(new Predicate(OperationKey.BETWEEN, new Object[] { lowerBound, upperBound, includeLowerBound, + includeUppderBound })); return this; } @@ -497,11 +496,11 @@ public Criteria in(Iterable values) { * @param distance * @return */ - public Criteria within(Point location, @Nullable Distance distance) { + public Criteria within(Point location, Distance distance) { Assert.notNull(location, "Location must not be null!"); assertPositiveDistanceValue(distance); - predicates.add( - new Predicate(OperationKey.WITHIN, new Object[] { location, distance != null ? distance : new Distance(0) })); + predicates.add(new Predicate(OperationKey.WITHIN, new Object[] { location, + distance != null ? distance : new Distance(0) })); return this; } @@ -539,12 +538,12 @@ public Criteria near(Box box) { * @throws IllegalArgumentException if location is null * @throws InvalidDataAccessApiUsageException if distance is negative */ - public Criteria near(Point location, @Nullable Distance distance) { + public Criteria near(Point location, Distance distance) { Assert.notNull(location, "Location must not be 'null' for near criteria."); assertPositiveDistanceValue(distance); - predicates.add( - new Predicate(OperationKey.NEAR, new Object[] { location, distance != null ? distance : new Distance(0) })); + predicates.add(new Predicate(OperationKey.NEAR, new Object[] { location, + distance != null ? distance : new Distance(0) })); return this; } @@ -581,7 +580,6 @@ public Criteria function(Function function) { * * @return null if not set */ - @Nullable public Field getField() { return this.field; } @@ -609,7 +607,7 @@ public Set getPredicates() { return Collections.unmodifiableSet(this.predicates); } - private void assertPositiveDistanceValue(@Nullable Distance distance) { + private void assertPositiveDistanceValue(Distance distance) { if (distance != null && distance.getValue() < 0) { throw new InvalidDataAccessApiUsageException("distance must not be negative."); } @@ -624,9 +622,9 @@ private void assertNoBlankInWildcardedQuery(String searchString, boolean leading private void assertValuesPresent(Object... values) { if (values.length == 0 || (values.length > 1 && values[1] instanceof Collection)) { - throw new InvalidDataAccessApiUsageException( - "At least one element " + (values.length > 0 ? ("of argument of type " + values[1].getClass().getName()) : "") - + " has to be present."); + throw new InvalidDataAccessApiUsageException("At least one element " + + (values.length > 0 ? ("of argument of type " + values[1].getClass().getName()) : "") + + " has to be present."); } } @@ -654,12 +652,12 @@ public String toString() { public enum OperationKey { EQUALS("$equals"), CONTAINS("$contains"), STARTS_WITH("$startsWith"), ENDS_WITH("$endsWith"), EXPRESSION( - "$expression"), BETWEEN( - "$between"), NEAR("$near"), WITHIN("$within"), FUZZY("$fuzzy"), SLOPPY("$sloppy"), FUNCTION("$function"); + "$expression"), BETWEEN("$between"), NEAR("$near"), WITHIN("$within"), FUZZY("$fuzzy"), SLOPPY("$sloppy"), FUNCTION( + "$function"); private final String key; - OperationKey(String key) { + private OperationKey(String key) { this.key = key; } @@ -692,7 +690,6 @@ public Predicate(String key, Object value) { /** * @return null if not set */ - @Nullable public String getKey() { return key; } @@ -709,7 +706,6 @@ public void setKey(String key) { /** * @return null if not set */ - @Nullable public Object getValue() { return value; } diff --git a/src/main/java/org/springframework/data/solr/core/query/Crotch.java b/src/main/java/org/springframework/data/solr/core/query/Crotch.java index 5026b7e..1a44cdd 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Crotch.java +++ b/src/main/java/org/springframework/data/solr/core/query/Crotch.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -23,7 +23,6 @@ import org.springframework.data.geo.Box; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; -import org.springframework.lang.Nullable; /** * @author Christoph Strobl @@ -31,8 +30,8 @@ */ public class Crotch extends Criteria { - private List siblings = new ArrayList<>(); - private @Nullable Node mostRecentSibling = null; + private List siblings = new ArrayList(); + private Node mostRecentSibling = null; Crotch() {} @@ -45,7 +44,7 @@ public Field getField() { } @Override - public Crotch is(@Nullable Object o) { + public Crotch is(Object o) { mostRecentSibling.is(o); return this; } @@ -177,13 +176,13 @@ public Crotch expression(String nativeSolrQueryExpression) { } @Override - public Crotch between(@Nullable Object lowerBound, @Nullable Object upperBound) { + public Crotch between(Object lowerBound, Object upperBound) { mostRecentSibling.between(lowerBound, upperBound); return this; } @Override - public Crotch between(@Nullable Object lowerBound, @Nullable Object upperBound, boolean includeLowerBound, boolean includeUpperBound) { + public Crotch between(Object lowerBound, Object upperBound, boolean includeLowerBound, boolean includeUpperBound) { mostRecentSibling.between(lowerBound, upperBound, includeLowerBound, includeUpperBound); return this; } @@ -225,7 +224,7 @@ public Crotch in(Iterable values) { } @Override - public Crotch within(Point location, @Nullable Distance distance) { + public Crotch within(Point location, Distance distance) { mostRecentSibling.within(location, distance); return this; } @@ -237,7 +236,7 @@ public Crotch near(Box box) { } @Override - public Crotch near(Point location, @Nullable Distance distance) { + public Crotch near(Point location, Distance distance) { mostRecentSibling.near(location, distance); return this; } diff --git a/src/main/java/org/springframework/data/solr/core/query/CurrencyFunction.java b/src/main/java/org/springframework/data/solr/core/query/CurrencyFunction.java index 0a83dd5..0b4ff57 100644 --- a/src/main/java/org/springframework/data/solr/core/query/CurrencyFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/CurrencyFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,9 +15,8 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -32,7 +31,7 @@ public class CurrencyFunction extends AbstractFunction { private static final String OPERATION = "currency"; private CurrencyFunction(String fieldname) { - super(Collections.singletonList(fieldname)); + super(Arrays.asList(fieldname)); } /** @@ -63,8 +62,7 @@ public static CurrencyFunction currency(Field field) { * @param currencyCode * @return */ - public static CurrencyFunction currency(Field field, @Nullable String currencyCode) { - + public static CurrencyFunction currency(Field field, String currencyCode) { Assert.notNull(field, "Field for currency function must not be 'null'."); return currency(field.getName(), currencyCode); @@ -78,7 +76,7 @@ public static CurrencyFunction currency(Field field, @Nullable String currencyCo * @param currencyCode * @return */ - public static CurrencyFunction currency(String fieldname, @Nullable String currencyCode) { + public static CurrencyFunction currency(String fieldname, String currencyCode) { Assert.hasText(fieldname, "Fieldname for currency function must not be 'empty'."); CurrencyFunction function = new CurrencyFunction(fieldname); diff --git a/src/main/java/org/springframework/data/solr/core/query/DistanceField.java b/src/main/java/org/springframework/data/solr/core/query/DistanceField.java index 5fa905f..1c18810 100644 --- a/src/main/java/org/springframework/data/solr/core/query/DistanceField.java +++ b/src/main/java/org/springframework/data/solr/core/query/DistanceField.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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. @@ -16,7 +16,6 @@ package org.springframework.data.solr.core.query; import org.springframework.data.geo.Point; -import org.springframework.lang.Nullable; /** * Implementation of {@link CalculatedField} for {@code geodist} @@ -30,7 +29,7 @@ public DistanceField(String geoFieldName, Point location) { this(null, geoFieldName, location); } - public DistanceField(@Nullable String alias, String geoFieldName, Point location) { + public DistanceField(String alias, String geoFieldName, Point location) { super(alias, GeoDistanceFunction.distanceFrom(geoFieldName).to(location)); } diff --git a/src/main/java/org/springframework/data/solr/core/query/DistanceFunction.java b/src/main/java/org/springframework/data/solr/core/query/DistanceFunction.java index 52a4359..cb51342 100644 --- a/src/main/java/org/springframework/data/solr/core/query/DistanceFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/DistanceFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.data.solr.core.geo.Point; import org.springframework.util.Assert; @@ -25,6 +25,7 @@ * * @author Christoph Strobl * @since 1.1 + * */ public class DistanceFunction extends AbstractFunction { @@ -35,7 +36,7 @@ public enum Power { private String value; - Power(String value) { + private Power(String value) { this.value = value; } @@ -46,7 +47,7 @@ public String getValue() { } private DistanceFunction(Power power) { - super(Collections.singletonList(power.getValue())); + super(Arrays.asList(power.getValue())); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/ExistsFunction.java b/src/main/java/org/springframework/data/solr/core/query/ExistsFunction.java index a6fb0d3..6616369 100644 --- a/src/main/java/org/springframework/data/solr/core/query/ExistsFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/ExistsFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.util.Assert; @@ -30,7 +30,7 @@ public class ExistsFunction extends AbstractFunction { private static final String OPERATION = "exists"; private ExistsFunction(Object candidate) { - super(Collections.singletonList(candidate)); + super(Arrays.asList(candidate)); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/FacetOptions.java b/src/main/java/org/springframework/data/solr/core/query/FacetOptions.java index ad17c73..43756e1 100644 --- a/src/main/java/org/springframework/data/solr/core/query/FacetOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/FacetOptions.java @@ -26,7 +26,6 @@ import org.apache.solr.common.params.FacetParams.FacetRangeInclude; import org.apache.solr.common.params.FacetParams.FacetRangeOther; import org.springframework.data.domain.Pageable; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -46,16 +45,17 @@ public enum FacetSort { COUNT, INDEX } - private List facetOnFields = new ArrayList<>(1); - private List facetOnPivotFields = new ArrayList<>(0); - private List> facetRangeOnFields = new ArrayList<>(1); - private List facetQueries = new ArrayList<>(0); + private List facetOnFields = new ArrayList(1); + private List facetOnPivotFields = new ArrayList(0); + private List> facetRangeOnFields = new ArrayList>( + 1); + private List facetQueries = new ArrayList(0); private int facetMinCount = DEFAULT_FACET_MIN_COUNT; private int facetLimit = DEFAULT_FACET_LIMIT; - private @Nullable String facetPrefix; + private String facetPrefix; private FacetSort facetSort = DEFAULT_FACET_SORT; - private @Nullable Pageable pageable; + private Pageable pageable; public FacetOptions() {} @@ -75,6 +75,8 @@ public FacetOptions(String... fieldnames) { /** * Creates new instance faceting on given fields + * + * @param fieldnames */ public FacetOptions(Field... fields) { Assert.notNull(fields, "Fields must not be null."); @@ -157,6 +159,7 @@ public final FacetOptions addFacetOnPivot(Field... fields) { } /** + * @param fieldName * @return */ public final FacetOptions addFacetOnPivot(String... fieldnames) { @@ -311,7 +314,6 @@ public FacetOptions setPageable(Pageable pageable) { * * @return */ - @Nullable public String getFacetPrefix() { return facetPrefix; } @@ -369,7 +371,7 @@ public boolean hasFacetPrefix() { @SuppressWarnings("unchecked") public Collection getFieldsWithParameters() { - List result = new ArrayList<>(); + List result = new ArrayList(); for (Field candidate : facetOnFields) { if (candidate instanceof FieldWithFacetParameters) { @@ -382,7 +384,7 @@ public Collection getFieldsWithParameters() { public static class FacetParameter extends QueryParameterImpl { - public FacetParameter(String parameter, @Nullable Object value) { + public FacetParameter(String parameter, Object value) { super(parameter, value); } @@ -390,7 +392,7 @@ public FacetParameter(String parameter, @Nullable Object value) { public static class FieldWithFacetParameters extends FieldWithQueryParameters { - private @Nullable FacetSort sort; + private FacetSort sort; public FieldWithFacetParameters(String name) { super(name); @@ -407,7 +409,6 @@ public FieldWithFacetParameters setPrefix(String prefix) { /** * @return null if not set */ - @Nullable public String getPrefix() { return getQueryParameterValue(FacetParams.FACET_PREFIX); } @@ -423,7 +424,6 @@ public FieldWithFacetParameters setSort(FacetSort sort) { /** * @return null if not set */ - @Nullable public FacetSort getSort() { return this.sort; } @@ -439,7 +439,6 @@ public FieldWithFacetParameters setLimit(Integer limit) { /** * @return null if not set */ - @Nullable public Integer getLimit() { return getQueryParameterValue(FacetParams.FACET_LIMIT); } @@ -455,7 +454,6 @@ public FieldWithFacetParameters setOffset(Integer offset) { /** * @return null if not set */ - @Nullable public Integer getOffset() { return getQueryParameterValue(FacetParams.FACET_OFFSET); } @@ -487,7 +485,6 @@ public FieldWithFacetParameters setMissing(Boolean missing) { /** * @return null if not set */ - @Nullable public Boolean getMissing() { return getQueryParameterValue(FacetParams.FACET_MISSING); } @@ -504,7 +501,6 @@ public FieldWithFacetParameters setMethod(String method) { /** * @return null if not set */ - @Nullable public String getMethod() { return getQueryParameterValue(FacetParams.FACET_METHOD); } @@ -515,11 +511,11 @@ public String getMethod() { * @param parameterName * @param value */ - public FieldWithFacetParameters addFacetParameter(String parameterName, @Nullable Object value) { + public FieldWithFacetParameters addFacetParameter(String parameterName, Object value) { return addFacetParameter(parameterName, value, false); } - protected FieldWithFacetParameters addFacetParameter(String parameterName, @Nullable Object value, + protected FieldWithFacetParameters addFacetParameter(String parameterName, Object value, boolean removeIfValueIsNull) { if (removeIfValueIsNull && value == null) { removeQueryParameter(parameterName); @@ -601,7 +597,6 @@ public T setHardEnd(Boolean rangeHardEnd) { * @return if hard end should be used, null will be returned if not set * @see FacetParams#FACET_RANGE_HARD_END */ - @Nullable public Boolean getHardEnd() { return getQueryParameterValue(FacetParams.FACET_RANGE_HARD_END); } @@ -626,7 +621,6 @@ public T setOther(FacetParams.FacetRangeOther rangeOther) { * @return null which other counts shall be added to the facet result * @see FacetParams.FACET_RANGE_OTHER */ - @Nullable public FacetRangeOther getOther() { return getQueryParameterValue(FacetParams.FACET_RANGE_OTHER); } @@ -651,7 +645,6 @@ public T setInclude(FacetParams.FacetRangeInclude rangeInclude) { * @return null if not set * @see FacetParams.FACET_RANGE_INCLUDE */ - @Nullable public FacetRangeInclude getInclude() { return getQueryParameterValue(FacetParams.FACET_RANGE_INCLUDE); } diff --git a/src/main/java/org/springframework/data/solr/core/query/FacetQuery.java b/src/main/java/org/springframework/data/solr/core/query/FacetQuery.java index e8bbbf4..7d97c49 100644 --- a/src/main/java/org/springframework/data/solr/core/query/FacetQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/FacetQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Query to be used for faceting. * @@ -35,7 +33,6 @@ public interface FacetQuery extends Query { /** * @return null if not set */ - @Nullable FacetOptions getFacetOptions(); /** diff --git a/src/main/java/org/springframework/data/solr/core/query/Field.java b/src/main/java/org/springframework/data/solr/core/query/Field.java index 8aed620..d4d685f 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Field.java +++ b/src/main/java/org/springframework/data/solr/core/query/Field.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,10 +15,8 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** - * Defines a Field that can be used within {@link Criteria}. + * Defines a Field that can be used within {@link Criteria}. * * @author Christoph Strobl */ @@ -29,7 +27,6 @@ public interface Field { * * @return */ - @Nullable String getName(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/FieldWithQueryParameters.java b/src/main/java/org/springframework/data/solr/core/query/FieldWithQueryParameters.java index dd4c502..7630d05 100644 --- a/src/main/java/org/springframework/data/solr/core/query/FieldWithQueryParameters.java +++ b/src/main/java/org/springframework/data/solr/core/query/FieldWithQueryParameters.java @@ -24,11 +24,12 @@ * Field that holds additional parameters to provide query hints to solr. * * @author Christoph Strobl + * * @param */ public class FieldWithQueryParameters extends SimpleField implements Iterable { - private final ParameterHolder parameterHolder = new ParameterHolder<>(); + private final ParameterHolder parameterHolder = new ParameterHolder(); /** * @param fieldname must not be null diff --git a/src/main/java/org/springframework/data/solr/core/query/GeoHashFunction.java b/src/main/java/org/springframework/data/solr/core/query/GeoHashFunction.java index bee63a4..45bc848 100644 --- a/src/main/java/org/springframework/data/solr/core/query/GeoHashFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/GeoHashFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.data.geo.Point; import org.springframework.util.Assert; @@ -31,7 +31,7 @@ public class GeoHashFunction extends AbstractFunction { private static final String OPERATION = "geohash"; private GeoHashFunction(Point location) { - super(Collections.singletonList(location)); + super(Arrays.asList(location)); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/GroupOptions.java b/src/main/java/org/springframework/data/solr/core/query/GroupOptions.java index 0c068d7..b4ba12d 100644 --- a/src/main/java/org/springframework/data/solr/core/query/GroupOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/GroupOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -21,14 +21,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Set of options that could be set for a {@link Query} in order to have grouped results. * * @author Francisco Spaeth - * @author Christoph Strobl * @since 1.4 */ public class GroupOptions { @@ -36,14 +34,14 @@ public class GroupOptions { int DEFAULT_GROUP_LIMIT = 1; int DEFAULT_CACHE_PERCENT = 0; - private List groupByFields = new ArrayList<>(0); - private List groupByFunctions = new ArrayList<>(0); - private List groupByQuery = new ArrayList<>(0); + private List groupByFields = new ArrayList(0); + private List groupByFunctions = new ArrayList(0); + private List groupByQuery = new ArrayList(0); - private @Nullable Integer offset = null; - private @Nullable Integer limit = null; + private Integer offset = null; + private Integer limit = null; - private @Nullable Sort sort; + private Sort sort; private boolean truncateFacets = false; private boolean groupFacets = false; @@ -137,7 +135,7 @@ public List getGroupByQueries() { * @param offset * @return */ - public GroupOptions setOffset(@Nullable Integer offset) { + public GroupOptions setOffset(Integer offset) { this.offset = offset == null ? null : Math.max(0, offset); return this; @@ -146,7 +144,6 @@ public GroupOptions setOffset(@Nullable Integer offset) { /** * @return initial offset of each group */ - @Nullable public Integer getOffset() { return offset; } @@ -154,7 +151,6 @@ public Integer getOffset() { /** * @return the number of rows to return for each group. */ - @Nullable public Integer getLimit() { return limit; } @@ -177,7 +173,7 @@ public GroupOptions setLimit(Integer limit) { * @param sort * @return */ - public GroupOptions addSort(@Nullable Sort sort) { + public GroupOptions addSort(Sort sort) { if (sort == null) { return this; @@ -195,7 +191,6 @@ public GroupOptions addSort(@Nullable Sort sort) { /** * @return sort instruction on how to sort elements within a single group. */ - @Nullable public Sort getSort() { return sort; } @@ -295,7 +290,6 @@ public boolean isGroupMain() { return groupMain; } - @Nullable public Pageable getPageRequest() { if (this.limit == null && this.offset == null) { diff --git a/src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java b/src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java index c7fe730..38ec0ce 100644 --- a/src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java @@ -21,7 +21,6 @@ import java.util.List; import org.apache.solr.common.params.HighlightParams; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -33,11 +32,17 @@ */ public class HighlightOptions { - public static final Field ALL_FIELDS = () -> Criteria.WILDCARD; + public static final Field ALL_FIELDS = new Field() { - private final ParameterHolder parameterHolder = new ParameterHolder<>(); - private @Nullable FilterQuery query; - private final List fields = new ArrayList<>(1); + @Override + public String getName() { + return Criteria.WILDCARD; + } + }; + + private final ParameterHolder parameterHolder = new ParameterHolder(); + private FilterQuery query; + private final List fields = new ArrayList(1); /** * Add field to highlight @@ -95,7 +100,6 @@ public HighlightOptions addFields(Collection fieldnames) { /** * @return null if not set */ - @Nullable public FilterQuery getQuery() { return this.query; } @@ -113,7 +117,6 @@ public HighlightOptions setQuery(FilterQuery query) { /** * @return null if not set */ - @Nullable public Integer getFragsize() { return this.parameterHolder.getParameterValue(HighlightParams.FRAGSIZE); } @@ -131,7 +134,6 @@ public HighlightOptions setFragsize(Integer fragsize) { /** * @return null if not set */ - @Nullable public String getFormatter() { return this.parameterHolder.getParameterValue(HighlightParams.FORMATTER); } @@ -149,7 +151,6 @@ public HighlightOptions setFormatter(String formatter) { /** * @return null if not set */ - @Nullable public Integer getNrSnipplets() { return this.parameterHolder.getParameterValue(HighlightParams.SNIPPETS); } @@ -177,7 +178,6 @@ public HighlightOptions setSimplePrefix(String prefix) { /** * @return */ - @Nullable public String getSimplePrefix() { return this.parameterHolder.getParameterValue(HighlightParams.SIMPLE_PRE); } @@ -195,7 +195,6 @@ public HighlightOptions setSimplePostfix(String postfix) { /** * @return */ - @Nullable public String getSimplePostfix() { return this.parameterHolder.getParameterValue(HighlightParams.SIMPLE_POST); } @@ -243,7 +242,6 @@ public HighlightOptions addHighlightParameter(HighlightParameter parameter) { * @param parameterName * @return null if not present */ - @Nullable public S getHighlightParameterValue(String parameterName) { return this.parameterHolder.getParameterValue(parameterName); } @@ -255,7 +253,7 @@ public S getHighlightParameterValue(String parameterName) { */ public Collection getFieldsWithHighlightParameters() { - List result = new ArrayList<>(); + List result = new ArrayList(); for (Field candidate : fields) { if (candidate instanceof FieldWithHighlightParameters) { @@ -310,13 +308,14 @@ public FieldWithHighlightParameters(String fieldname) { /** * @return null if not set */ - @Nullable public Integer getNrSnipplets() { return getQueryParameterValue(HighlightParams.SNIPPETS); } /** * set fragsize {@code hl.fragsize}. + * + * @param fragsize */ public FieldWithHighlightParameters setNrSnipplets(Integer nrSnipplets) { addHighlightParameter(HighlightParams.SNIPPETS, nrSnipplets); @@ -326,7 +325,6 @@ public FieldWithHighlightParameters setNrSnipplets(Integer nrSnipplets) { /** * @return null if not set */ - @Nullable public Integer getFragsize() { return getQueryParameterValue(HighlightParams.FRAGSIZE); } @@ -344,13 +342,14 @@ public FieldWithHighlightParameters setFragsize(Integer fragsize) { /** * @return null if not set */ - @Nullable public Boolean isMergeContigous() { return getQueryParameterValue(HighlightParams.MERGE_CONTIGUOUS_FRAGMENTS); } /** * set fragsize {@code f.<fieldname>.hl.fragsize}. + * + * @param fragsize */ public FieldWithHighlightParameters setMergeContigous(Boolean mergeContigous) { addHighlightParameter(HighlightParams.MERGE_CONTIGUOUS_FRAGMENTS, mergeContigous); @@ -360,13 +359,14 @@ public FieldWithHighlightParameters setMergeContigous(Boolean mergeContigous) { /** * @return null if not set */ - @Nullable public String getFormatter() { return getQueryParameterValue(HighlightParams.FORMATTER); } /** * set fragsize {@code f.<formatter>.hl.fragsize}. + * + * @param fragsize */ public FieldWithHighlightParameters setFormatter(String formatter) { addHighlightParameter(HighlightParams.FORMATTER, formatter); diff --git a/src/main/java/org/springframework/data/solr/core/query/HighlightQuery.java b/src/main/java/org/springframework/data/solr/core/query/HighlightQuery.java index 9d0e317..7d0573f 100644 --- a/src/main/java/org/springframework/data/solr/core/query/HighlightQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/HighlightQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * @author Christoph Strobl */ @@ -33,7 +31,6 @@ public interface HighlightQuery extends Query { /** * @return null if not set */ - @Nullable HighlightOptions getHighlightOptions(); /** diff --git a/src/main/java/org/springframework/data/solr/core/query/Join.java b/src/main/java/org/springframework/data/solr/core/query/Join.java index 5f53f8a..d633e76 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Join.java +++ b/src/main/java/org/springframework/data/solr/core/query/Join.java @@ -15,7 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -26,9 +25,9 @@ */ public class Join { - private @Nullable Field from; - private @Nullable Field to; - private @Nullable String fromIndex; + private Field from; + private Field to; + private String fromIndex; private Join() { // hide default constructor @@ -46,7 +45,7 @@ public Join(Field from, Field to) { * @param fromIndex * @since 2.0 */ - public Join(Field from, Field to, @Nullable String fromIndex) { + public Join(Field from, Field to, String fromIndex) { this.from = from; this.to = to; this.fromIndex = fromIndex; @@ -71,7 +70,6 @@ public static Builder from(String fieldname) { /** * @return null if not set */ - @Nullable public Field getFrom() { return from; } @@ -79,7 +77,6 @@ public Field getFrom() { /** * @return null if not set */ - @Nullable public Field getTo() { return to; } @@ -88,7 +85,6 @@ public Field getTo() { * @return can be {@literal null}. * @since 2.0 */ - @Nullable public String getFromIndex() { return fromIndex; } diff --git a/src/main/java/org/springframework/data/solr/core/query/MaxFunction.java b/src/main/java/org/springframework/data/solr/core/query/MaxFunction.java index 6ae0cad..d538497 100644 --- a/src/main/java/org/springframework/data/solr/core/query/MaxFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/MaxFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -33,6 +33,7 @@ private MaxFunction(Object candiate, Object maxValue) { /** * @param fieldName + * @param maxValue * @return */ public static MaxFunction max(String fieldName, Number value) { @@ -50,6 +51,7 @@ public static MaxFunction max(String fieldName, String compareFieldName) { /** * @param fieldName + * @param compareFieldName * @return */ public static MaxFunction max(String fieldName, Function function) { @@ -57,6 +59,8 @@ public static MaxFunction max(String fieldName, Function function) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Function function, Number value) { @@ -64,6 +68,8 @@ public static MaxFunction max(Function function, Number value) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Function function, String fieldname) { @@ -71,6 +77,8 @@ public static MaxFunction max(Function function, String fieldname) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Function function, Function compareFunction) { @@ -78,6 +86,8 @@ public static MaxFunction max(Function function, Function compareFunction) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Number value, Number compareValue) { @@ -85,6 +95,8 @@ public static MaxFunction max(Number value, Number compareValue) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Number value, String fieldname) { @@ -92,6 +104,8 @@ public static MaxFunction max(Number value, String fieldname) { } /** + * @param candidate + * @param maxValue * @return */ public static MaxFunction max(Number value, Function compareFunction) { diff --git a/src/main/java/org/springframework/data/solr/core/query/Node.java b/src/main/java/org/springframework/data/solr/core/query/Node.java index 5573064..34b412c 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Node.java +++ b/src/main/java/org/springframework/data/solr/core/query/Node.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -21,7 +21,6 @@ import org.springframework.data.geo.Box; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; -import org.springframework.lang.Nullable; /** * @author Christoph Strobl @@ -29,14 +28,14 @@ */ public abstract class Node { - private @Nullable Node parent; + private Node parent; private boolean isOr = false; private boolean negating = false; protected Node() {} // ------- TREE --------- - protected void setParent(@Nullable Node parent) { + protected void setParent(Node parent) { this.parent = parent; } @@ -68,7 +67,6 @@ public boolean isOr() { * * @return null in case no parent set. */ - @Nullable public Node getParent() { return this.parent; } @@ -115,6 +113,7 @@ protected void setNegating(boolean negating) { /** * Combine node with new {@link Node} for given {@literal fieldname} using {@literal and}. * + * @param part * @return */ public abstract T and(String fieldname); @@ -130,6 +129,7 @@ protected void setNegating(boolean negating) { /** * Combine node with new {@link Node} for given {@literal fieldname} using {@literal and}. * + * @param part * @return */ public abstract T or(String fieldname); diff --git a/src/main/java/org/springframework/data/solr/core/query/NotFunction.java b/src/main/java/org/springframework/data/solr/core/query/NotFunction.java index 601b0d1..d1328be 100644 --- a/src/main/java/org/springframework/data/solr/core/query/NotFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/NotFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.util.Assert; @@ -30,7 +30,7 @@ public class NotFunction extends AbstractFunction { private static final String OPERATION = "not"; private NotFunction(Object condition) { - super(Collections.singletonList(condition)); + super(Arrays.asList(condition)); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/ParameterHolder.java b/src/main/java/org/springframework/data/solr/core/query/ParameterHolder.java index 02e0bcb..7681161 100644 --- a/src/main/java/org/springframework/data/solr/core/query/ParameterHolder.java +++ b/src/main/java/org/springframework/data/solr/core/query/ParameterHolder.java @@ -21,7 +21,6 @@ import java.util.LinkedHashMap; import java.util.Map; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -32,10 +31,9 @@ */ class ParameterHolder implements Iterable { - private final Map parameters = new LinkedHashMap<>(1); + private final Map parameters = new LinkedHashMap(1); @SuppressWarnings("unchecked") - @Nullable public S getParameterValue(String parameterName) { T parameter = this.parameters.get(parameterName); if (parameter == null) { @@ -58,7 +56,6 @@ public void add(T queryParameter) { * @param parameterName * @return null if not found */ - @Nullable public T get(String parameterName) { return this.parameters.get(parameterName); } diff --git a/src/main/java/org/springframework/data/solr/core/query/PartialUpdate.java b/src/main/java/org/springframework/data/solr/core/query/PartialUpdate.java index 84c4f74..c6b400c 100644 --- a/src/main/java/org/springframework/data/solr/core/query/PartialUpdate.java +++ b/src/main/java/org/springframework/data/solr/core/query/PartialUpdate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -19,19 +19,18 @@ import java.util.Collections; import java.util.List; -import org.springframework.lang.Nullable; - /** * Implementation of {@link Update} to be used when performing atomic updates against solr.
* Update can directly be saved via {@link org.springframework.data.solr.core.SolrOperations#saveBean(Object)} * + * * @author Christoph Strobl */ public class PartialUpdate implements Update { private final ValueHoldingField idField; - private @Nullable Object version; - private final List updates = new ArrayList<>(); + private Object version; + private final List updates = new ArrayList(); public PartialUpdate(String idFieldName, Object idFieldValue) { this(new IdField(idFieldName, idFieldValue)); @@ -51,8 +50,8 @@ public ValueHoldingField getIdField() { } /** - * Add field with given name and value to the fields to be updated. Default {@link UpdateAction} will be - * {@link UpdateAction.SET}. + * Add field with given name and value to the fields to be updated. Default {@link UpateAction} will be + * {@link UpateAction.SET}. * * @param fieldName * @param value @@ -71,7 +70,7 @@ public void add(UpdateField field) { } /** - * Add field with given name and value using {@link UpdateAction#ADD} to the fields to be updated. + * Add field with given name and value using {@link UpateAction.ADD} to the fields to be updated. * * @param fieldName * @param value @@ -81,7 +80,7 @@ public void addValueToField(String fieldName, Object value) { } /** - * Add field with given name and value using {@link UpdateAction#SET} to the fields to be updated. + * Add field with given name and value using {@link UpateAction.SET} to the fields to be updated. * * @param fieldName * @param value @@ -91,7 +90,7 @@ public void setValueOfField(String fieldName, Object value) { } /** - * Add field with given name and value using {@link UpdateAction#INC} to the fields to be updated. + * Add field with given name and value using {@link UpateAction.INC} to the fields to be updated. * * @param fieldName * @param value @@ -105,7 +104,6 @@ public List getUpdates() { return Collections.unmodifiableList(updates); } - @Nullable @Override public Object getVersion() { return this.version; diff --git a/src/main/java/org/springframework/data/solr/core/query/ProductFunction.java b/src/main/java/org/springframework/data/solr/core/query/ProductFunction.java index bb61a6f..7a36b74 100644 --- a/src/main/java/org/springframework/data/solr/core/query/ProductFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/ProductFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.util.Assert; @@ -30,7 +30,7 @@ public class ProductFunction extends AbstractFunction { private static final String OPERATION = "product"; private ProductFunction(Object value) { - super(Collections.singletonList(value)); + super(Arrays.asList(value)); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/Query.java b/src/main/java/org/springframework/data/solr/core/query/Query.java index 83ade2c..cfeb5b0 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Query.java +++ b/src/main/java/org/springframework/data/solr/core/query/Query.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -19,7 +19,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.lang.Nullable; /** * A Query that can be translated into a solr understandable Query. @@ -40,7 +39,7 @@ enum Operator { private String operator; - Operator(String operator) { + private Operator(String operator) { this.operator = operator; } @@ -79,16 +78,7 @@ public String toString() { * @return * @since 1.3 */ - T setOffset(Long offset); - - /** - * Set the rerank value. - * - * @param offset - * @return - * @since 1.3 - */ - T setReRank(String rqqValue); + T setOffset(Integer offset); /** * Set the number of rows to fetch. @@ -144,8 +134,7 @@ public String toString() { * * @since 1.3 */ - @Nullable - Long getOffset(); + Integer getOffset(); /** * Get number of rows to fetch. @@ -153,7 +142,6 @@ public String toString() { * @return * @since 1.3 */ - @Nullable Integer getRows(); /** @@ -181,7 +169,6 @@ public String toString() { /** * @return null if not set */ - @Nullable Sort getSort(); /** @@ -189,17 +176,7 @@ public String toString() { * * @return */ - @Nullable Integer getTimeAllowed(); - - /** - * Return the time (in milliseconds) allowed for a search to finish - * - * @return - */ - @Nullable - String getRqqValue(); - /** * Set the default operator {@code q.op} for query expressions @@ -214,7 +191,6 @@ public String toString() { * * @return */ - @Nullable Operator getDefaultOperator(); /** @@ -223,7 +199,6 @@ public String toString() { * * @return */ - @Nullable String getDefType(); /** @@ -234,7 +209,6 @@ public String toString() { /** * Returns the request handler. */ - @Nullable String getRequestHandler(); /** @@ -253,7 +227,6 @@ public String toString() { /** * @return group options */ - @Nullable GroupOptions getGroupOptions(); /** @@ -269,7 +242,6 @@ public String toString() { * @return {@link StatsOptions} or null if not set. * @since 1.4 */ - @Nullable StatsOptions getStatsOptions(); /** @@ -285,7 +257,6 @@ public String toString() { * @return {@literal null} if not set. * @since 2.1 */ - @Nullable SpellcheckOptions getSpellcheckOptions(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/QueryFunction.java b/src/main/java/org/springframework/data/solr/core/query/QueryFunction.java index 77bc1c0..0789dbb 100644 --- a/src/main/java/org/springframework/data/solr/core/query/QueryFunction.java +++ b/src/main/java/org/springframework/data/solr/core/query/QueryFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,7 @@ */ package org.springframework.data.solr.core.query; -import java.util.Collections; +import java.util.Arrays; import org.springframework.util.Assert; @@ -30,7 +30,7 @@ public class QueryFunction extends AbstractFunction { private static final String OPERATION = "query"; private QueryFunction(Query query) { - super(Collections.singletonList(query)); + super(Arrays.asList(query)); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/QueryParameter.java b/src/main/java/org/springframework/data/solr/core/query/QueryParameter.java index 4cfa95a..54f45c3 100644 --- a/src/main/java/org/springframework/data/solr/core/query/QueryParameter.java +++ b/src/main/java/org/springframework/data/solr/core/query/QueryParameter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Query Parameter to be used when executing query against solr server * @@ -32,7 +30,6 @@ public interface QueryParameter { /** * @return null if not set */ - @Nullable Object getValue(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/QueryParameterImpl.java b/src/main/java/org/springframework/data/solr/core/query/QueryParameterImpl.java index 6d99a41..8379299 100644 --- a/src/main/java/org/springframework/data/solr/core/query/QueryParameterImpl.java +++ b/src/main/java/org/springframework/data/solr/core/query/QueryParameterImpl.java @@ -15,7 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -26,13 +25,13 @@ public class QueryParameterImpl implements QueryParameter { private final String name; - private @Nullable Object value; + private Object value; /** * @param name must not be null * @param value */ - public QueryParameterImpl(String name, @Nullable Object value) { + public QueryParameterImpl(String name, Object value) { super(); Assert.notNull(name, "Name must not be null!"); @@ -45,7 +44,6 @@ public String getName() { return this.name; } - @Nullable @Override public Object getValue() { return this.value; diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleCalculatedField.java b/src/main/java/org/springframework/data/solr/core/query/SimpleCalculatedField.java index 92d2caf..0657268 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleCalculatedField.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleCalculatedField.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,7 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -31,7 +30,7 @@ public SimpleCalculatedField(Function function) { this(null, function); } - public SimpleCalculatedField(@Nullable String alias, Function function) { + public SimpleCalculatedField(String alias, Function function) { Assert.notNull(function, "Function cannot be empty."); this.alias = alias; diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleFacetAndHighlightQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleFacetAndHighlightQuery.java index 6cc3961..2abb6d5 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleFacetAndHighlightQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleFacetAndHighlightQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -16,20 +16,18 @@ package org.springframework.data.solr.core.query; import org.springframework.data.domain.Pageable; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Trivial implementation of {@link FacetAndHighlightQuery} * * @author David Webb - * @author Christoph Strobl * @since 2.1.0 */ public class SimpleFacetAndHighlightQuery extends SimpleQuery implements FacetAndHighlightQuery { - private @Nullable FacetOptions facetOptions; - private @Nullable HighlightOptions highlightOptions; + private FacetOptions facetOptions; + private HighlightOptions highlightOptions; public SimpleFacetAndHighlightQuery() { super(); @@ -39,7 +37,7 @@ public SimpleFacetAndHighlightQuery(Criteria criteria) { this(criteria, null); } - public SimpleFacetAndHighlightQuery(Criteria criteria, @Nullable Pageable pageable) { + public SimpleFacetAndHighlightQuery(Criteria criteria, Pageable pageable) { super(criteria, pageable); } @@ -49,7 +47,7 @@ public SimpleFacetAndHighlightQuery(Criteria criteria, @Nullable Pageable pageab */ @SuppressWarnings("unchecked") @Override - public final T setFacetOptions(@Nullable FacetOptions facetOptions) { + public final T setFacetOptions(FacetOptions facetOptions) { if (facetOptions != null) { Assert.isTrue(facetOptions.hasFacets(), "Cannot set facet options having neither fields nor queries."); @@ -62,7 +60,6 @@ public final T setFacetOptions(@Nullable FacetOptions * (non-Javadoc) * @see org.springframework.data.solr.core.query.FacetQuery#getFacetOptions() */ - @Nullable @Override public FacetOptions getFacetOptions() { return this.facetOptions; @@ -93,7 +90,6 @@ public T setHighlightOptions(HighlightOptions highligh * (non-Javadoc) * @see org.springframework.data.solr.core.query.HighlightQuery#getHighlightOptions() */ - @Nullable @Override public HighlightOptions getHighlightOptions() { return this.highlightOptions; diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleFacetQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleFacetQuery.java index 91bcc60..9a8e6ac 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleFacetQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleFacetQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. @@ -16,7 +16,6 @@ package org.springframework.data.solr.core.query; import org.springframework.data.domain.Pageable; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -26,7 +25,7 @@ */ public class SimpleFacetQuery extends SimpleQuery implements FacetQuery { - private @Nullable FacetOptions facetOptions; + private FacetOptions facetOptions; public SimpleFacetQuery() { super(); @@ -36,7 +35,7 @@ public SimpleFacetQuery(Criteria criteria) { this(criteria, null); } - public SimpleFacetQuery(Criteria criteria, @Nullable Pageable pageable) { + public SimpleFacetQuery(Criteria criteria, Pageable pageable) { super(criteria, pageable); } @@ -50,7 +49,6 @@ public final T setFacetOptions(FacetOptions facetOptio return (T) this; } - @Nullable @Override public FacetOptions getFacetOptions() { return this.facetOptions; diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleHighlightQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleHighlightQuery.java index 1fbd623..e82d101 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleHighlightQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleHighlightQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -16,7 +16,6 @@ package org.springframework.data.solr.core.query; import org.springframework.data.domain.Pageable; -import org.springframework.lang.Nullable; /** * Trivial implementation of {@link HighlightQuery} extending {@link SimpleQuery}. @@ -25,13 +24,13 @@ */ public class SimpleHighlightQuery extends SimpleQuery implements HighlightQuery { - private @Nullable HighlightOptions highlightOptions; + private HighlightOptions highlightOptions; public SimpleHighlightQuery() { super(); } - public SimpleHighlightQuery(Criteria criteria, @Nullable Pageable pageable) { + public SimpleHighlightQuery(Criteria criteria, Pageable pageable) { super(criteria, pageable); } @@ -46,7 +45,6 @@ public T setHighlightOptions(HighlightOptions highligh return (T) this; } - @Nullable @Override public HighlightOptions getHighlightOptions() { return this.highlightOptions; diff --git a/src/main/java/org/springframework/data/solr/core/query/SimplePivotField.java b/src/main/java/org/springframework/data/solr/core/query/SimplePivotField.java index 809bad9..ca7112b 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimplePivotField.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimplePivotField.java @@ -1,25 +1,9 @@ -/* - * 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.solr.core.query; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -27,12 +11,13 @@ * * @author Francisco Spaeth * @author Christoph Strobl + * */ public class SimplePivotField implements PivotField { private static final String DELIMINATOR = ","; - private final List fields = new ArrayList<>(2); - private @Nullable String name; + private final List fields = new ArrayList(2); + private String name; /** * Create new {@link SimplePivotField} @@ -56,7 +41,7 @@ public SimplePivotField(List fields) { this.fields.addAll(fields); } - private void splitAndAddFieldnames(String... fieldnames) { + private final void splitAndAddFieldnames(String... fieldnames) { for (String fieldname : fieldnames) { if (fieldname.contains(DELIMINATOR)) { splitAndAddFieldnames(fieldname.split(DELIMINATOR)); @@ -125,4 +110,4 @@ public boolean equals(Object obj) { return true; } -} +} \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java index feabd56..abbc725 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java @@ -21,7 +21,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -35,23 +34,21 @@ */ public class SimpleQuery extends AbstractQuery implements Query, FilterQuery { - private List projectionOnFields = new ArrayList<>(0); - private List filterQueries = new ArrayList<>(0); + private List projectionOnFields = new ArrayList(0); + private List filterQueries = new ArrayList(0);; - private @Nullable Long offset = null; - private @Nullable Integer rows = null; + private Integer offset = null; + private Integer rows = null; - private Sort sort = Sort.unsorted(); + private Sort sort; - private @Nullable Operator defaultOperator; - private @Nullable Integer timeAllowed; - private @Nullable String rqqValue; - - private @Nullable String defType; + private Operator defaultOperator; + private Integer timeAllowed; + private String defType; - private @Nullable GroupOptions groupOptions; - private @Nullable StatsOptions statsOptions; - private @Nullable SpellcheckOptions spellcheckOptions; + private GroupOptions groupOptions; + private StatsOptions statsOptions; + private SpellcheckOptions spellcheckOptions; public SimpleQuery() {} @@ -59,7 +56,7 @@ public SimpleQuery() {} * @param criteria */ public SimpleQuery(Criteria criteria) { - this(criteria, Pageable.unpaged()); + this(criteria, null); } /** @@ -74,10 +71,10 @@ public SimpleQuery(String queryString) { * @param criteria * @param pageable */ - public SimpleQuery(Criteria criteria, @Nullable Pageable pageable) { + public SimpleQuery(Criteria criteria, Pageable pageable) { super(criteria); - if (pageable != null && !pageable.isUnpaged()) { + if (pageable != null) { this.offset = pageable.getOffset(); this.rows = pageable.getPageSize(); this.addSort(pageable.getSort()); @@ -93,13 +90,11 @@ public SimpleQuery(String queryString, Pageable pageable) { this(new SimpleStringCriteria(queryString), pageable); } - @Nullable public static final Query fromQuery(Query source) { return fromQuery(source, new SimpleQuery()); } - @Nullable - public static T fromQuery(@Nullable Query source, @Nullable T destination) { + public static T fromQuery(Query source, T destination) { if (source == null || destination == null) { return null; } @@ -188,7 +183,7 @@ public final T setPageRequest(Pageable pageable) { @SuppressWarnings("unchecked") @Override - public T setOffset(Long offset) { + public T setOffset(Integer offset) { this.offset = offset; return (T) this; } @@ -230,7 +225,7 @@ public final T addGroupByField(String fieldname) { @SuppressWarnings("unchecked") @Override - public final T addSort(@Nullable Sort sort) { + public final T addSort(Sort sort) { if (sort == null) { return (T) this; } @@ -253,22 +248,20 @@ public Sort getSort() { public Pageable getPageRequest() { if (this.rows == null && this.offset == null) { - return Pageable.unpaged(); + return null; } int rows = this.rows != null ? this.rows : DEFAULT_PAGE_SIZE; - long offset = this.offset != null ? this.offset : 0; + int offset = this.offset != null ? this.offset : 0; - return new SolrPageRequest(rows != 0 ? (int) (offset / rows) : 0, rows, this.sort); + return new SolrPageRequest(rows != 0 ? offset / rows : 0, rows, this.sort); } - @Nullable @Override - public Long getOffset() { + public Integer getOffset() { return this.offset; } - @Nullable @Override public Integer getRows() { return this.rows; @@ -302,7 +295,6 @@ public T setTimeAllowed(Integer timeAllowed) { return (T) this; } - @Nullable @Override public Integer getTimeAllowed() { return this.timeAllowed; @@ -315,7 +307,6 @@ public T setGroupOptions(GroupOptions groupOptions) { return (T) this; } - @Nullable @Override public GroupOptions getGroupOptions() { return groupOptions; @@ -325,7 +316,6 @@ public GroupOptions getGroupOptions() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.Query#getStatsOptions() */ - @Nullable @Override public StatsOptions getStatsOptions() { return statsOptions; @@ -391,21 +381,8 @@ public T setSpellcheckOptions(SpellcheckOptions spellcheckOpti * (non-Javadoc) * @see org.springframework.data.solr.core.query.Query#getSpellcheckOptions() */ - @Nullable @Override public SpellcheckOptions getSpellcheckOptions() { return this.spellcheckOptions; } - - @SuppressWarnings("unchecked") - @Override - public T setReRank(String rqqValue) { - this.rqqValue=rqqValue; - return (T) this; - } - - @Override - public String getRqqValue() { - return this.rqqValue; - } } diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleTermsQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleTermsQuery.java index a336625..cff687d 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleTermsQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleTermsQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -25,13 +25,14 @@ /** * @author Christoph Strobl + * */ public class SimpleTermsQuery extends AbstractQuery implements TermsQuery { public static final String DEFAULT_REQUEST_HANDLER = "/terms"; private TermsOptions termsOptions = new TermsOptions(); - private List fields = new ArrayList<>(1); + private List fields = new ArrayList(1); public SimpleTermsQuery() { super(); diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleUpdateField.java b/src/main/java/org/springframework/data/solr/core/query/SimpleUpdateField.java index 500084b..07ce851 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleUpdateField.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleUpdateField.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Implementation of {@link UpdateField} to be used with {@link Update} * @@ -33,11 +31,10 @@ public SimpleUpdateField(String name) { /** * Creates new instance with {@link #DEFAULT_ACTION} - * - * @param name + * @param name * @param value */ - public SimpleUpdateField(String name, @Nullable Object value) { + public SimpleUpdateField(String name, Object value) { this(name, value, DEFAULT_ACTION); } @@ -46,7 +43,7 @@ public SimpleUpdateField(String name, @Nullable Object value) { * @param value * @param action */ - public SimpleUpdateField(String name, @Nullable Object value, UpdateAction action) { + public SimpleUpdateField(String name, Object value, UpdateAction action) { super(name, value); this.action = action; } diff --git a/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java b/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java index 3926199..9491685 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Common interface for any Query * @@ -35,18 +33,19 @@ public interface SolrDataQuery { /** * @return */ - @Nullable Criteria getCriteria(); /** * Set values for join {@code !join from=inner_id to=outer_id} + * + * @param from + * @param to */ void setJoin(Join join); /** * @return */ - @Nullable Join getJoin(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/SolrPageRequest.java b/src/main/java/org/springframework/data/solr/core/query/SolrPageRequest.java index 07ef934..de34950 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SolrPageRequest.java +++ b/src/main/java/org/springframework/data/solr/core/query/SolrPageRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -19,7 +19,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; -import org.springframework.lang.Nullable; /** * Solr specific implementation of {@code Pageable} allowing zero sized pages. @@ -28,7 +27,7 @@ */ public class SolrPageRequest implements Pageable { - private @Nullable Sort sort; + private Sort sort; private int page; private int size; @@ -39,7 +38,7 @@ public class SolrPageRequest implements Pageable { * @param size the size of the page to be returned. */ public SolrPageRequest(int page, int size) { - this(page, size, Sort.unsorted()); + this(page, size, null); } /** @@ -61,7 +60,7 @@ public SolrPageRequest(int page, int size, Direction direction, String... proper * @param size the size of the page to be returned. * @param sort can be {@literal null}. */ - public SolrPageRequest(int page, int size, @Nullable Sort sort) { + public SolrPageRequest(int page, int size, Sort sort) { this.page = page; this.size = size; this.sort = sort; @@ -90,7 +89,7 @@ public int getPageSize() { * @see org.springframework.data.domain.Pageable#getOffset() */ @Override - public long getOffset() { + public int getOffset() { return page * size; } @@ -100,7 +99,7 @@ public long getOffset() { */ @Override public Sort getSort() { - return sort != null ? sort : Sort.unsorted(); + return sort; } /* @@ -150,9 +149,12 @@ public Pageable previous() { @Override public int hashCode() { - int result = sort.hashCode(); - result = 31 * result + page; - result = 31 * result + (int) (size ^ (size >>> 32)); + + final int prime = 31; + int result = 1; + result = prime * result + page; + result = prime * result + size; + result = prime * result + ((sort == null) ? 0 : sort.hashCode()); return result; } diff --git a/src/main/java/org/springframework/data/solr/core/query/SpellcheckOptions.java b/src/main/java/org/springframework/data/solr/core/query/SpellcheckOptions.java index e8379f3..cc2b094 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SpellcheckOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/SpellcheckOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -21,7 +21,6 @@ import java.util.Map.Entry; import org.apache.solr.common.params.SpellingParams; -import org.springframework.lang.Nullable; /** * {@link SpellcheckOptions} allows modification of query parameters targeting the SpellCheck component is designed to @@ -32,13 +31,13 @@ */ public class SpellcheckOptions { - private @Nullable Query query; + private Query query; private Map params; - private SpellcheckOptions(@Nullable Query query, Map params) { + private SpellcheckOptions(Query query, Map params) { this.query = query; - this.params = new LinkedHashMap<>(params); + this.params = new LinkedHashMap(params); } /** @@ -47,7 +46,7 @@ private SpellcheckOptions(@Nullable Query query, Map params) { * @return */ public static SpellcheckOptions spellcheck() { - return new SpellcheckOptions(null, new LinkedHashMap<>()); + return new SpellcheckOptions(null, new LinkedHashMap()); } /** @@ -57,7 +56,7 @@ public static SpellcheckOptions spellcheck() { * @return */ public static SpellcheckOptions spellcheck(Query q) { - return new SpellcheckOptions(q, new LinkedHashMap<>()); + return new SpellcheckOptions(q, new LinkedHashMap()); } /** @@ -65,7 +64,6 @@ public static SpellcheckOptions spellcheck(Query q) { * * @return can be {@literal null}. */ - @Nullable public Query getQuery() { return query; } @@ -125,7 +123,6 @@ public SpellcheckOptions maxCollations(long max) { /** * @return can be {@literal null}. */ - @Nullable public Long getMaxCollations() { return (Long) params.get(SpellingParams.SPELLCHECK_MAX_COLLATIONS); } @@ -143,7 +140,6 @@ public SpellcheckOptions maxCollationTries(long tries) { /** * @return can be {@literal null}. */ - @Nullable public Long getMaxCollationTries() { return (Long) params.get(SpellingParams.SPELLCHECK_MAX_COLLATION_TRIES); } @@ -162,7 +158,6 @@ public SpellcheckOptions maxCollationEvaluations(long evaluations) { /** * @return can be {@literal null}. */ - @Nullable public Long getMaxCollationEvaluations() { return (Long) params.get(SpellingParams.SPELLCHECK_MAX_COLLATION_EVALUATIONS); } @@ -180,7 +175,6 @@ public SpellcheckOptions extendedResults() { /** * @return can be {@literal null}. */ - @Nullable public Boolean getExtendedResults() { return (Boolean) params.get(SpellingParams.SPELLCHECK_EXTENDED_RESULTS); } @@ -216,7 +210,6 @@ public SpellcheckOptions maxCollationCollectDocs(long nr) { /** * @return can be {@literal null}. */ - @Nullable public Long getMaxCollationCollectDocs() { return (Long) params.get(SpellingParams.SPELLCHECK_COLLATE_MAX_COLLECT_DOCS); } @@ -238,7 +231,7 @@ public SpellcheckOptions collateParam(String param, Object value) { */ public Map getCollateParams() { - Map tmp = new LinkedHashMap<>(); + Map tmp = new LinkedHashMap(); for (Entry entry : params.entrySet()) { if (entry.getKey().startsWith(SpellingParams.SPELLCHECK_COLLATE_PARAM_OVERRIDE)) { @@ -261,7 +254,6 @@ public SpellcheckOptions count(long nr) { /** * @return can be {@literal null}. */ - @Nullable public Long getCount() { return (Long) params.get(SpellingParams.SPELLCHECK_COUNT); } @@ -270,6 +262,7 @@ public Long getCount() { * This parameter causes Solr to use the dictionary named in the parameter's argument. The default setting is * "default". This parameter can be used to invoke a specific spellchecker on a per request basis. * + * @param name * @return */ public SpellcheckOptions dictionaries(String... names) { @@ -279,7 +272,6 @@ public SpellcheckOptions dictionaries(String... names) { /** * @return can be {@literal null}. */ - @Nullable public String[] getDictionary() { return (String[]) params.get(SpellingParams.SPELLCHECK_DICT); } @@ -315,7 +307,6 @@ public SpellcheckOptions maxResultsForSuggest(long nr) { /** * @return can be {@literal null}. */ - @Nullable public Long getMaxResultsForSuggest() { return (Long) params.get(SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST); } @@ -333,7 +324,6 @@ public SpellcheckOptions alternativeTermCount(long nr) { /** * @return can be {@literal null}. */ - @Nullable public Long getAlternativeTermCount() { return (Long) params.get(SpellingParams.SPELLCHECK_ALTERNATIVE_TERM_COUNT); } @@ -352,7 +342,6 @@ public SpellcheckOptions accuracy(float nr) { /** * @return can be {@literal null}. */ - @Nullable public Float getAccuracy() { return (Float) params.get(SpellingParams.SPELLCHECK_ACCURACY); } diff --git a/src/main/java/org/springframework/data/solr/core/query/StatsOptions.java b/src/main/java/org/springframework/data/solr/core/query/StatsOptions.java index 00ba18d..cb15297 100644 --- a/src/main/java/org/springframework/data/solr/core/query/StatsOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/StatsOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -23,7 +23,6 @@ import java.util.Map; import java.util.Set; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -81,6 +80,7 @@ public Collection getFields() { /** * Adds a facet on field to the statistics to be requested. * + * @param fieldName * @return */ public StatsOptions addFacet(Field field) { @@ -147,7 +147,6 @@ public Map getSelectiveCalcDistincts() { * @param field * @return true if a distinct calculation shall be done selectively to the given field. */ - @Nullable public Boolean isSelectiveCalcDistincts(Field field) { return state.selectiveCalcDistinct.get(field); } @@ -175,7 +174,7 @@ private FieldStatsOptions(Field fieldContext, StatsOptionsState state) { */ public FieldStatsOptions addSelectiveFacet(Field field) { if (!state.selectiveFacets.containsKey(fieldContext)) { - state.selectiveFacets.put(fieldContext, new ArrayList<>()); + state.selectiveFacets.put(fieldContext, new ArrayList()); } state.selectiveFacets.get(fieldContext).add(field); return this; @@ -198,10 +197,10 @@ public FieldStatsOptions setSelectiveCalcDistinct(boolean calcDistinct) { */ private static class StatsOptionsState { - private Set fields = new LinkedHashSet<>(1); - private Set facets = new LinkedHashSet<>(0); + private Set fields = new LinkedHashSet(1); + private Set facets = new LinkedHashSet(0); private boolean calcDistinct = false; - private Map> selectiveFacets = new LinkedHashMap<>(); - private Map selectiveCalcDistinct = new LinkedHashMap<>(); + private Map> selectiveFacets = new LinkedHashMap>(); + private Map selectiveCalcDistinct = new LinkedHashMap(); } } diff --git a/src/main/java/org/springframework/data/solr/core/query/TermsOptions.java b/src/main/java/org/springframework/data/solr/core/query/TermsOptions.java index b28e7bf..e38603b 100644 --- a/src/main/java/org/springframework/data/solr/core/query/TermsOptions.java +++ b/src/main/java/org/springframework/data/solr/core/query/TermsOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,28 +15,27 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * @author Christoph Strobl + * */ public class TermsOptions { public static final Sort DEFAULT_SORT = Sort.COUNT; - private @Nullable BoundTerm lowerBoundTerm; + private BoundTerm lowerBoundTerm; - private @Nullable BoundTerm upperBoundTerm; + private BoundTerm upperBoundTerm; private int minCount = -1; private int maxCount = -1; - private @Nullable String prefix; + private String prefix; - private @Nullable String regex; + private String regex; - private @Nullable RegexFlag regexFlag; + private RegexFlag regexFlag; private int limit = -1; @@ -44,7 +43,6 @@ public class TermsOptions { private boolean raw = false; - @Nullable public BoundTerm getLowerBoundTerm() { return lowerBoundTerm; } @@ -53,7 +51,6 @@ public void setLowerBoundTerm(BoundTerm lowerBoundTerm) { this.lowerBoundTerm = lowerBoundTerm; } - @Nullable public BoundTerm getUpperBoundTerm() { return upperBoundTerm; } @@ -78,7 +75,6 @@ public void setMaxCount(int maxCount) { this.maxCount = maxCount; } - @Nullable public String getPrefix() { return prefix; } @@ -87,7 +83,6 @@ public void setPrefix(String prefix) { this.prefix = prefix; } - @Nullable public String getRegex() { return regex; } @@ -96,7 +91,6 @@ public void setRegex(String regex) { this.regex = regex; } - @Nullable public RegexFlag getRegexFlag() { return regexFlag; } @@ -113,7 +107,6 @@ public void setLimit(int limit) { this.limit = limit; } - @Nullable public Sort getSort() { return sort; } @@ -132,14 +125,14 @@ public void setRaw(boolean raw) { /** * @author Christoph Strobl + * */ public static class BoundTerm { - private @Nullable String term; + private String term; private boolean include; - @Nullable public String getTerm() { return term; } diff --git a/src/main/java/org/springframework/data/solr/core/query/Update.java b/src/main/java/org/springframework/data/solr/core/query/Update.java index e9858b9..abd6ab9 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Update.java +++ b/src/main/java/org/springframework/data/solr/core/query/Update.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * Update one or more fields of a Document without touching the others. * @@ -43,7 +41,6 @@ public interface Update { * * @return */ - @Nullable Object getVersion(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/ValueHoldingField.java b/src/main/java/org/springframework/data/solr/core/query/ValueHoldingField.java index e56d64a..15b8853 100644 --- a/src/main/java/org/springframework/data/solr/core/query/ValueHoldingField.java +++ b/src/main/java/org/springframework/data/solr/core/query/ValueHoldingField.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import org.springframework.lang.Nullable; - /** * @author Christoph Strobl */ @@ -25,9 +23,8 @@ public interface ValueHoldingField extends Field { /** * Get value for field * - * @return can be {@literal null}. + * @return */ - @Nullable Object getValue(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/package-info.java b/src/main/java/org/springframework/data/solr/core/query/package-info.java deleted file mode 100644 index 32e36a7..0000000 --- a/src/main/java/org/springframework/data/solr/core/query/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Query abstractions for {@link org.apache.solr.client.solrj.SolrQuery}. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.core.query; diff --git a/src/main/java/org/springframework/data/solr/core/query/result/Cursor.java b/src/main/java/org/springframework/data/solr/core/query/result/Cursor.java index e805142..60f06c9 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/Cursor.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/Cursor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -19,8 +19,6 @@ import java.io.Serializable; import java.util.Iterator; -import org.springframework.lang.Nullable; - /** * {@link Cursor} provides a lazy loading abstraction for fetching documents. * @@ -30,7 +28,7 @@ public interface Cursor extends Iterator, Closeable { enum State { - REDAY, OPEN, FINISHED, CLOSED + REDAY, OPEN, FINISHED, CLOSED; } /** @@ -38,7 +36,6 @@ enum State { * * @return */ - @Nullable Serializable getCursorMark(); /** diff --git a/src/main/java/org/springframework/data/solr/core/query/result/DelegatingCursor.java b/src/main/java/org/springframework/data/solr/core/query/result/DelegatingCursor.java index 0ae1887..4920d7a 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/DelegatingCursor.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/DelegatingCursor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -25,7 +25,6 @@ import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.params.CursorMarkParams; import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -39,7 +38,7 @@ public abstract class DelegatingCursor implements Cursor { private State state; - private @Nullable String cursorMark; + private String cursorMark; private long position; private Iterator delegate; private final SolrQuery referenceQuery; @@ -104,10 +103,10 @@ protected T moveNext(Iterator source) { return source.next(); } - private void load(@Nullable String cursorMark) { + private void load(String cursorMark) { SolrQuery query = referenceQuery.getCopy(); - query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark); + query.set(CursorMarkParams.CURSOR_MARK_PARAM, this.getCursorMark()); PartialResult result = doLoad(query); process(result); @@ -121,7 +120,7 @@ private void load(@Nullable String cursorMark) { */ protected abstract PartialResult doLoad(SolrQuery nativeQuery); - private void process(@Nullable PartialResult result) { + private void process(PartialResult result) { if (result == null) { this.delegate = Collections. emptyList().iterator(); @@ -163,7 +162,7 @@ public DelegatingCursor open() { * * @param cursorMark */ - protected void doOpen(@Nullable String cursorMark) { + protected void doOpen(String cursorMark) { load(cursorMark); } @@ -214,7 +213,6 @@ public long getPosition() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.Cursor#getCursorMark() */ - @Nullable @Override public String getCursorMark() { return this.cursorMark; @@ -269,9 +267,9 @@ public static class PartialResult implements Iterable { private String nextCursorMark; private Collection items; - public PartialResult(String nextCursorMark, @Nullable Collection items) { + public PartialResult(String nextCursorMark, Collection items) { this.nextCursorMark = nextCursorMark; - this.items = (items != null ? new ArrayList<>(items) : Collections. emptyList()); + this.items = (items != null ? new ArrayList(items) : Collections. emptyList()); } /** diff --git a/src/main/java/org/springframework/data/solr/core/query/result/FacetQueryResult.java b/src/main/java/org/springframework/data/solr/core/query/result/FacetQueryResult.java index 80fe088..0a9180c 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/FacetQueryResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/FacetQueryResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -68,6 +68,7 @@ public interface FacetQueryResult { /** * Get Facet Pivot results for fields with given fields. * + * @param fields pivot field name * @return */ List getPivot(String fieldName); @@ -75,6 +76,7 @@ public interface FacetQueryResult { /** * Get Facet Pivot results for fields with given fields. * + * @param fields pivot field * @return */ List getPivot(PivotField field); diff --git a/src/main/java/org/springframework/data/solr/core/query/result/FieldStatsResult.java b/src/main/java/org/springframework/data/solr/core/query/result/FieldStatsResult.java index 55b08eb..37e89c3 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/FieldStatsResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/FieldStatsResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -19,7 +19,6 @@ import java.util.Map; import org.springframework.data.solr.core.query.Field; -import org.springframework.lang.Nullable; /** * Specialization of {@link StatsResult} to represent statistic information for a field. @@ -40,6 +39,7 @@ public interface FieldStatsResult extends StatsResult { /** * Return a map of value associated to its statistics for a given field. * + * @param value * @return map of values statistics */ Map getFacetStatsResult(Field field); @@ -47,6 +47,7 @@ public interface FieldStatsResult extends StatsResult { /** * Return a map of value associated to its statistics for a given field name. * + * @param value * @return map of values statistics */ Map getFacetStatsResult(String fieldName); @@ -56,7 +57,6 @@ public interface FieldStatsResult extends StatsResult { * * @return distinct count, {@literal null} when not requested */ - @Nullable Long getDistinctCount(); /** diff --git a/src/main/java/org/springframework/data/solr/core/query/result/FieldValueCountEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/FieldValueCountEntry.java index 3b78cba..53cf45c 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/FieldValueCountEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/FieldValueCountEntry.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -17,25 +17,23 @@ import org.springframework.data.solr.core.query.Field; import org.springframework.data.solr.core.query.SimpleField; -import org.springframework.lang.Nullable; /** * @author Christoph Strobl + * */ public class FieldValueCountEntry extends ValueCountEntry { - private @Nullable Field field; + private Field field; public FieldValueCountEntry(String value, long valueCount) { super(value, valueCount); } - @Nullable public Field getKey() { return getField(); } - @Nullable public Field getField() { return this.field; } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/GroupPage.java b/src/main/java/org/springframework/data/solr/core/query/result/GroupPage.java index 8c12254..6583da6 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/GroupPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/GroupPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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. @@ -36,7 +36,7 @@ public interface GroupPage extends Page { * @param field * @return */ - GroupResult getGroupResult(Field field); + public GroupResult getGroupResult(Field field); /** * Get a group result done for the given {@link Function}. @@ -44,7 +44,7 @@ public interface GroupPage extends Page { * @param function * @return */ - GroupResult getGroupResult(Function function); + public GroupResult getGroupResult(Function function); /** * Get a group result done for the given {@link Query}. @@ -52,7 +52,7 @@ public interface GroupPage extends Page { * @param query * @return */ - GroupResult getGroupResult(Query query); + public GroupResult getGroupResult(Query query); /** * Get a group result with the given name. @@ -60,6 +60,6 @@ public interface GroupPage extends Page { * @param name * @return */ - GroupResult getGroupResult(String name); + public GroupResult getGroupResult(String name); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/GroupResult.java b/src/main/java/org/springframework/data/solr/core/query/result/GroupResult.java index 3c2bcfa..a302314 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/GroupResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/GroupResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,7 +18,13 @@ import org.springframework.data.domain.Page; /** - * Representation of a group in response to group request (i.e. , , ) will have a {@link GroupResult} representation. + * Representation of a group in response to group request (i.e. + * {@link org.springframework.data.solr.core.query.GroupQuery#addGroupByField(org.springframework.data.solr.core.query.Field)} + * , + * {@link org.springframework.data.solr.core.query.GroupQuery#addGroupByFunction(org.springframework.data.solr.core.query.Function)} + * , + * {@link org.springframework.data.solr.core.query.GroupQuery#addGroupByQuery(org.springframework.data.solr.core.query.Query)} + * ) will have a {@link GroupResult} representation. * * @author Francisco Spaeth * @param grouped content type diff --git a/src/main/java/org/springframework/data/solr/core/query/result/HighlightEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/HighlightEntry.java index ec6e2a4..5ee8ff4 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/HighlightEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/HighlightEntry.java @@ -21,7 +21,6 @@ import org.springframework.data.solr.core.query.Field; import org.springframework.data.solr.core.query.SimpleField; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -32,7 +31,7 @@ public class HighlightEntry { private final T entity; - private final List highlights = new ArrayList<>(1); + private final List highlights = new ArrayList(1); /** * @param entity must not be null @@ -88,11 +87,11 @@ public static class Highlight { * @param field must not be null * @param snipplets */ - Highlight(Field field, @Nullable List snipplets) { + Highlight(Field field, List snipplets) { Assert.notNull(field, "Field must not be null!"); this.field = field; - this.snipplets = snipplets != null ? snipplets : Collections.emptyList(); + this.snipplets = snipplets; } Highlight(String fieldname, List snipplets) { @@ -110,7 +109,7 @@ public Field getField() { * @return empty list none available */ public List getSnipplets() { - return this.snipplets; + return this.snipplets != null ? this.snipplets : Collections. emptyList(); } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/PageKey.java b/src/main/java/org/springframework/data/solr/core/query/result/PageKey.java index 4619647..e975d38 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/PageKey.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/PageKey.java @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query.result; -import org.springframework.lang.Nullable; - /** * @author Christoph Strobl */ diff --git a/src/main/java/org/springframework/data/solr/core/query/result/ScoredPage.java b/src/main/java/org/springframework/data/solr/core/query/result/ScoredPage.java index d59055b..38f833f 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/ScoredPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/ScoredPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -16,7 +16,6 @@ package org.springframework.data.solr.core.query.result; import org.springframework.data.domain.Page; -import org.springframework.lang.Nullable; /** * Specific type of {@link Page} holding max score information. @@ -31,7 +30,6 @@ public interface ScoredPage extends Page { * * @return */ - @Nullable Float getMaxScore(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleFacetPivotEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleFacetPivotEntry.java index 94f8238..0683137 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SimpleFacetPivotEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleFacetPivotEntry.java @@ -1,25 +1,8 @@ -/* - * 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. - * 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.solr.core.query.result; -import java.util.Collections; import java.util.List; import org.springframework.data.solr.core.query.Field; -import org.springframework.util.Assert; /** * The most trivial implementation of {@link FacetPivotFieldEntry}. @@ -29,7 +12,7 @@ */ public class SimpleFacetPivotEntry extends FieldValueCountEntry implements FacetPivotFieldEntry { - private List pivot = Collections.emptyList(); + private List pivot; public SimpleFacetPivotEntry(Field field, String value, long count) { super(value, count); @@ -42,8 +25,6 @@ public List getPivot() { } public void setPivot(List pivot) { - - Assert.notNull(pivot, "Pivot must not be null!"); this.pivot = pivot; } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleFieldStatsResult.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleFieldStatsResult.java index c48a30f..07071d6 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SimpleFieldStatsResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleFieldStatsResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -21,7 +21,6 @@ import java.util.Map; import org.springframework.data.solr.core.query.Field; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -32,8 +31,8 @@ */ public class SimpleFieldStatsResult extends SimpleStatsResult implements FieldStatsResult { - private Map> facetStatsResult = Collections.emptyMap(); - private @Nullable Long distinctCount; + private Map> facetStatsResult; + private Long distinctCount; private Collection distinctValues = Collections.emptyList(); @Override @@ -57,7 +56,6 @@ public Map getFacetStatsResult(String fieldName) { return facetStatsResult.get(fieldName); } - @Nullable @Override public Long getDistinctCount() { return distinctCount; @@ -72,20 +70,20 @@ public Collection getDistinctValues() { return Collections.unmodifiableCollection(this.distinctValues); } - public void setDistinctValues(@Nullable Collection distinctValues) { + public void setDistinctValues(Collection distinctValues) { if (distinctValues == null) { this.distinctValues = Collections.emptyList(); } else { - this.distinctValues = new ArrayList<>(); + this.distinctValues = new ArrayList(); this.distinctValues.addAll(distinctValues); } } @Override public String toString() { - return "SimpleFieldStatsResult [min=" + getMin() + ", max=" + getMax() + ", sum=" + getSum() + ", mean=" + getMean() - + ", count=" + getCount() + ", missing=" + getMissing() + ", stddev=" + getStddev() + ", statsResults=" - + facetStatsResult + "]"; + return "SimpleFieldStatsResult [min=" + getMin() + ", max=" + getMax() + ", sum=" + getSum() + ", mean=" + + getMean() + ", count=" + getCount() + ", missing=" + getMissing() + ", stddev=" + getStddev() + + ", statsResults=" + facetStatsResult + "]"; } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleGroupResult.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleGroupResult.java index 5fa8ab4..0113853 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SimpleGroupResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleGroupResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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. @@ -65,12 +65,12 @@ public Page> getGroupEntries() { @Override public String toString() { - return // - "SimpleGroupResult [name=" + name + // - ", matches=" + matches + // - ", groupsCount=" + groupsCount + // - ", groupsEntries.total=" + groupEntries.getTotalElements() + // - "]"; + return new StringBuilder() // + .append("SimpleGroupResult [name=").append(name) // + .append(", matches=").append(matches) // + .append(", groupsCount=").append(groupsCount) // + .append(", groupsEntries.total=").append(groupEntries.getTotalElements()) // + .append("]").toString(); } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleStatsResult.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleStatsResult.java index d9bdc85..e3c3904 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SimpleStatsResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleStatsResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -17,7 +17,6 @@ import java.util.Date; -import org.springframework.lang.Nullable; import org.springframework.util.ObjectUtils; /** @@ -29,20 +28,19 @@ */ public class SimpleStatsResult implements StatsResult { - private @Nullable Object min; - private @Nullable Object max; - private @Nullable Object sum; - private @Nullable Object mean; - private @Nullable Long count; - private @Nullable Long missing; - private @Nullable Double stddev; - private @Nullable Double sumOfSquares; + private Object min; + private Object max; + private Object sum; + private Object mean; + private Long count; + private Long missing; + private Double stddev; + private Double sumOfSquares; /* * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMin() */ - @Nullable @Override public Object getMin() { return min; @@ -52,7 +50,6 @@ public Object getMin() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMinAsDate() */ - @Nullable @Override public Date getMinAsDate() { @@ -66,7 +63,6 @@ public Date getMinAsDate() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMinAsDouble() */ - @Nullable @Override public Double getMinAsDouble() { @@ -93,7 +89,6 @@ public void setMin(Object min) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMax() */ - @Nullable @Override public Object getMax() { return max; @@ -103,7 +98,6 @@ public Object getMax() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMaxAsDate() */ - @Nullable @Override public Date getMaxAsDate() { @@ -117,7 +111,6 @@ public Date getMaxAsDate() { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMaxAsDouble() */ - @Nullable @Override public Double getMaxAsDouble() { @@ -144,7 +137,6 @@ public void setMax(Object max) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getSum() */ - @Nullable @Override public Object getSum() { return sum; @@ -158,24 +150,11 @@ public void setSum(Object sum) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMean() */ - @Nullable @Override public Object getMean() { return mean; } - @Nullable - @Override - public Double getMeanAsDouble() { - return mean instanceof Number ? ((Number) mean).doubleValue() : null; - } - - @Nullable - @Override - public Date getMeanAsDate() { - return mean instanceof Date ? (Date) mean : null; - } - public void setMean(Object mean) { this.mean = mean; } @@ -184,7 +163,6 @@ public void setMean(Object mean) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getCount() */ - @Nullable @Override public Long getCount() { return count; @@ -198,7 +176,6 @@ public void setCount(Long count) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getMissing() */ - @Nullable @Override public Long getMissing() { return missing; @@ -212,7 +189,6 @@ public void setMissing(Long missing) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getStddev() */ - @Nullable @Override public Double getStddev() { return stddev; @@ -226,7 +202,6 @@ public void setStddev(Double stddev) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.StatsResult#getSumOfSquares() */ - @Nullable @Override public Double getSumOfSquares() { return this.sumOfSquares; diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java index e5f6688..f1cc4d0 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -32,7 +32,6 @@ import org.springframework.data.solr.core.query.SimpleField; import org.springframework.data.solr.core.query.SimplePivotField; import org.springframework.data.solr.core.query.result.HighlightEntry.Highlight; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -49,28 +48,29 @@ public class SolrResultPage extends PageImpl implements FacetPage, High private static final long serialVersionUID = -4199560685036530258L; - private Map> facetResultPages = new LinkedHashMap<>(1); - private Map> facetPivotResultPages = new LinkedHashMap<>(); - private Map> facetRangeResultPages = new LinkedHashMap<>(1); - private @Nullable Page facetQueryResult; - private List> highlighted = Collections.emptyList(); - private @Nullable Float maxScore; + private Map> facetResultPages = new LinkedHashMap>(1); + private Map> facetPivotResultPages = new LinkedHashMap>(); + private Map> facetRangeResultPages = new LinkedHashMap>( + 1); + private Page facetQueryResult; + private List> highlighted; + private Float maxScore; private Map> groupResults = Collections.emptyMap(); - private Map fieldStatsResults = Collections.emptyMap(); - private Map> suggestions = new LinkedHashMap<>(); + private Map fieldStatsResults; + private Map> suggestions = new LinkedHashMap>(); public SolrResultPage(List content) { super(content); } - public SolrResultPage(List content, Pageable pageable, long total, @Nullable Float maxScore) { + public SolrResultPage(List content, Pageable pageable, long total, Float maxScore) { super(content, pageable, total); this.maxScore = maxScore; } private Page getResultPage(String fieldname, Map> resultPages) { Page page = resultPages.get(new StringPageKey(fieldname)); - return page != null ? page : new PageImpl<>(Collections. emptyList()); + return page != null ? page : new PageImpl(Collections. emptyList()); } @Override @@ -156,13 +156,13 @@ public Collection> getFacetResultPages() { } public final void setFacetQueryResultPage(List facetQueryResult) { - this.facetQueryResult = new PageImpl<>(facetQueryResult); + this.facetQueryResult = new PageImpl(facetQueryResult); } @Override public Page getFacetQueryResult() { return this.facetQueryResult != null ? this.facetQueryResult - : new PageImpl<>(Collections. emptyList()); + : new PageImpl(Collections. emptyList()); } @Override @@ -170,7 +170,7 @@ public Collection getFacetFields() { if (this.facetResultPages.isEmpty()) { return Collections.emptyList(); } - List fields = new ArrayList<>(this.facetResultPages.size()); + List fields = new ArrayList(this.facetResultPages.size()); for (PageKey pageKey : this.facetResultPages.keySet()) { fields.add(new SimpleField(pageKey.getKey().toString())); } @@ -182,7 +182,7 @@ public Collection getFacetPivotFields() { if (this.facetPivotResultPages.isEmpty()) { return Collections.emptyList(); } - List fields = new ArrayList<>(this.facetPivotResultPages.size()); + List fields = new ArrayList(this.facetPivotResultPages.size()); for (PageKey pageKey : this.facetPivotResultPages.keySet()) { fields.add(new SimplePivotField(pageKey.getKey().toString())); @@ -193,7 +193,8 @@ public Collection getFacetPivotFields() { @Override public Collection> getAllFacets() { - List> entries = new ArrayList<>(this.facetResultPages.size() + 1); + List> entries = new ArrayList>( + this.facetResultPages.size() + 1); entries.addAll(this.facetResultPages.values()); entries.add(this.facetQueryResult); return entries; @@ -201,7 +202,7 @@ public Collection> getAllFacets() { @Override public List> getHighlighted() { - return this.highlighted; + return this.highlighted != null ? this.highlighted : Collections.> emptyList(); } public void setHighlighted(List> highlighted) { @@ -210,7 +211,7 @@ public void setHighlighted(List> highlighted) { @Override public List getHighlights(T entity) { - if (entity != null) { + if (entity != null && this.highlighted != null) { for (HighlightEntry highlightEntry : this.highlighted) { if (highlightEntry != null && ObjectUtils.nullSafeEquals(highlightEntry.getEntity(), entity)) { return highlightEntry.getHighlights(); @@ -232,7 +233,6 @@ public void setGroupResults(Map> groupResults) { * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.ScoredPage#getMaxScore() */ - @Nullable @Override public Float getMaxScore() { return maxScore; @@ -263,6 +263,7 @@ public GroupResult getGroupResult(String name) { } /** + * @param fieldStatsResult * @since 1.4 */ public void setFieldStatsResults(Map fieldStatsResults) { @@ -291,7 +292,7 @@ public Map getFieldStatsResults() { @Override public Collection getSuggestions(String term) { - List suggestions = new ArrayList<>(); + List suggestions = new ArrayList(); for (Alternative alternative : getAlternatives(term)) { suggestions.add(alternative.getSuggestion()); } @@ -305,7 +306,7 @@ public Collection getSuggestions(String term) { @Override public Collection getSuggestions() { - List suggestions = new ArrayList<>(); + List suggestions = new ArrayList(); for (Alternative alternative : getAlternatives()) { suggestions.add(alternative.getSuggestion()); } @@ -328,7 +329,7 @@ public void addSuggestions(String term, List suggestions) { @Override public Collection getAlternatives() { - List allSuggestions = new ArrayList<>(); + List allSuggestions = new ArrayList(); for (List suggestions : this.suggestions.values()) { allSuggestions.addAll(suggestions); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java b/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java index 5910e3f..3efb9d0 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -63,41 +63,11 @@ public interface SpellcheckQueryResult { * @since 2.1 */ @Data - class Alternative { + public static class Alternative { private final String term; private final int termFrequency; private final String suggestion; private final int suggestionFrequency; - - - public Alternative(String term, int termFrequency, String suggestion, int suggestionFrequency) { - super(); - this.term = term; - this.termFrequency = termFrequency; - this.suggestion = suggestion; - this.suggestionFrequency = suggestionFrequency; - } - - - public String getTerm() { - return term; - } - - - public int getTermFrequency() { - return termFrequency; - } - - - public String getSuggestion() { - return suggestion; - } - - - public int getSuggestionFrequency() { - return suggestionFrequency; - } - } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/StatsResult.java b/src/main/java/org/springframework/data/solr/core/query/result/StatsResult.java index e836a02..60ac9b3 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/StatsResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/StatsResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -17,8 +17,6 @@ import java.util.Date; -import org.springframework.lang.Nullable; - /** * Contract to define representation of statistic information requested using * {@link org.springframework.data.solr.core.query.StatsOptions}. @@ -31,19 +29,16 @@ public interface StatsResult { /** * @return minimum value */ - @Nullable Object getMin(); /** * @return minimum value as {@link Double}, {@code null} will be returned when not {@link Number} */ - @Nullable Double getMinAsDouble(); /** * @return minimum value as {@link Date}, {@code null} will be returned when not {@link Date} */ - @Nullable Date getMinAsDate(); /** @@ -54,19 +49,16 @@ public interface StatsResult { /** * @return maximum value */ - @Nullable Object getMax(); /** * @return maximum value as {@link Double}, {@code null} will be returned when not {@link Number} */ - @Nullable Double getMaxAsDouble(); /** * @return maximum value as {@link Date}, {@code null} will be returned when not {@link Date} */ - @Nullable Date getMaxAsDate(); /** @@ -77,51 +69,31 @@ public interface StatsResult { /** * @return sum of all values */ - @Nullable Object getSum(); /** * @return average */ - @Nullable Object getMean(); - /** - * @return mean value as {@link Double}, {@code null} will be returned when not {@link Number}. - * @since 3.0 - */ - @Nullable - Double getMeanAsDouble(); - - /** - * @return mean value as {@link Date}, {@code null} will be returned when not {@link Date}. - * @since 3.0 - */ - @Nullable - Date getMeanAsDate(); - /** * @return number of non-null values */ - @Nullable Long getCount(); /** * @return number of null values */ - @Nullable Long getMissing(); /** * @return standard deviation */ - @Nullable Double getStddev(); /** * @return sum of squares */ - @Nullable Double getSumOfSquares(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/StringPageKey.java b/src/main/java/org/springframework/data/solr/core/query/result/StringPageKey.java index d74a351..db986fd 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/StringPageKey.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/StringPageKey.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. diff --git a/src/main/java/org/springframework/data/solr/core/query/result/TermsPage.java b/src/main/java/org/springframework/data/solr/core/query/result/TermsPage.java index a2bb368..aee9318 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/TermsPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/TermsPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -21,6 +21,8 @@ /** * @author Christoph Strobl + * + * @param */ public interface TermsPage extends Iterable { @@ -32,6 +34,7 @@ public interface TermsPage extends Iterable { Iterable getContent(); /** + * * @param fieldname * @return */ diff --git a/src/main/java/org/springframework/data/solr/core/query/result/TermsResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/TermsResultPage.java index 1553110..ffebdee 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/TermsResultPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/TermsResultPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -29,10 +29,12 @@ /** * @author Christoph Strobl + * */ public class TermsResultPage implements TermsPage { - private Map> termsMap = new LinkedHashMap<>(1); + private Map> termsMap = new LinkedHashMap>( + 1); public final void addTermsResult(List entries, Field field) { Assert.notNull(field, "Cannot add terms for 'null' field."); @@ -66,7 +68,7 @@ public Collection getTermsFields() { return Collections.emptyList(); } - List fields = new ArrayList<>(this.termsMap.size()); + List fields = new ArrayList(this.termsMap.size()); for (StringPageKey pageKey : this.termsMap.keySet()) { fields.add(new SimpleField(pageKey.getKey())); } @@ -80,7 +82,7 @@ public Iterator iterator() { @Override public List getContent() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (List entries : termsMap.values()) { values.addAll(entries); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/package-info.java b/src/main/java/org/springframework/data/solr/core/query/result/package-info.java deleted file mode 100644 index 8716b72..0000000 --- a/src/main/java/org/springframework/data/solr/core/query/result/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Query result abstractions for Solr returned {@link org.apache.solr.common.util.NamedList}. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.core.query.result; diff --git a/src/main/java/org/springframework/data/solr/core/schema/DefaultSchemaOperations.java b/src/main/java/org/springframework/data/solr/core/schema/DefaultSchemaOperations.java index 7662767..e5edb0c 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/DefaultSchemaOperations.java +++ b/src/main/java/org/springframework/data/solr/core/schema/DefaultSchemaOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -15,11 +15,15 @@ */ package org.springframework.data.solr.core.schema; +import java.io.IOException; import java.util.Map; +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.schema.SchemaRepresentation; import org.apache.solr.client.solrj.response.schema.SchemaResponse.UpdateResponse; +import org.springframework.data.solr.core.CollectionCallback; import org.springframework.data.solr.core.SolrTemplate; import org.springframework.data.solr.core.schema.SchemaDefinition.CopyFieldDefinition; import org.springframework.data.solr.core.schema.SchemaDefinition.FieldDefinition; @@ -54,8 +58,13 @@ public DefaultSchemaOperations(String collection, SolrTemplate template) { @Override public String getSchemaName() { - return template - .execute(solrClient -> new SchemaRequest.SchemaName().process(solrClient, collection).getSchemaName()); + return template.execute(collection, new CollectionCallback() { + + @Override + public String doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return new SchemaRequest.SchemaName().process(solrClient, collection).getSchemaName(); + } + }); } @@ -65,8 +74,13 @@ public String getSchemaName() { */ @Override public Double getSchemaVersion() { - return template.execute( - solrClient -> new Double(new SchemaRequest.SchemaVersion().process(solrClient, collection).getSchemaVersion())); + return template.execute(collection, new CollectionCallback() { + + @Override + public Double doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { + return new Double(new SchemaRequest.SchemaVersion().process(solrClient, collection).getSchemaVersion()); + } + }); } /* @@ -76,8 +90,14 @@ public Double getSchemaVersion() { @Override public SchemaDefinition readSchema() { - SchemaRepresentation representation = template - .execute(solrClient -> new SchemaRequest().process(solrClient, collection).getSchemaRepresentation()); + SchemaRepresentation representation = template.execute(collection, new CollectionCallback() { + + @Override + public SchemaRepresentation doInSolr(SolrClient solrClient, String collection) + throws SolrServerException, IOException { + return new SchemaRequest().process(solrClient, collection).getSchemaRepresentation(); + } + }); SchemaDefinition sd = new SchemaDefinition(collection); @@ -113,15 +133,19 @@ public void addField(final SchemaField field) { private void addField(final FieldDefinition field) { - template.execute(solrClient -> { + template.execute(collection, new CollectionCallback() { + + @Override + public Integer doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { - UpdateResponse response = new SchemaRequest.AddField(field.asMap()).process(solrClient, collection); - if (hasErrors(response)) { - throw new SchemaModificationException( - String.format("Adding field %s with args %s to collection %s failed with status %s. Server returned %s.", - field.getName(), field.asMap(), collection, response.getStatus(), response)); + UpdateResponse response = new SchemaRequest.AddField(field.asMap()).process(solrClient, collection); + if (hasErrors(response)) { + throw new SchemaModificationException( + String.format("Adding field %s with args %s to collection %s failed with status %s. Server returned %s.", + field.getName(), field.asMap(), collection, response.getStatus(), response)); + } + return Integer.valueOf(response.getStatus()); } - return Integer.valueOf(response.getStatus()); }); if (!CollectionUtils.isEmpty(field.getCopyFields())) { @@ -136,18 +160,22 @@ private void addField(final FieldDefinition field) { private void addCopyField(final CopyFieldDefinition field) { - template.execute(solrClient -> { + template.execute(collection, new CollectionCallback() { - UpdateResponse response = new SchemaRequest.AddCopyField(field.getSource(), field.getDestination()) - .process(solrClient, collection); + @Override + public Integer doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { - if (hasErrors(response)) { - throw new SchemaModificationException(String.format( - "Adding copy field %s with destinations %s to collection %s failed with status %s. Server returned %s.", - field.getSource(), field.getDestination(), collection, response.getStatus(), response)); - } + UpdateResponse response = new SchemaRequest.AddCopyField(field.getSource(), field.getDestination()) + .process(solrClient, collection); + + if (hasErrors(response)) { + throw new SchemaModificationException(String.format( + "Adding copy field %s with destinations %s to collection %s failed with status %s. Server returned %s.", + field.getSource(), field.getDestination(), collection, response.getStatus(), response)); + } - return Integer.valueOf(response.getStatus()); + return Integer.valueOf(response.getStatus()); + } }); } @@ -158,16 +186,20 @@ private void addCopyField(final CopyFieldDefinition field) { @Override public void removeField(final String name) { - template.execute(solrClient -> { + template.execute(collection, new CollectionCallback() { - UpdateResponse response = new SchemaRequest.DeleteField(name).process(solrClient, collection); - if (hasErrors(response)) { - throw new SchemaModificationException( - String.format("Removing field with name %s from collection %s failed with status %s. Server returned %s.", - name, collection, response.getStatus(), response)); - } + @Override + public Integer doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { - return Integer.valueOf(response.getStatus()); + UpdateResponse response = new SchemaRequest.DeleteField(name).process(solrClient, collection); + if (hasErrors(response)) { + throw new SchemaModificationException( + String.format("Removing field with name %s from collection %s failed with status %s. Server returned %s.", + name, collection, response.getStatus(), response)); + } + + return Integer.valueOf(response.getStatus()); + } }); } diff --git a/src/main/java/org/springframework/data/solr/core/schema/MappingJacksonResponseParser.java b/src/main/java/org/springframework/data/solr/core/schema/MappingJacksonResponseParser.java index 174e8e7..853f603 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/MappingJacksonResponseParser.java +++ b/src/main/java/org/springframework/data/solr/core/schema/MappingJacksonResponseParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -26,7 +26,6 @@ import org.apache.solr.client.solrj.ResponseParser; import org.apache.solr.common.util.NamedList; import org.springframework.dao.InvalidDataAccessResourceUsageException; -import org.springframework.lang.Nullable; import org.springframework.util.StreamUtils; /** @@ -43,7 +42,7 @@ public MappingJacksonResponseParser() { this(defaultMimeType()); } - public MappingJacksonResponseParser(@Nullable MimeType responseType) { + public MappingJacksonResponseParser(MimeType responseType) { this.responseType = responseType != null ? responseType : defaultMimeType(); } @@ -65,7 +64,7 @@ public String getVersion() { @Override public NamedList processResponse(InputStream body, String encoding) { - NamedList result = new NamedList<>(); + NamedList result = new NamedList(); try { result.add("json", StreamUtils.copyToString(body, Charset.forName(encoding))); } catch (IOException e) { diff --git a/src/main/java/org/springframework/data/solr/core/schema/SchemaDefinition.java b/src/main/java/org/springframework/data/solr/core/schema/SchemaDefinition.java index b42ffd2..a3b6c89 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SchemaDefinition.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SchemaDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-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. @@ -15,9 +15,6 @@ */ package org.springframework.data.solr.core.schema; -import lombok.Data; -import lombok.NoArgsConstructor; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -26,31 +23,32 @@ import java.util.List; import java.util.Map; -import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; +import lombok.Data; +import lombok.NoArgsConstructor; + /** * @author Christoph Strobl * @since 1.3 */ public class SchemaDefinition { - private @Nullable String collectionName; - private List fields = new ArrayList<>(); - private List copyFields = new ArrayList<>(); - private @Nullable String name; - private @Nullable Double version; - private @Nullable String uniqueKey; + private String collectionName; + private List fields; + private List copyFields; + private String name; + private Double version; + private String uniqueKey; public SchemaDefinition() {} public SchemaDefinition(String collectionName) { this.collectionName = collectionName; - this.fields = new ArrayList<>(); + this.fields = new ArrayList(); } - @Nullable public String getCollectionName() { return collectionName; } @@ -59,11 +57,10 @@ public List getFields() { return fields; } - public void setFields(@Nullable List fields) { - this.fields = fields != null ? fields : new ArrayList<>(); + public void setFields(List fields) { + this.fields = fields != null ? fields : new ArrayList(); } - @Nullable public String getName() { return name; } @@ -72,7 +69,6 @@ public void setName(String name) { this.name = name; } - @Nullable public Double getVersion() { return version; } @@ -81,7 +77,6 @@ public void setVersion(Double version) { this.version = version; } - @Nullable public String getUniqueKey() { return uniqueKey; } @@ -94,7 +89,6 @@ public boolean containsField(String name) { return getFieldDefinition(name) != null; } - @Nullable public FieldDefinition getFieldDefinition(String name) { if (CollectionUtils.isEmpty(this.fields)) { @@ -111,10 +105,18 @@ public FieldDefinition getFieldDefinition(String name) { } public void addFieldDefinition(FieldDefinition fieldDef) { + + if (this.fields == null) { + this.fields = new ArrayList(); + } this.fields.add(fieldDef); } public void addCopyField(CopyFieldDefinition copyField) { + + if (this.copyFields == null) { + this.copyFields = new ArrayList(); + } this.copyFields.add(copyField); } @@ -130,7 +132,7 @@ public void setCollectionName(String collectionName) { * @author Christoph Strobl * @since 1.3 */ - public interface SchemaField {} + public static interface SchemaField {} /** * @author Christoph Strobl @@ -140,14 +142,14 @@ public interface SchemaField {} @NoArgsConstructor public static class FieldDefinition implements SchemaField { - private @Nullable String name; - private @Nullable String type; + private String name; + private String type; private boolean stored; private boolean indexed; - private @Nullable Object defaultValue; - private List copyFields = Collections.emptyList(); - private List filters = Collections.emptyList(); - private List tokenizers = Collections.emptyList(); + private Object defaultValue; + private List copyFields; + private List filters; + private List tokenizers; private boolean multiValued; private boolean required; @@ -156,7 +158,7 @@ public FieldDefinition(String name) { } public void setCopyFields(Collection copyFields) { - this.copyFields = new ArrayList<>(copyFields); + this.copyFields = new ArrayList(copyFields); } /** @@ -165,7 +167,7 @@ public void setCopyFields(Collection copyFields) { */ public Map asMap() { - Map values = new LinkedHashMap<>(); + Map values = new LinkedHashMap(); addIfNotNull("name", name, values); addIfNotNull("type", type, values); addIfNotNull("indexed", indexed, values); @@ -176,7 +178,7 @@ public Map asMap() { return values; } - private void addIfNotNull(String key, @Nullable Object value, Map dest) { + private void addIfNotNull(String key, Object value, Map dest) { if (value != null) { dest.put(key, value); } @@ -203,7 +205,7 @@ public static FieldDefinition fromMap(Map source) { return fd; } - private static T valueFromMap(String key, Map source, @Nullable T defaultValue) { + private static T valueFromMap(String key, Map source, T defaultValue) { if (source.containsKey(key)) { return (T) source.get(key); @@ -277,8 +279,6 @@ public FieldDefinition create() { public static Builder newFieldDefinition() { return new Builder(); } - - } @@ -289,8 +289,8 @@ public static Builder newFieldDefinition() { @Data public static class CopyFieldDefinition implements SchemaField { - @Nullable String source; - List destination = Collections.emptyList(); + String source; + List destination; public static CopyFieldDefinition fromMap(Map fieldValueMap) { @@ -299,11 +299,9 @@ public static CopyFieldDefinition fromMap(Map fieldValueMap) { Object dest = fieldValueMap.get("dest"); if (dest instanceof Collection) { - cfd.destination = new ArrayList<>((Collection) dest); + cfd.destination = new ArrayList((Collection) dest); } else if (fieldValueMap.get("dest") instanceof String) { - cfd.destination = Collections.singletonList(dest.toString()); - } else { - cfd.destination = Collections.emptyList(); + cfd.destination = Collections. singletonList(dest.toString()); } return cfd; @@ -339,7 +337,7 @@ public Builder to(String... destinations) { if (cf.getDestination() == null) { cf.setDestination(Arrays.asList(destinations)); } else { - ArrayList values = new ArrayList<>(cf.getDestination()); + ArrayList values = new ArrayList(cf.getDestination()); CollectionUtils.mergeArrayIntoCollection(destinations, values); cf.setDestination(values); } @@ -358,10 +356,10 @@ public CopyFieldDefinition create() { */ public static class Filter { - @Nullable String clazz; - @Nullable String pattern; - @Nullable String replace; - @Nullable String replacement; + String clazz; + String pattern; + String replace; + String replacement; } /** @@ -370,7 +368,7 @@ public static class Filter { */ public static class Tokenizer { - @Nullable String clazz; + String clazz; } public static class FieldDefinitionBuilder { diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrJsonRequest.java b/src/main/java/org/springframework/data/solr/core/schema/SolrJsonRequest.java index e891620..c0d9f7c 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SolrJsonRequest.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrJsonRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 - 2017 the original author or authors. + * Copyright 2014 - 2015 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. @@ -28,7 +28,6 @@ import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.ContentStream; -import org.springframework.lang.Nullable; import org.springframework.util.StreamUtils; /** @@ -40,8 +39,8 @@ public class SolrJsonRequest extends SolrRequest { private static final long serialVersionUID = 5786008418321490550L; private ModifiableSolrParams params = new ModifiableSolrParams(); - private List contentStream = Collections.emptyList(); - private @Nullable ContentParser contentParser; + private List contentStream = null; + private ContentParser contentParser; public SolrJsonRequest(METHOD method, String path) { super(method, path); @@ -49,11 +48,10 @@ public SolrJsonRequest(METHOD method, String path) { setContentParser(new MappingJacksonRequestContentParser()); } - private void setContentParser(@Nullable ContentParser requestParser) { + private void setContentParser(ContentParser requestParser) { this.contentParser = requestParser != null ? requestParser : new MappingJacksonRequestContentParser(); } - @Nullable public ContentParser getContentParser() { return this.contentParser; } @@ -65,18 +63,27 @@ public SolrParams getParams() { @Override public Collection getContentStreams() throws IOException { - return Collections.unmodifiableCollection(contentStream); + return contentStream != null ? Collections. unmodifiableCollection(contentStream) : null; } public void addContentToStream(Object content) { - contentStream = new ArrayList<>(contentStream); + if (contentStream == null) { + this.contentStream = new ArrayList(); + } + contentStream.add(getContentParser().parse(content)); } @Override public String toString() { - return getMethod().toString() + " " + getPath() + "\r\n" + quietlyReadContentStreams(); + StringBuilder sb = new StringBuilder(getMethod().toString()); + sb.append(" "); + sb.append(getPath()); + sb.append("\r\n"); + sb.append(quietlyReadContentStreams()); + + return sb.toString(); } private String quietlyReadContentStreams() { diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrJsonResponse.java b/src/main/java/org/springframework/data/solr/core/schema/SolrJsonResponse.java index 58f986e..bb5f9c7 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SolrJsonResponse.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrJsonResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-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. @@ -18,7 +18,6 @@ import org.apache.solr.client.solrj.response.SolrResponseBase; import org.apache.solr.common.util.NamedList; import org.springframework.dao.InvalidDataAccessResourceUsageException; -import org.springframework.lang.Nullable; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -32,7 +31,7 @@ public class SolrJsonResponse extends SolrResponseBase { private static final long serialVersionUID = 5727953031460362404L; - private @Nullable JsonNode root; + private JsonNode root; private ObjectMapper mapper; public SolrJsonResponse() { @@ -66,7 +65,6 @@ public void setResponse(NamedList response) { } } - @Nullable public String getJsonResponse() { return (String) getResponse().get("json"); } diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrPersistentEntitySchemaCreator.java b/src/main/java/org/springframework/data/solr/core/schema/SolrPersistentEntitySchemaCreator.java index e38fbf4..073cf5f 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SolrPersistentEntitySchemaCreator.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrPersistentEntitySchemaCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2015 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,7 +24,6 @@ import org.springframework.data.mapping.context.MappingContextEvent; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.server.SolrClientFactory; -import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; /** @@ -34,7 +33,7 @@ public class SolrPersistentEntitySchemaCreator implements ApplicationListener> { public enum Feature { - CREATE_MISSING_FIELDS + CREATE_MISSING_FIELDS; } private SolrClientFactory factory; @@ -42,18 +41,18 @@ public enum Feature { private SolrSchemaResolver schemaResolver; private ConcurrentHashMap, Class> processed; - private Set features = new HashSet<>(); + private Set features = new HashSet(); public SolrPersistentEntitySchemaCreator(SolrClientFactory solrClientFactory) { this(solrClientFactory, null); } - public SolrPersistentEntitySchemaCreator(SolrClientFactory factory, @Nullable SolrSchemaWriter schemaWriter) { + public SolrPersistentEntitySchemaCreator(SolrClientFactory factory, SolrSchemaWriter schemaWriter) { super(); this.factory = factory; this.schemaWriter = schemaWriter != null ? schemaWriter : new SolrSchemaWriter(this.factory); this.schemaResolver = new SolrSchemaResolver(); - this.processed = new ConcurrentHashMap<>(); + this.processed = new ConcurrentHashMap, Class>(); } private void process(SolrPersistentEntity entity) { @@ -87,7 +86,7 @@ public void onApplicationEvent(MappingContextEvent event) { } } - public SolrPersistentEntitySchemaCreator enable(@Nullable Feature feature) { + public SolrPersistentEntitySchemaCreator enable(Feature feature) { if (feature != null) { this.features.add(feature); diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaRequest.java b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaRequest.java new file mode 100644 index 0000000..ed21dae --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaRequest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2014-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.solr.core.schema; + +import java.text.MessageFormat; +import java.util.Collection; + +import org.springframework.data.solr.core.schema.SchemaDefinition.FieldDefinition; +import org.springframework.util.CollectionUtils; + +/** + * @author Christoph Strobl + * @since 1.3 + * @deprecated since 2.1. Use {@link org.apache.solr.client.solrj.request.schema.SchemaRequest} instead. + */ +@Deprecated +public class SolrSchemaRequest extends SolrJsonRequest { + + private static final long serialVersionUID = 483080361035195746L; + + public SolrSchemaRequest(METHOD method, String path) { + super(method, path); + } + + public static SolrSchemaRequest version() { + return new SolrSchemaRequestBuilder().forVersion().build(); + } + + public static SolrSchemaRequest schema() { + return new SolrSchemaRequestBuilder().schema().build(); + } + + public static SolrSchemaRequestBuilder create() { + return new SolrSchemaRequestBuilder().create(); + } + + public static SolrSchemaRequest name() { + return new SolrSchemaRequestBuilder().forName().build(); + } + + // -- static + public static class SolrSchemaRequestBuilder { + + private static final String PATH_PATTERN = "/schema/{0}"; + private String command; + private METHOD method; + private Collection newFields; + + public SolrSchemaRequestBuilder schema() { + + method = METHOD.GET; + command = ""; + return this; + } + + public SolrSchemaRequestBuilder forName() { + schema(); + command = "name"; + return this; + } + + public SolrSchemaRequestBuilder forVersion() { + + method = METHOD.GET; + command = "version"; + return this; + } + + public SolrSchemaRequestBuilder create() { + method = METHOD.POST; + return this; + } + + public SolrSchemaRequestBuilder fields(Collection fields) { + command = "fields"; + newFields = fields; + return this; + } + + public SolrSchemaRequest build() { + + String path = buildRequestPath(); + SolrSchemaRequest request = new SolrSchemaRequest(method, path); + + if (!CollectionUtils.isEmpty(newFields)) { + request.addContentToStream(newFields); + } + return request; + } + + private String buildRequestPath() { + return MessageFormat.format(PATH_PATTERN, command); + } + + } + +} diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaResolver.java b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaResolver.java index f9d9073..57b8b74 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaResolver.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -21,7 +21,6 @@ import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; import org.springframework.data.solr.core.schema.SchemaDefinition.FieldDefinition; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -35,21 +34,24 @@ public SchemaDefinition resolveSchemaForEntity(SolrPersistentEntity entity) { Assert.notNull(entity, "Schema cannot be resolved for 'null'."); - final SchemaDefinition schemaDefinition = new SchemaDefinition(entity.getCollectionName()); + final SchemaDefinition schemaDefinition = new SchemaDefinition(entity.getSolrCoreName()); - entity.doWithProperties((PropertyHandler) persistentProperty -> { + entity.doWithProperties(new PropertyHandler() { - FieldDefinition fieldDefinition = createFieldDefinitionForProperty(persistentProperty); - if (fieldDefinition != null) { - schemaDefinition.addFieldDefinition(fieldDefinition); + @Override + public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) { + + FieldDefinition fieldDefinition = createFieldDefinitionForProperty(persistentProperty); + if (fieldDefinition != null) { + schemaDefinition.addFieldDefinition(fieldDefinition); + } } }); return schemaDefinition; } - @Nullable - protected FieldDefinition createFieldDefinitionForProperty(@Nullable SolrPersistentProperty property) { + protected FieldDefinition createFieldDefinitionForProperty(SolrPersistentProperty property) { if (property == null || property.isReadonly() || property.isTransient()) { return null; diff --git a/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaWriter.java b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaWriter.java index 342ed23..9b31803 100644 --- a/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaWriter.java +++ b/src/main/java/org/springframework/data/solr/core/schema/SolrSchemaWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-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. @@ -54,7 +54,7 @@ protected void updateSchema(SchemaDefinition schemaDefinition) { SchemaDefinition existing = loadExistingSchema(schemaDefinition.getCollectionName()); - List fieldsToBeCreated = new ArrayList<>(); + List fieldsToBeCreated = new ArrayList(); for (FieldDefinition fieldDefinition : schemaDefinition.getFields()) { if (!existing.containsField(fieldDefinition.getName())) diff --git a/src/main/java/org/springframework/data/solr/core/schema/package-info.java b/src/main/java/org/springframework/data/solr/core/schema/package-info.java deleted file mode 100644 index 1b2f527..0000000 --- a/src/main/java/org/springframework/data/solr/core/schema/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Everything Apache Solr schema specific. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.core.schema; diff --git a/src/main/java/org/springframework/data/solr/package-info.java b/src/main/java/org/springframework/data/solr/package-info.java deleted file mode 100644 index 8674dc8..0000000 --- a/src/main/java/org/springframework/data/solr/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Root stuff used through out Spring Data for Apache Solr. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr; diff --git a/src/main/java/org/springframework/data/solr/repository/Query.java b/src/main/java/org/springframework/data/solr/repository/Query.java index 5d0327d..9b8d80a 100644 --- a/src/main/java/org/springframework/data/solr/repository/Query.java +++ b/src/main/java/org/springframework/data/solr/repository/Query.java @@ -93,7 +93,5 @@ * @since 1.2 */ boolean delete() default false; - - String rqqValue() default ""; } diff --git a/src/main/java/org/springframework/data/solr/repository/SelectiveStats.java b/src/main/java/org/springframework/data/solr/repository/SelectiveStats.java index 458283f..5b27e56 100644 --- a/src/main/java/org/springframework/data/solr/repository/SelectiveStats.java +++ b/src/main/java/org/springframework/data/solr/repository/SelectiveStats.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -26,16 +26,16 @@ /** * @return field name to which the selective stats are associated to */ - String field(); + public String field(); /** * @return fields to be facet within this stats field request */ - String[] facets(); + public String[] facets(); /** * @return if distinct elements for this field shall be calculated */ - boolean distinct() default false; + public boolean distinct() default false; } diff --git a/src/main/java/org/springframework/data/solr/repository/Stats.java b/src/main/java/org/springframework/data/solr/repository/Stats.java index 12bd15d..f799fdb 100644 --- a/src/main/java/org/springframework/data/solr/repository/Stats.java +++ b/src/main/java/org/springframework/data/solr/repository/Stats.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014 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. @@ -35,21 +35,21 @@ /** * @return fields that shall have its statistics returned. */ - String[] value() default {}; + public String[] value() default {}; /** * @return faceting that shall be returned within statistics result. */ - String[] facets() default {}; + public String[] facets() default {}; /** * @return if distinct elements shall be calculated */ - boolean distinct() default false; + public boolean distinct() default false; /** * @return field selective stats parameters. */ - SelectiveStats[] selective() default {}; + public SelectiveStats[] selective() default {}; } diff --git a/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryBean.java b/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryBean.java index 04e252d..9d9e7cc 100644 --- a/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryBean.java +++ b/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryBean.java @@ -16,7 +16,6 @@ package org.springframework.data.solr.repository.cdi; import java.lang.annotation.Annotation; -import java.util.Optional; import java.util.Set; import javax.enterprise.context.spi.CreationalContext; @@ -51,7 +50,7 @@ public class SolrRepositoryBean extends CdiRepositoryBean { * {@link CustomRepositoryImplementationDetector}, can be {@literal null}. */ public SolrRepositoryBean(Bean operations, Set qualifiers, Class repositoryType, - BeanManager beanManager, Optional detector) { + BeanManager beanManager, CustomRepositoryImplementationDetector detector) { super(qualifiers, repositoryType, beanManager, detector); Assert.notNull(operations, "Cannot create repository with 'null' for SolrOperations."); @@ -59,17 +58,13 @@ public SolrRepositoryBean(Bean operations, Set quali } /* - * (non-Javadoc) - * @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.lang.Object) - */ + * (non-Javadoc) + * @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.lang.Object) + */ @Override - protected T create(CreationalContext creationalContext, Class repositoryType, - Optional customImplementation) { + protected T create(CreationalContext creationalContext, Class repositoryType, Object customImplementation) { SolrOperations solrOperations = getDependencyInstance(solrOperationsBean, SolrOperations.class); - - return customImplementation.isPresent() - ? new SolrRepositoryFactory(solrOperations).getRepository(repositoryType, customImplementation.get()) - : new SolrRepositoryFactory(solrOperations).getRepository(repositoryType); + return new SolrRepositoryFactory(solrOperations).getRepository(repositoryType, customImplementation); } /* diff --git a/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryExtension.java b/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryExtension.java index f35a74b..e6c8684 100644 --- a/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryExtension.java +++ b/src/main/java/org/springframework/data/solr/repository/cdi/SolrRepositoryExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2014 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,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.Optional; import java.util.Set; import javax.enterprise.event.Observes; @@ -39,7 +38,7 @@ */ public class SolrRepositoryExtension extends CdiRepositoryExtensionSupport { - private final Map> solrOperationsMap = new HashMap<>(); + private final Map> solrOperationsMap = new HashMap>(); @SuppressWarnings("unchecked") void processBean(@Observes ProcessBean processBean) { @@ -62,8 +61,7 @@ void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanMan } } - private Bean createRepositoryBean(Class repositoryType, Set qualifiers, - BeanManager beanManager) { + private Bean createRepositoryBean(Class repositoryType, Set qualifiers, BeanManager beanManager) { Bean solrOperationBeans = this.solrOperationsMap.get(qualifiers.toString()); if (solrOperationBeans == null) { @@ -71,8 +69,8 @@ private Bean createRepositoryBean(Class repositoryType, Set(solrOperationBeans, qualifiers, repositoryType, beanManager, - Optional.ofNullable(getCustomImplementationDetector())); + return new SolrRepositoryBean(solrOperationBeans, qualifiers, repositoryType, beanManager, + getCustomImplementationDetector()); } } diff --git a/src/main/java/org/springframework/data/solr/repository/cdi/package-info.java b/src/main/java/org/springframework/data/solr/repository/cdi/package-info.java deleted file mode 100644 index 0369ea6..0000000 --- a/src/main/java/org/springframework/data/solr/repository/cdi/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Cdi extension. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.repository.cdi; diff --git a/src/main/java/org/springframework/data/solr/repository/config/AbstractSolrConfiguration.java b/src/main/java/org/springframework/data/solr/repository/config/AbstractSolrConfiguration.java deleted file mode 100644 index 015d28c..0000000 --- a/src/main/java/org/springframework/data/solr/repository/config/AbstractSolrConfiguration.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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.solr.repository.config; - -import java.util.Collection; -import java.util.Collections; - -import org.apache.solr.client.solrj.SolrClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.convert.CustomConversions; -import org.springframework.data.mapping.context.MappingContext; -import org.springframework.data.solr.core.RequestMethod; -import org.springframework.data.solr.core.SolrTemplate; -import org.springframework.data.solr.core.convert.MappingSolrConverter; -import org.springframework.data.solr.core.convert.SolrConverter; -import org.springframework.data.solr.core.convert.SolrCustomConversions; -import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext; -import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator; -import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator.Feature; -import org.springframework.data.solr.server.SolrClientFactory; - -/** - * Spring Data for Apache Solr base configuration using JavaConfig. - * - * @author Christoph Strobl - * @author Mark Paluch - * @since 3.0 - */ -@Configuration -public abstract class AbstractSolrConfiguration { - - /** - * {@link SolrTemplate} setup to provide {@link org.springframework.data.solr.core.SolrOperations} implementation - * picking up {@link #solrClientFactory}, {@link #solrConverter()} and {@link #defaultRequestMethod()}. - * - * @return - */ - @Bean - public SolrTemplate solrTemplate() { - return new SolrTemplate(solrClientFactory(), solrConverter(), defaultRequestMethod()); - } - - /** - * @return {@link MappingSolrConverter} picking up {@link #customConversions()} by default. - */ - @Bean - public SolrConverter solrConverter() { - - MappingSolrConverter solrConverter = new MappingSolrConverter(solrMappingContext()); - solrConverter.setCustomConversions(customConversions()); - return solrConverter; - } - - /** - * @return {@link SimpleSolrMappingContext} picking up {@link #solrClientFactory()} and {@link #schemaSupport()} by - * default. - */ - @Bean - protected MappingContext solrMappingContext() { - - return new SimpleSolrMappingContext( - new SolrPersistentEntitySchemaCreator(solrClientFactory()).enable(schemaSupport())); - } - - /** - * Define the {@link SolrClientFactory} to be used.
- * Unless you use an {@link org.apache.solr.client.solrj.embedded.EmbeddedSolrServer} simply - * {@code () -> new HttpSolrClient("...")} should be sufficient. - * - * @return Never {@literal null}. - */ - @Bean - public abstract SolrClientFactory solrClientFactory(); - - /** - * {@link CustomConversions} to be applied by mapping. - * - * @return CustomConversions by default. Never {@literal null}. - */ - protected CustomConversions customConversions() { - return new SolrCustomConversions(Collections.emptyList()); - } - - /** - * Default {@link RequestMethod} to be used when sending requests via {@link SolrClient}. - * - * @return {@link RequestMethod#GET} by default. Never {@literal null}. - */ - protected RequestMethod defaultRequestMethod() { - return RequestMethod.GET; - } - - /** - * Define schema setup {@link Feature}s. - * - * @return empty {@link java.util.Set} by default. Never {@literal null}. - */ - protected Collection schemaSupport() { - return Collections.emptySet(); - } -} diff --git a/src/main/java/org/springframework/data/solr/repository/config/EnableSolrRepositories.java b/src/main/java/org/springframework/data/solr/repository/config/EnableSolrRepositories.java index dd63dda..d882f91 100644 --- a/src/main/java/org/springframework/data/solr/repository/config/EnableSolrRepositories.java +++ b/src/main/java/org/springframework/data/solr/repository/config/EnableSolrRepositories.java @@ -132,6 +132,13 @@ */ String solrClientRef() default "solrClient"; + /** + * Configures Multicore support for Solr Server + * + * @since 1.1 + */ + boolean multicoreSupport() default false; + /** * Configure schema creation support using the solr schema api. * diff --git a/src/main/java/org/springframework/data/solr/repository/config/SolrRepositoryConfigExtension.java b/src/main/java/org/springframework/data/solr/repository/config/SolrRepositoryConfigExtension.java index 4d8f4a9..c8085c9 100644 --- a/src/main/java/org/springframework/data/solr/repository/config/SolrRepositoryConfigExtension.java +++ b/src/main/java/org/springframework/data/solr/repository/config/SolrRepositoryConfigExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -21,13 +21,11 @@ import java.util.Collections; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource; @@ -36,35 +34,31 @@ import org.springframework.data.repository.config.RepositoryConfigurationSource; import org.springframework.data.repository.config.XmlRepositoryConfigurationSource; import org.springframework.data.solr.core.SolrExceptionTranslator; -import org.springframework.data.solr.core.SolrOperations; -import org.springframework.data.solr.core.SolrTemplate; +import org.springframework.data.solr.core.convert.CustomConversions; import org.springframework.data.solr.core.convert.MappingSolrConverter; -import org.springframework.data.solr.core.convert.SolrCustomConversions; import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext; import org.springframework.data.solr.core.mapping.SolrDocument; import org.springframework.data.solr.repository.SolrCrudRepository; import org.springframework.data.solr.repository.SolrRepository; import org.springframework.data.solr.repository.support.SolrRepositoryFactoryBean; -import org.springframework.data.solr.server.support.HttpSolrClientFactory; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * {@link RepositoryConfigurationExtension} implementation to configure Solr repository configuration support, * evaluating the {@link EnableSolrRepositories} annotation or the equivalent XML element. - * + * * @author Oliver Gierke * @author Christoph Strobl - * @author Mark Paluch */ public class SolrRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport { - enum BeanDefinitionName { + enum BeanDefinition { SOLR_MAPPTING_CONTEXT("solrMappingContext"), SOLR_OPERATIONS("solrOperations"), SOLR_CLIENT( "solrClient"), SOLR_CONVERTER("solrConverter"), CUSTOM_CONVERSIONS("customConversions"); String beanName; - BeanDefinitionName(String beanName) { + private BeanDefinition(String beanName) { this.beanName = beanName; } @@ -78,7 +72,7 @@ public String getBeanName() { * @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getRepositoryFactoryClassName() */ @Override - public String getRepositoryFactoryBeanClassName() { + public String getRepositoryFactoryClassName() { return SolrRepositoryFactoryBean.class.getName(); } @@ -91,7 +85,7 @@ protected String getModulePrefix() { return "solr"; } - /* + /* * (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource) */ @@ -99,12 +93,16 @@ protected String getModulePrefix() { public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource config) { AnnotationAttributes attributes = config.getAttributes(); - builder.addPropertyReference(BeanDefinitionName.SOLR_OPERATIONS.getBeanName(), - attributes.getString("solrTemplateRef")); + if (!attributes.getBoolean("multicoreSupport")) { + builder.addPropertyReference(BeanDefinition.SOLR_OPERATIONS.getBeanName(), + attributes.getString("solrTemplateRef")); + } else { + builder.addPropertyReference(BeanDefinition.SOLR_CLIENT.getBeanName(), attributes.getString("solrClientRef")); + } builder.addPropertyValue("schemaCreationSupport", attributes.getBoolean("schemaCreationSupport")); - builder.addPropertyReference(BeanDefinitionName.SOLR_MAPPTING_CONTEXT.getBeanName(), "solrMappingContext"); + builder.addPropertyReference(BeanDefinition.SOLR_MAPPTING_CONTEXT.getBeanName(), "solrMappingContext"); - builder.addPropertyReference(BeanDefinitionName.SOLR_CONVERTER.getBeanName(), "solrConverter"); + builder.addPropertyReference(BeanDefinition.SOLR_CONVERTER.getBeanName(), "solrConverter"); } @Override @@ -115,7 +113,6 @@ public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConf registeCustomConversionsIfNotPresent(registry, configurationSource); registerSolrMappingContextIfNotPresent(registry, configurationSource); registerSolrConverterIfNotPresent(registry, configurationSource); - registerSolrTemplateIfNotPresent(registry, configurationSource); registerIfNotAlreadyRegistered( BeanDefinitionBuilder.genericBeanDefinition(SolrExceptionTranslator.class).getBeanDefinition(), registry, @@ -123,7 +120,7 @@ public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConf } - /* + /* * (non-Javadoc) * @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.XmlRepositoryConfigurationSource) */ @@ -131,14 +128,17 @@ public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConf public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfigurationSource config) { Element element = config.getElement(); - builder.addPropertyReference(BeanDefinitionName.SOLR_OPERATIONS.getBeanName(), - element.getAttribute("solr-template-ref")); - + if (!Boolean.valueOf(element.getAttribute("multicore-support"))) { + builder.addPropertyReference(BeanDefinition.SOLR_OPERATIONS.getBeanName(), + element.getAttribute("solr-template-ref")); + } else { + builder.addPropertyReference(BeanDefinition.SOLR_CLIENT.getBeanName(), element.getAttribute("solr-client-ref")); + } if (StringUtils.hasText(element.getAttribute("schema-creation-support"))) { builder.addPropertyValue("schemaCreationSupport", element.getAttribute("schema-creation-support")); } - builder.addPropertyReference(BeanDefinitionName.SOLR_MAPPTING_CONTEXT.getBeanName(), "solrMappingContext"); - builder.addPropertyReference(BeanDefinitionName.SOLR_CONVERTER.getBeanName(), "solrConverter"); + builder.addPropertyReference(BeanDefinition.SOLR_MAPPTING_CONTEXT.getBeanName(), "solrMappingContext"); + builder.addPropertyReference(BeanDefinition.SOLR_CONVERTER.getBeanName(), "solrConverter"); } /* @@ -147,7 +147,7 @@ public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfiguratio */ @Override protected Collection> getIdentifyingAnnotations() { - return Collections.singleton(SolrDocument.class); + return Collections.> singleton(SolrDocument.class); } /* @@ -156,20 +156,17 @@ protected Collection> getIdentifyingAnnotations() { */ @Override protected Collection> getIdentifyingTypes() { - return Arrays.asList(SolrRepository.class, SolrCrudRepository.class); + return Arrays.> asList(SolrRepository.class, SolrCrudRepository.class); } private void registeCustomConversionsIfNotPresent(BeanDefinitionRegistry registry, RepositoryConfigurationSource configurationSource) { - RootBeanDefinition definition = new RootBeanDefinition(SolrCustomConversions.class); - - definition.getConstructorArgumentValues().addGenericArgumentValue(Collections.emptyList()); + RootBeanDefinition definition = new RootBeanDefinition(CustomConversions.class); definition.setRole(AbstractBeanDefinition.ROLE_INFRASTRUCTURE); definition.setSource(configurationSource.getSource()); - registerIfNotAlreadyRegistered(definition, registry, BeanDefinitionName.CUSTOM_CONVERSIONS.getBeanName(), - definition); + registerIfNotAlreadyRegistered(definition, registry, BeanDefinition.CUSTOM_CONVERSIONS.getBeanName(), definition); } private void registerSolrMappingContextIfNotPresent(BeanDefinitionRegistry registry, @@ -179,7 +176,7 @@ private void registerSolrMappingContextIfNotPresent(BeanDefinitionRegistry regis definition.setRole(AbstractBeanDefinition.ROLE_INFRASTRUCTURE); definition.setSource(configurationSource.getSource()); - registerIfNotAlreadyRegistered(definition, registry, BeanDefinitionName.SOLR_MAPPTING_CONTEXT.getBeanName(), + registerIfNotAlreadyRegistered(definition, registry, BeanDefinition.SOLR_MAPPTING_CONTEXT.getBeanName(), definition); } @@ -188,43 +185,16 @@ private void registerSolrConverterIfNotPresent(BeanDefinitionRegistry registry, RootBeanDefinition definition = new RootBeanDefinition(MappingSolrConverter.class); ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues(); - ctorArgs.addIndexedArgumentValue(0, - new RuntimeBeanReference(BeanDefinitionName.SOLR_MAPPTING_CONTEXT.getBeanName())); + ctorArgs.addIndexedArgumentValue(0, new RuntimeBeanReference(BeanDefinition.SOLR_MAPPTING_CONTEXT.getBeanName())); definition.setConstructorArgumentValues(ctorArgs); MutablePropertyValues properties = new MutablePropertyValues(); - properties.add("customConversions", new RuntimeBeanReference(BeanDefinitionName.CUSTOM_CONVERSIONS.getBeanName())); + properties.add("customConversions", new RuntimeBeanReference(BeanDefinition.CUSTOM_CONVERSIONS.getBeanName())); definition.setPropertyValues(properties); definition.setRole(AbstractBeanDefinition.ROLE_INFRASTRUCTURE); definition.setSource(configurationSource.getSource()); - registerIfNotAlreadyRegistered(definition, registry, BeanDefinitionName.SOLR_CONVERTER.getBeanName(), definition); - } - - private void registerSolrTemplateIfNotPresent(BeanDefinitionRegistry registry, - RepositoryConfigurationSource configurationSource) { - - RootBeanDefinition solrTemplateDefinition = new RootBeanDefinition(SolrTemplate.class); - solrTemplateDefinition.setTargetType(SolrOperations.class); - - ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues(); - - ctorArgs.addIndexedArgumentValue(0, createHttpSolrClientFactory()); - ctorArgs.addIndexedArgumentValue(1, new RuntimeBeanReference(BeanDefinitionName.SOLR_CONVERTER.getBeanName())); - - solrTemplateDefinition.setConstructorArgumentValues(ctorArgs); - - registerIfNotAlreadyRegistered(solrTemplateDefinition, registry, "solrTemplate", solrTemplateDefinition); - } - - private BeanDefinition createHttpSolrClientFactory() { - - GenericBeanDefinition solrClientFactory = new GenericBeanDefinition(); - solrClientFactory.setBeanClass(HttpSolrClientFactory.class); - ConstructorArgumentValues args = new ConstructorArgumentValues(); - args.addIndexedArgumentValue(0, new RuntimeBeanReference(BeanDefinitionName.SOLR_CLIENT.getBeanName())); - solrClientFactory.setConstructorArgumentValues(args); - return solrClientFactory; + registerIfNotAlreadyRegistered(definition, registry, BeanDefinition.SOLR_CONVERTER.getBeanName(), definition); } } diff --git a/src/main/java/org/springframework/data/solr/repository/config/package-info.java b/src/main/java/org/springframework/data/solr/repository/config/package-info.java deleted file mode 100644 index 7abb765..0000000 --- a/src/main/java/org/springframework/data/solr/repository/config/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Repository configuration and extension support. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.repository.config; diff --git a/src/main/java/org/springframework/data/solr/repository/package-info.java b/src/main/java/org/springframework/data/solr/repository/package-info.java index 0bbaf47..8a66e1c 100644 --- a/src/main/java/org/springframework/data/solr/repository/package-info.java +++ b/src/main/java/org/springframework/data/solr/repository/package-info.java @@ -2,6 +2,4 @@ * Solr specific repository implementation. * {@link org.springframework.data.solr.repository.support.SimpleSolrRepository} provides Solr specific implementation of {@link org.springframework.data.repository.CrudRepository}. */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields package org.springframework.data.solr.repository; \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java index dab916f..698dbe3 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java @@ -17,13 +17,10 @@ import java.util.Collection; import java.util.Map.Entry; -import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.common.params.HighlightParams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Page; @@ -40,13 +37,25 @@ import org.springframework.data.solr.core.convert.DateTimeConverters; import org.springframework.data.solr.core.convert.NumberConverters; import org.springframework.data.solr.core.geo.GeoConverters; -import org.springframework.data.solr.core.query.*; +import org.springframework.data.solr.core.query.FacetAndHighlightQuery; +import org.springframework.data.solr.core.query.FacetOptions; +import org.springframework.data.solr.core.query.FacetQuery; +import org.springframework.data.solr.core.query.HighlightOptions; import org.springframework.data.solr.core.query.HighlightOptions.HighlightParameter; +import org.springframework.data.solr.core.query.HighlightQuery; +import org.springframework.data.solr.core.query.Query; +import org.springframework.data.solr.core.query.SimpleFacetAndHighlightQuery; +import org.springframework.data.solr.core.query.SimpleFacetQuery; +import org.springframework.data.solr.core.query.SimpleField; +import org.springframework.data.solr.core.query.SimpleHighlightQuery; +import org.springframework.data.solr.core.query.SimpleQuery; +import org.springframework.data.solr.core.query.SimpleStringCriteria; +import org.springframework.data.solr.core.query.SolrPageRequest; +import org.springframework.data.solr.core.query.StatsOptions; import org.springframework.data.solr.core.query.StatsOptions.FieldStatsOptions; import org.springframework.data.solr.core.query.result.FacetAndHighlightPage; import org.springframework.data.solr.core.query.result.FacetPage; import org.springframework.data.solr.core.query.result.HighlightPage; -import org.springframework.lang.Nullable; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; @@ -64,11 +73,9 @@ public abstract class AbstractSolrQuery implements RepositoryQuery { private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); - private static final Logger logger = LoggerFactory.getLogger(AbstractSolrQuery.class); private final SolrOperations solrOperations; private final SolrQueryMethod solrQueryMethod; - private final String collection; public final int UNLIMITED = 1; @@ -101,13 +108,11 @@ public abstract class AbstractSolrQuery implements RepositoryQuery { * @param solrOperations must not be null * @param solrQueryMethod must not be null */ - protected AbstractSolrQuery(@Nullable String collection, SolrOperations solrOperations, - SolrQueryMethod solrQueryMethod) { + protected AbstractSolrQuery(SolrOperations solrOperations, SolrQueryMethod solrQueryMethod) { Assert.notNull(solrOperations, "SolrOperations must not be null!"); Assert.notNull(solrQueryMethod, "SolrQueryMethod must not be null!"); this.solrOperations = solrOperations; this.solrQueryMethod = solrQueryMethod; - this.collection = collection; } @Override @@ -121,7 +126,6 @@ public Object execute(Object[] parameters) { setDefTypeIfDefined(query); setRequestHandlerIfDefined(query); setSpellecheckOptionsWhenDefined(query); - setReRankIfDefined(query); if (solrQueryMethod.hasStatsDefinition()) { query.setStatsOptions(extractStatsOptions(solrQueryMethod, accessor)); @@ -164,16 +168,6 @@ public Object execute(Object[] parameters) { return new SingleEntityExecution().execute(query); } - /** - * @param query - */ - private void setReRankIfDefined(Query query) { - String rqqValue = query.getRqqValue(); - if(rqqValue!=null) { - query.setReRank(rqqValue); - } - } - @Override public SolrQueryMethod getQueryMethod() { return this.solrQueryMethod; @@ -181,7 +175,7 @@ public SolrQueryMethod getQueryMethod() { private void setDefaultQueryOperatorIfDefined(Query query) { Query.Operator defaultOperator = solrQueryMethod.getDefaultOperator(); - if (!Query.Operator.NONE.equals(defaultOperator)) { + if (defaultOperator != null && !Query.Operator.NONE.equals(defaultOperator)) { query.setDefaultOperator(defaultOperator); } } @@ -222,7 +216,7 @@ private void decorateWithFilterQuery(Query query, SolrParameterAccessor paramete } } - protected void appendProjection(@Nullable Query query) { + protected void appendProjection(Query query) { if (query != null && this.getQueryMethod().hasProjectionFields()) { for (String fieldname : this.getQueryMethod().getProjectionFields()) { query.addProjectionOnField(new SimpleField(fieldname)); @@ -252,13 +246,13 @@ private String replacePlaceholders(String input, SolrParameterAccessor accessor) } @SuppressWarnings("rawtypes") - @Nullable private String getParameterWithIndex(SolrParameterAccessor accessor, int index) { - Object parameter = accessor.getBindableValue(index); + if (parameter == null) { return "null"; } + if (conversionService.canConvert(parameter.getClass(), String.class)) { return conversionService.convert(parameter, String.class); } @@ -279,9 +273,7 @@ private String getParameterWithIndex(SolrParameterAccessor accessor, int index) return parameter.toString(); } - @Nullable private StatsOptions extractStatsOptions(SolrQueryMethod queryMethod, SolrParameterAccessor accessor) { - if (!queryMethod.hasStatsDefinition()) { return null; } @@ -377,7 +369,7 @@ private void appendHighlightFormatOptions(HighlightOptions options, SolrQueryMet } } - private boolean isSimpleHighlightingOption(@Nullable String formatter) { + private boolean isSimpleHighlightingOption(String formatter) { return formatter == null || HighlightParams.SIMPLE.equalsIgnoreCase(formatter); } @@ -413,7 +405,7 @@ public int getLimit() { return UNLIMITED; } - protected Pageable getLimitingPageable(@Nullable Pageable source, final int limit) { + protected Pageable getLimitingPageable(final Pageable source, final int limit) { if (source == null) { return new SolrPageRequest(0, limit); @@ -424,7 +416,7 @@ protected Pageable getLimitingPageable(@Nullable Pageable source, final int limi private static final long serialVersionUID = 8100166028148948968L; @Override - public long getOffset() { + public int getOffset() { return source.getOffset(); } @@ -449,7 +441,7 @@ abstract class AbstractQueryExecution implements QueryExecution { protected Page executeFind(Query query) { EntityMetadata metadata = solrQueryMethod.getEntityInformation(); - return solrOperations.queryForPage(collection, query, metadata.getJavaType()); + return solrOperations.queryForPage(query, metadata.getJavaType()); } } @@ -474,11 +466,11 @@ public Object execute(Query query) { if (!isLimiting()) { - query.setPageRequest(pageable.isPaged() ? pageable : new SolrPageRequest(0, (int) count(query))); + query.setPageRequest(pageable != null ? pageable : new SolrPageRequest(0, (int) count(query))); return executeFind(query).getContent(); } - if (pageable.isUnpaged() && isLimiting()) { + if (pageable == null && isLimiting()) { return executeFind(query.setPageRequest(new SolrPageRequest(0, getLimit()))).getContent(); } @@ -487,14 +479,14 @@ public Object execute(Query query) { return new PageImpl(java.util.Collections.emptyList(), pageable, getLimit()); } if (pageable.getOffset() + pageable.getPageSize() > getLimit()) { - query.setPageRequest(getLimitingPageable(pageable, getLimit() - (int) pageable.getOffset())); + query.setPageRequest(getLimitingPageable(pageable, getLimit() - pageable.getOffset())); } } return executeFind(query).getContent(); } private long count(Query query) { - return solrOperations.count(collection, query); + return solrOperations.count(query); } } @@ -529,7 +521,7 @@ public Object execute(Query query) { return new PageImpl(java.util.Collections.emptyList(), pageToUse, limit); } if (pageToUse.getOffset() + pageToUse.getPageSize() > limit) { - pageToUse = getLimitingPageable(pageToUse, limit - (int) pageToUse.getOffset()); + pageToUse = getLimitingPageable(pageToUse, limit - pageToUse.getOffset()); } } } @@ -559,7 +551,7 @@ protected FacetPage executeFind(Query query) { Assert.isInstanceOf(FacetQuery.class, query, "Query must be instance of FacetQuery!"); EntityMetadata metadata = solrQueryMethod.getEntityInformation(); - return solrOperations.queryForFacetPage(collection, (FacetQuery) query, metadata.getJavaType()); + return solrOperations.queryForFacetPage((FacetQuery) query, metadata.getJavaType()); } } @@ -580,8 +572,9 @@ protected HighlightPage executeFind(Query query) { Assert.isInstanceOf(HighlightQuery.class, query, "Query must be instanceof HighlightQuery!"); EntityMetadata metadata = solrQueryMethod.getEntityInformation(); - return solrOperations.queryForHighlightPage(collection, (HighlightQuery) query, metadata.getJavaType()); - } + return solrOperations.queryForHighlightPage((HighlightQuery) query, metadata.getJavaType()); + }; + } /** @@ -602,8 +595,7 @@ protected FacetAndHighlightPage executeFind(Query query) { Assert.isInstanceOf(FacetAndHighlightQuery.class, query, "Query must be instance of FacetAndHighlightQuery!"); EntityMetadata metadata = solrQueryMethod.getEntityInformation(); - return solrOperations.queryForFacetAndHighlightPage(collection, (FacetAndHighlightQuery) query, - metadata.getJavaType()); + return solrOperations.queryForFacetAndHighlightPage((FacetAndHighlightQuery) query, metadata.getJavaType()); } } @@ -616,11 +608,8 @@ class SingleEntityExecution implements QueryExecution { @Override public Object execute(Query query) { - EntityMetadata metadata = solrQueryMethod.getEntityInformation(); - - Optional result = solrOperations.queryForObject(collection, query, metadata.getJavaType()); - return solrQueryMethod.returnsOptional() ? result : result.orElse(null); + return solrOperations.queryForObject(query, metadata.getJavaType()); } } @@ -631,7 +620,7 @@ class CountExecution implements QueryExecution { @Override public Object execute(Query query) { - return solrOperations.count(collection, query); + return Long.valueOf(solrOperations.count(query)); } } @@ -645,35 +634,31 @@ class DeleteExecution implements QueryExecution { public Object execute(Query query) { if (TransactionSynchronizationManager.isSynchronizationActive()) { - SolrTransactionSynchronizationAdapterBuilder.forOperations(solrOperations).onCollection(collection) - .withDefaultBehaviour().register(); + SolrTransactionSynchronizationAdapterBuilder.forOperations(solrOperations).withDefaultBehaviour().register(); } Object result = countOrGetDocumentsForDelete(query); - solrOperations.delete(collection, query); + solrOperations.delete(query); if (!TransactionSynchronizationManager.isSynchronizationActive()) { - solrOperations.commit(collection); + solrOperations.commit(); } return result; } - @Nullable private Object countOrGetDocumentsForDelete(Query query) { Object result = null; if (solrQueryMethod.isCollectionQuery()) { Query clone = SimpleQuery.fromQuery(query); - result = solrOperations - .queryForPage(collection, clone.setPageRequest(new SolrPageRequest(0, Integer.MAX_VALUE)), - solrQueryMethod.getEntityInformation().getJavaType()) - .getContent(); + result = solrOperations.queryForPage(clone.setPageRequest(new SolrPageRequest(0, Integer.MAX_VALUE)), + solrQueryMethod.getEntityInformation().getJavaType()).getContent(); } if (ClassUtils.isAssignable(Number.class, solrQueryMethod.getReturnedObjectType())) { - result = solrOperations.count(collection, query); + result = solrOperations.count(query); } return result; } diff --git a/src/main/java/org/springframework/data/solr/repository/query/PartTreeSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/PartTreeSolrQuery.java index affc7a7..b913e06 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/PartTreeSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/PartTreeSolrQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 -2014 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,6 @@ import org.springframework.data.solr.core.SolrOperations; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; import org.springframework.data.solr.core.query.Query; -import org.springframework.lang.Nullable; /** * Solr specific implementation of a query derived from method name @@ -33,11 +32,7 @@ public class PartTreeSolrQuery extends AbstractSolrQuery { private final MappingContext mappingContext; public PartTreeSolrQuery(SolrQueryMethod method, SolrOperations solrOperations) { - this(null, method, solrOperations); - } - - public PartTreeSolrQuery(@Nullable String collection, SolrQueryMethod method, SolrOperations solrOperations) { - super(collection, solrOperations, method); + super(solrOperations, method); this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType()); this.mappingContext = solrOperations.getConverter().getMappingContext(); } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformation.java b/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformation.java index 3afa778..32438c0 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformation.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,6 +15,8 @@ */ package org.springframework.data.solr.repository.query; +import java.io.Serializable; + import org.springframework.data.repository.core.EntityInformation; /** @@ -22,20 +24,18 @@ * @param * @author Christoph Strobl */ -public interface SolrEntityInformation extends EntityInformation { +public interface SolrEntityInformation extends EntityInformation { /** - * Get the name of the id attribute. - * + * get the name of the id attribute * @return */ String getIdAttribute(); /** - * Get the name of the solr collection the entity resides in. - * + * get the name of the solr collection the entity resides in * @return */ - String getCollectionName(); + String getSolrCoreName(); } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformationCreator.java b/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformationCreator.java index 72da118..607f39b 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformationCreator.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrEntityInformationCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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,11 +15,13 @@ */ package org.springframework.data.solr.repository.query; +import java.io.Serializable; + /** * @author Christoph Strobl */ public interface SolrEntityInformationCreator { - SolrEntityInformation getEntityInformation(Class domainClass); + SolrEntityInformation getEntityInformation(Class domainClass); } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrParameter.java b/src/main/java/org/springframework/data/solr/repository/query/SolrParameter.java index 2693811..21d67a0 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrParameter.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrParameter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -18,7 +18,6 @@ import org.springframework.core.MethodParameter; import org.springframework.data.repository.query.Parameter; import org.springframework.data.solr.repository.Boost; -import org.springframework.lang.Nullable; /** * Solr specific {@link Parameter} implementation @@ -34,7 +33,6 @@ protected SolrParameter(MethodParameter parameter) { this.parameter = parameter; } - @Nullable private Boost getBoostAnnotation() { return parameter.getParameterAnnotation(Boost.class); } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessor.java b/src/main/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessor.java index a33ed30..037d392 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessor.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessor.java @@ -16,7 +16,6 @@ package org.springframework.data.solr.repository.query; import java.util.Iterator; -import java.util.Optional; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -68,7 +67,7 @@ public Iterator iterator() { } @Override - public Optional> getDynamicProjection() { + public Class getDynamicProjection() { return parametersParameterAccessorDelegate.getDynamicProjection(); } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryCreator.java b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryCreator.java index 2b6db65..f589952 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryCreator.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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. @@ -33,7 +33,6 @@ import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SimpleQuery; -import org.springframework.lang.Nullable; /** * Solr specific implmentation of an {@link AbstractQueryCreator} that constructs {@link Query} @@ -59,7 +58,7 @@ protected Query create(Part part, Iterator iterator) { } @Override - protected Query and(Part part, @Nullable Query base, Iterator iterator) { + protected Query and(Part part, Query base, Iterator iterator) { if (base == null) { return create(part, iterator); } @@ -89,10 +88,13 @@ protected Query or(Query base, Query query) { @Override protected Query complete(Query query, Sort sort) { + if (query == null) { + return null; + } return query.addSort(sort); } - private Criteria from(Type type, @Nullable Criteria instance, Iterator parameters) { + private Criteria from(Type type, Criteria instance, Iterator parameters) { Criteria criteria = instance; if (criteria == null) { criteria = new Criteria(); @@ -166,8 +168,7 @@ private Criteria appendBoost(Criteria criteria, BindableSolrParameter parameter) return criteria; } - @Nullable - private Object getBindableValue(@Nullable BindableSolrParameter parameter) { + private Object getBindableValue(BindableSolrParameter parameter) { if (parameter == null) { return null; } diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java index 06486b1..2be347e 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -24,7 +24,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationUtils; @@ -36,26 +35,22 @@ import org.springframework.data.solr.repository.Highlight; import org.springframework.data.solr.repository.Pivot; import org.springframework.data.solr.repository.Query; -import org.springframework.data.solr.repository.Rerank; import org.springframework.data.solr.repository.SelectiveStats; import org.springframework.data.solr.repository.Spellcheck; import org.springframework.data.solr.repository.Stats; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; -import org.springframework.lang.Nullable; -import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Solr specific implementation of {@link QueryMethod} taking care of {@link Query} - * + * * @author Christoph Strobl * @author Luke Corpe * @author Andrey Paramonov * @author Francisco Spaeth - * @author Mark Paluch */ public class SolrQueryMethod extends QueryMethod { @@ -81,7 +76,6 @@ public boolean hasQueryAnnotation() { return this.method.getAnnotation(Query.class) != null; } - @Nullable String getAnnotatedQuery() { return getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "value"); } @@ -93,7 +87,6 @@ public boolean hasAnnotatedNamedQueryName() { return getAnnotatedNamedQueryName() != null; } - @Nullable String getAnnotatedNamedQueryName() { return getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "name"); } @@ -110,7 +103,10 @@ TypeInformation getReturnType() { * @return true if {@link Query#fields()} is not empty */ public boolean hasProjectionFields() { - return hasQueryAnnotation() && !CollectionUtils.isEmpty(getProjectionFields()); + if (hasQueryAnnotation()) { + return !CollectionUtils.isEmpty(getProjectionFields()); + } + return false; } /** @@ -123,24 +119,12 @@ public List getProjectionFields() { /** * @return null if {@link Query#timeAllowed()} is null or negative */ - @Nullable public Integer getTimeAllowed() { if (hasQueryAnnotation()) { return getAnnotationValueAsIntOrNullIfNegative(getQueryAnnotation(), "timeAllowed"); } return null; } - - /** - * @return null if {@link Query#rqqValue()} is null or blank - */ - @Nullable - public String getRqqValue() { - if (hasQueryAnnotation()) { - return getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "rqqValue"); - } - return null; - } /** * @return true if {@link #hasFacetFields()} or {@link #hasFacetQueries()} @@ -153,14 +137,20 @@ public boolean isFacetQuery() { * @return true if {@link Facet#fields()} is not empty */ public boolean hasFacetFields() { - return hasFacetAnnotation() && !CollectionUtils.isEmpty(getFacetFields()); + if (hasFacetAnnotation()) { + return !CollectionUtils.isEmpty(getFacetFields()); + } + return false; } /** - * @return true if is not empty + * @return true if {@link Facet#pivotFields()} is not empty */ public boolean hasPivotFields() { - return hasFacetAnnotation() && !CollectionUtils.isEmpty(getPivotFields()); + if (hasFacetAnnotation()) { + return !CollectionUtils.isEmpty(getPivotFields()); + } + return false; } private boolean hasFacetAnnotation() { @@ -183,7 +173,7 @@ public List getFacetQueries() { public List getPivotFields() { List pivotFields = getAnnotationValuesList(getFacetAnnotation(), "pivots", Pivot.class); - ArrayList result = new ArrayList<>(); + ArrayList result = new ArrayList(); for (Pivot pivot : pivotFields) { result.add(pivot.value()); @@ -196,10 +186,12 @@ public List getPivotFields() { * @return true if {@link Facet#queries()} is not empty */ public boolean hasFacetQueries() { - return hasFacetAnnotation() && !CollectionUtils.isEmpty(getFacetQueries()); + if (hasFacetAnnotation()) { + return !CollectionUtils.isEmpty(getFacetQueries()); + } + return false; } - @Nullable private Facet getFacetAnnotation() { return this.method.getAnnotation(Facet.class); } @@ -207,90 +199,27 @@ private Facet getFacetAnnotation() { /** * @return value of {@link Facet#limit()} */ - @Nullable public Integer getFacetLimit() { - - Facet facetAnnotation = getFacetAnnotation(); - - if (facetAnnotation != null) { - return (Integer) AnnotationUtils.getValue(getFacetAnnotation(), "limit"); - } - - return null; + return (Integer) AnnotationUtils.getValue(getFacetAnnotation(), "limit"); } /** * @return value of {@link Facet#minCount()} */ - @Nullable public Integer getFacetMinCount() { - - Facet facetAnnotation = getFacetAnnotation(); - - if (facetAnnotation != null) { - return (Integer) AnnotationUtils.getValue(getFacetAnnotation(), "minCount"); - } - - return null; + return (Integer) AnnotationUtils.getValue(getFacetAnnotation(), "minCount"); } /** * @return value of {@link Facet#prefix()} */ - @Nullable public String getFacetPrefix() { return getAnnotationValueAsStringOrNullIfBlank(getFacetAnnotation(), "prefix"); } - - // Rerank Anotation - - - /** - * @return the {@link Rerank} annotation, null if there is none - */ - @Nullable - private Rerank getRerankAnnotation() { - return this.method.getAnnotation(Rerank.class); - } - - private boolean hasRerankAnnotation() { - return getRerankAnnotation() != null; - } - - /** - * @return null if {@link Rerank#reRankDocs()} is null or negative - */ - @Nullable - public Integer getReRankDocs() { - if (hasRerankAnnotation()) { - return getAnnotationValueAsIntOrNullIfNegative(getRerankAnnotation(), "reRankDocs"); - } - return null; - } - - /** - * @return null if {@link Rerank#reRankWt()} is null or negative - */ - @Nullable - public Integer getReRankWt() { - if (hasRerankAnnotation()) { - return getAnnotationValueAsIntOrNullIfNegative(getRerankAnnotation(), "reRankWt"); - } - return null; - } - - /** - * @return null if {@link Rerank#value()} is null or blank - */ - @Nullable - public String getAnnotatedRerank() { - return getAnnotationValueAsStringOrNullIfBlank(getRerankAnnotation(), "value"); - } - + /** * @return the {@link Stats} annotation, null if there is none */ - @Nullable private Stats getStatsAnnotation() { return this.method.getAnnotation(Stats.class); } @@ -343,7 +272,7 @@ public Map getStatsSelectiveFacets() { List selective = getAnnotationValuesList(getStatsAnnotation(), "selective", SelectiveStats.class); - Map result = new LinkedHashMap<>(); + Map result = new LinkedHashMap(); for (SelectiveStats selectiveFacet : selective) { result.put(selectiveFacet.field(), selectiveFacet.facets()); } @@ -359,7 +288,7 @@ public Collection getStatsSelectiveCountDistinctFields() { List selective = getAnnotationValuesList(getStatsAnnotation(), "selective", SelectiveStats.class); - Collection result = new LinkedHashSet<>(); + Collection result = new LinkedHashSet(); for (SelectiveStats selectiveFacet : selective) { if (selectiveFacet.distinct()) { result.add(selectiveFacet.field()); @@ -373,7 +302,10 @@ public Collection getStatsSelectiveCountDistinctFields() { * @return true if {@link Query#filters()} is not empty */ public boolean hasFilterQuery() { - return hasQueryAnnotation() && !CollectionUtils.isEmpty(getFilterQueries()); + if (hasQueryAnnotation()) { + return !CollectionUtils.isEmpty(getFilterQueries()); + } + return false; } /** @@ -381,10 +313,12 @@ public boolean hasFilterQuery() { * @since 1.2 */ public boolean isDeleteQuery() { - return hasQueryAnnotation() && (Boolean) AnnotationUtils.getValue(getQueryAnnotation(), "delete"); + if (hasQueryAnnotation()) { + return ((Boolean) AnnotationUtils.getValue(getQueryAnnotation(), "delete")).booleanValue(); + } + return false; } - @Nullable private Annotation getHighlightAnnotation() { return this.method.getAnnotation(Highlight.class); } @@ -413,7 +347,6 @@ public List getHighlightFieldNames() { /** * @return null if {@link Highlight#query()} is blank */ - @Nullable public String getHighlightQuery() { if (hasHighlightAnnotation()) { return getAnnotationValueAsStringOrNullIfBlank(getHighlightAnnotation(), "query"); @@ -424,7 +357,6 @@ public String getHighlightQuery() { /** * @return value of {@link Highlight#snipplets()} or null if negative */ - @Nullable public Integer getHighlighSnipplets() { if (hasHighlightAnnotation()) { return getAnnotationValueAsIntOrNullIfNegative(getHighlightAnnotation(), "snipplets"); @@ -435,7 +367,6 @@ public Integer getHighlighSnipplets() { /** * @return value of {@link Highlight#fragsize()} or null if negative */ - @Nullable public Integer getHighlightFragsize() { if (hasHighlightAnnotation()) { return getAnnotationValueAsIntOrNullIfNegative(getHighlightAnnotation(), "fragsize"); @@ -446,7 +377,6 @@ public Integer getHighlightFragsize() { /** * @return value of {@link Highlight#formatter()} or null if blank */ - @Nullable public String getHighlightFormatter() { if (hasHighlightAnnotation()) { return getAnnotationValueAsStringOrNullIfBlank(getHighlightAnnotation(), "formatter"); @@ -457,7 +387,6 @@ public String getHighlightFormatter() { /** * @return value of {@link Highlight#prefix()} or null if blank */ - @Nullable public String getHighlightPrefix() { if (hasHighlightAnnotation()) { return getAnnotationValueAsStringOrNullIfBlank(getHighlightAnnotation(), "prefix"); @@ -468,7 +397,6 @@ public String getHighlightPrefix() { /** * @return value of {@link Highlight#postfix()} or null if blank */ - @Nullable public String getHighlightPostfix() { if (hasHighlightAnnotation()) { return getAnnotationValueAsStringOrNullIfBlank(getHighlightAnnotation(), "postfix"); @@ -492,7 +420,6 @@ List getFilterQueries() { * {@link org.springframework.data.solr.core.query.Query.Operator#NONE} if not set */ public org.springframework.data.solr.core.query.Query.Operator getDefaultOperator() { - if (hasQueryAnnotation()) { return getQueryAnnotation().defaultOperator(); } @@ -502,7 +429,6 @@ public org.springframework.data.solr.core.query.Query.Operator getDefaultOperato /** * @return null if {@link Query#defType()} not set */ - @Nullable public String getDefType() { if (hasQueryAnnotation()) { return getQueryAnnotation().defType(); @@ -513,7 +439,6 @@ public String getDefType() { /** * @return null if {@link Query#requestHandler()} not set */ - @Nullable public String getRequestHandler() { if (hasQueryAnnotation()) { return getQueryAnnotation().requestHandler(); @@ -525,7 +450,6 @@ public String getRequestHandler() { * @return * @since 2.1 */ - @Nullable public Spellcheck getSpellcheckAnnotation() { return AnnotatedElementUtils.findMergedAnnotation(this.method, Spellcheck.class); } @@ -542,7 +466,6 @@ public boolean hasSpellcheck() { * @return * @since 2.1 */ - @Nullable public SpellcheckOptions getSpellcheckOptions() { Spellcheck spellcheck = getSpellcheckAnnotation(); @@ -596,40 +519,21 @@ public SpellcheckOptions getSpellcheckOptions() { return sc; } - private String getAnnotationValueAsStringOrNullIfBlank(@Nullable Annotation annotation, String attributeName) { - - if (annotation == null) { - return null; - } - + private String getAnnotationValueAsStringOrNullIfBlank(Annotation annotation, String attributeName) { String value = (String) AnnotationUtils.getValue(annotation, attributeName); - return StringUtils.hasText(value) ? value : null; } - @Nullable - private Integer getAnnotationValueAsIntOrNullIfNegative(@Nullable Annotation annotation, String attributeName) { - - if (annotation == null) { - return null; - } - + private Integer getAnnotationValueAsIntOrNullIfNegative(Annotation annotation, String attributeName) { Integer timeAllowed = (Integer) AnnotationUtils.getValue(annotation, attributeName); - - if (timeAllowed != null && timeAllowed > 0) { + if (timeAllowed != null && timeAllowed.intValue() > 0) { return timeAllowed; } - return null; } @SuppressWarnings("unchecked") - private List getAnnotationValuesAsStringList(@Nullable Annotation annotation, String attribute) { - - if (annotation == null) { - return Collections.emptyList(); - } - + private List getAnnotationValuesAsStringList(Annotation annotation, String attribute) { String[] values = (String[]) AnnotationUtils.getValue(annotation, attribute); if (values.length > 1 || (values.length == 1 && StringUtils.hasText(values[0]))) { return CollectionUtils.arrayToList(values); @@ -638,14 +542,8 @@ private List getAnnotationValuesAsStringList(@Nullable Annotation annota } @SuppressWarnings("unchecked") - private List getAnnotationValuesList(@Nullable Annotation annotation, String attribute, Class clazz) { - - if (annotation == null) { - return Collections.emptyList(); - } - + private List getAnnotationValuesList(Annotation annotation, String attribute, Class clazz) { T[] values = (T[]) AnnotationUtils.getValue(annotation, attribute); - return CollectionUtils.arrayToList(values); } @@ -657,14 +555,6 @@ public String getNamedQueryName() { return getAnnotatedNamedQueryName(); } - /** - * @return {@literal true} if the method return type is {@link Optional}. - * @since 2.0 - */ - public boolean returnsOptional() { - return ClassUtils.isAssignable(Optional.class, getReturnedObjectType()); - } - @Override protected SolrParameters createParameters(Method method) { return new SolrParameters(method); diff --git a/src/main/java/org/springframework/data/solr/repository/query/StringBasedSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/StringBasedSolrQuery.java index aaec7c5..2e9b34d 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/StringBasedSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/StringBasedSolrQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. @@ -19,7 +19,6 @@ import org.springframework.data.solr.core.SolrOperations; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SimpleQuery; -import org.springframework.lang.Nullable; /** * Solr specific implementation of {@link RepositoryQuery} that can handle string based queries @@ -31,15 +30,11 @@ public class StringBasedSolrQuery extends AbstractSolrQuery { private final String rawQueryString; public StringBasedSolrQuery(SolrQueryMethod method, SolrOperations solrOperations) { - this(null, method, solrOperations); + this(method.getAnnotatedQuery(), method, solrOperations); } - public StringBasedSolrQuery(@Nullable String collection, SolrQueryMethod method, SolrOperations solrOperations) { - this(collection, method.getAnnotatedQuery(), method, solrOperations); - } - - public StringBasedSolrQuery(String collection, String query, SolrQueryMethod queryMethod, SolrOperations solrOperations) { - super(collection, solrOperations, queryMethod); + public StringBasedSolrQuery(String query, SolrQueryMethod queryMethod, SolrOperations solrOperations) { + super(solrOperations, queryMethod); this.rawQueryString = query; } diff --git a/src/main/java/org/springframework/data/solr/repository/query/package-info.java b/src/main/java/org/springframework/data/solr/repository/query/package-info.java deleted file mode 100644 index c4c1247..0000000 --- a/src/main/java/org/springframework/data/solr/repository/query/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Apache Solr specific repository query methods and executions. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.repository.query; diff --git a/src/main/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformation.java b/src/main/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformation.java index 95e951c..8346652 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformation.java +++ b/src/main/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2015 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,6 +15,8 @@ */ package org.springframework.data.solr.repository.support; +import java.io.Serializable; + import org.springframework.data.repository.core.support.AbstractEntityInformation; import org.springframework.data.repository.core.support.PersistentEntityInformation; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; @@ -22,29 +24,34 @@ /** * Solr specific implementation of {@link AbstractEntityInformation} - * + * * @param * @param * @author Christoph Strobl * @author Oliver Gierke - * @author Mark Paluch */ -public class MappingSolrEntityInformation extends PersistentEntityInformation +public class MappingSolrEntityInformation extends PersistentEntityInformation implements SolrEntityInformation { private final SolrPersistentEntity entityMetadata; + private final String solrCoreName; public MappingSolrEntityInformation(SolrPersistentEntity entity) { + this(entity, null); + } + + public MappingSolrEntityInformation(SolrPersistentEntity entity, String solrCoreName) { super(entity); this.entityMetadata = entity; + this.solrCoreName = solrCoreName; } @Override public String getIdAttribute() { - return entityMetadata.getRequiredIdProperty().getFieldName(); + return entityMetadata.getIdProperty().getFieldName(); } - public String getCollectionName() { - return entityMetadata.getCollectionName(); + public String getSolrCoreName() { + return solrCoreName != null ? solrCoreName : entityMetadata.getSolrCoreName(); } } diff --git a/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java b/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java index 587aa9a..8ae2c0d 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java +++ b/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java @@ -16,10 +16,12 @@ package org.springframework.data.solr.repository.support; import java.io.Serializable; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Optional; import org.apache.solr.common.SolrInputDocument; import org.springframework.dao.InvalidDataAccessApiUsageException; @@ -29,7 +31,6 @@ import org.springframework.data.domain.Sort; import org.springframework.data.solr.core.SolrOperations; import org.springframework.data.solr.core.SolrTransactionSynchronizationAdapterBuilder; -import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.SimpleFilterQuery; import org.springframework.data.solr.core.query.SimpleQuery; @@ -41,35 +42,44 @@ /** * Solr specific repository implementation. Likely to be used as target within {@link SolrRepositoryFactory} - * + * * @param * @Param * @author Christoph Strobl - * @author Mark Paluch */ public class SimpleSolrRepository implements SolrCrudRepository { private static final String DEFAULT_ID_FIELD = "id"; - private final SolrOperations solrOperations; + private SolrOperations solrOperations; private String idFieldName = DEFAULT_ID_FIELD; - private final Class entityClass; - private final String solrCollectionName; - private final SolrEntityInformation entityInformation; + private Class entityClass; + private SolrEntityInformation entityInformation; + + public SimpleSolrRepository() { + + } /** - * @param metadata must not be null * @param solrOperations must not be null */ - public SimpleSolrRepository(SolrOperations solrOperations, SolrEntityInformation metadata) { + public SimpleSolrRepository(SolrOperations solrOperations) { + Assert.notNull(solrOperations, "SolrOperations must not be null!"); + + this.setSolrOperations(solrOperations); + } + /** + * @param metadata must not be null + * @param solrOperations must not be null + */ + public SimpleSolrRepository(SolrEntityInformation metadata, SolrOperations solrOperations) { + this(solrOperations); Assert.notNull(metadata, "Metadata must not be null!"); - this.solrOperations = solrOperations; this.entityInformation = metadata; - this.entityClass = this.entityInformation.getJavaType(); - this.idFieldName = this.entityInformation.getIdAttribute(); - this.solrCollectionName = this.entityInformation.getCollectionName(); + setIdFieldName(this.entityInformation.getIdAttribute()); + setEntityClass(this.entityInformation.getJavaType()); } /** @@ -77,31 +87,28 @@ public SimpleSolrRepository(SolrOperations solrOperations, SolrEntityInformation * @param entityClass */ public SimpleSolrRepository(SolrOperations solrOperations, Class entityClass) { - this(solrOperations, getEntityInformation(entityClass)); - } + this(solrOperations); - private static SolrEntityInformation getEntityInformation(Class type) { - return new SolrEntityInformationCreatorImpl(new SimpleSolrMappingContext()).getEntityInformation(type); + this.setEntityClass(entityClass); } @Override - public Optional findById(ID id) { - return getSolrOperations().queryForObject(solrCollectionName, - new SimpleQuery(new Criteria(this.idFieldName).is(id)), getEntityClass()); + public T findOne(ID id) { + return getSolrOperations().queryForObject(new SimpleQuery(new Criteria(this.idFieldName).is(id)), getEntityClass()); } @Override public Iterable findAll() { int itemCount = (int) this.count(); if (itemCount == 0) { - return new PageImpl<>(Collections. emptyList()); + return new PageImpl(Collections. emptyList()); } return this.findAll(new SolrPageRequest(0, itemCount)); } @Override public Page findAll(Pageable pageable) { - return getSolrOperations().queryForPage(solrCollectionName, + return getSolrOperations().queryForPage( new SimpleQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)).setPageRequest(pageable), getEntityClass()); } @@ -110,20 +117,19 @@ public Page findAll(Pageable pageable) { public Iterable findAll(Sort sort) { int itemCount = (int) this.count(); if (itemCount == 0) { - return new PageImpl<>(Collections. emptyList()); + return new PageImpl(Collections. emptyList()); } - return getSolrOperations().queryForPage(solrCollectionName, - new SimpleQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) - .setPageRequest(new SolrPageRequest(0, itemCount)).addSort(sort), - getEntityClass()); + return getSolrOperations().queryForPage( + new SimpleQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)).setPageRequest( + new SolrPageRequest(0, itemCount)).addSort(sort), getEntityClass()); } @Override - public Iterable findAllById(Iterable ids) { + public Iterable findAll(Iterable ids) { org.springframework.data.solr.core.query.Query query = new SimpleQuery(new Criteria(this.idFieldName).in(ids)); query.setPageRequest(new SolrPageRequest(0, (int) count(query))); - return getSolrOperations().queryForPage(solrCollectionName, query, getEntityClass()); + return getSolrOperations().queryForPage(query, getEntityClass()); } @Override @@ -133,20 +139,20 @@ public long count() { protected long count(org.springframework.data.solr.core.query.Query query) { org.springframework.data.solr.core.query.Query countQuery = SimpleQuery.fromQuery(query); - return getSolrOperations().count(solrCollectionName, countQuery); + return getSolrOperations().count(countQuery); } @Override public S save(S entity) { Assert.notNull(entity, "Cannot save 'null' entity."); registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.saveBean(solrCollectionName, entity); + this.solrOperations.saveBean(entity); commitIfTransactionSynchronisationIsInactive(); return entity; } @Override - public Iterable saveAll(Iterable entities) { + public Iterable save(Iterable entities) { Assert.notNull(entities, "Cannot insert 'null' as a List."); if (!(entities instanceof Collection)) { @@ -154,22 +160,22 @@ public Iterable saveAll(Iterable entities) { } registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.saveBeans(solrCollectionName, (Collection) entities); + this.solrOperations.saveBeans((Collection) entities); commitIfTransactionSynchronisationIsInactive(); return entities; } @Override - public boolean existsById(ID id) { - return findById(id).isPresent(); + public boolean exists(ID id) { + return findOne(id) != null; } @Override - public void deleteById(ID id) { + public void delete(ID id) { Assert.notNull(id, "Cannot delete entity with id 'null'."); registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.deleteByIds(solrCollectionName, id.toString()); + this.solrOperations.deleteById(id.toString()); commitIfTransactionSynchronisationIsInactive(); } @@ -177,28 +183,27 @@ public void deleteById(ID id) { public void delete(T entity) { Assert.notNull(entity, "Cannot delete 'null' entity."); - deleteAll(Collections.singletonList(entity)); + delete(Arrays.asList(entity)); } @Override - public void deleteAll(Iterable entities) { + public void delete(Iterable entities) { Assert.notNull(entities, "Cannot delete 'null' list."); - ArrayList idsToDelete = new ArrayList<>(); + ArrayList idsToDelete = new ArrayList(); for (T entity : entities) { idsToDelete.add(extractIdFromBean(entity).toString()); } registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.deleteByIds(solrCollectionName, idsToDelete); + this.solrOperations.deleteById(idsToDelete); commitIfTransactionSynchronisationIsInactive(); } @Override public void deleteAll() { registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.delete(solrCollectionName, - new SimpleFilterQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD))); + this.solrOperations.delete(new SimpleFilterQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD))); commitIfTransactionSynchronisationIsInactive(); } @@ -206,10 +211,37 @@ public final String getIdFieldName() { return idFieldName; } - public Class getEntityClass() { + public final void setIdFieldName(String idFieldName) { + Assert.notNull(idFieldName, "ID Field cannot be null."); + + this.idFieldName = idFieldName; + } + + @SuppressWarnings("unchecked") + private Class resolveReturnedClassFromGernericType() { + ParameterizedType parameterizedType = resolveReturnedClassFromGernericType(getClass()); + return (Class) parameterizedType.getActualTypeArguments()[0]; + } + + private ParameterizedType resolveReturnedClassFromGernericType(Class clazz) { + Object genericSuperclass = clazz.getGenericSuperclass(); + if (genericSuperclass instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; + Type rawtype = parameterizedType.getRawType(); + if (SimpleSolrRepository.class.equals(rawtype)) { + return parameterizedType; + } + } + return resolveReturnedClassFromGernericType(clazz.getSuperclass()); + } + public Class getEntityClass() { if (!isEntityClassSet()) { - throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!"); + try { + this.entityClass = resolveReturnedClassFromGernericType(); + } catch (Exception e) { + throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e); + } } return entityClass; } @@ -218,14 +250,25 @@ private boolean isEntityClassSet() { return entityClass != null; } + public final void setEntityClass(Class entityClass) { + Assert.notNull(entityClass, "EntityClass must not be null."); + + this.entityClass = entityClass; + } + + public final void setSolrOperations(SolrOperations solrOperations) { + Assert.notNull(solrOperations, "SolrOperations must not be null."); + + this.solrOperations = solrOperations; + } + public final SolrOperations getSolrOperations() { return solrOperations; } private Object extractIdFromBean(T entity) { - if (entityInformation != null) { - return entityInformation.getRequiredId(entity); + return entityInformation.getId(entity); } SolrInputDocument solrInputDocument = this.solrOperations.convertBeanToSolrInputDocument(entity); @@ -233,8 +276,8 @@ private Object extractIdFromBean(T entity) { } private String extractIdFromSolrInputDocument(SolrInputDocument solrInputDocument) { - Assert.notNull(solrInputDocument.getField(idFieldName), - "Unable to find field '" + idFieldName + "' in SolrDocument."); + Assert.notNull(solrInputDocument.getField(idFieldName), "Unable to find field '" + idFieldName + + "' in SolrDocument."); Assert.notNull(solrInputDocument.getField(idFieldName).getValue(), "ID must not be 'null'."); return solrInputDocument.getField(idFieldName).getValue().toString(); @@ -248,12 +291,13 @@ private void registerTransactionSynchronisationIfSynchronisationActive() { private void registerTransactionSynchronisationAdapter() { TransactionSynchronizationManager.registerSynchronization(SolrTransactionSynchronizationAdapterBuilder - .forOperations(this.solrOperations).onCollection(solrCollectionName).withDefaultBehaviour()); + .forOperations(this.solrOperations).withDefaultBehaviour()); } private void commitIfTransactionSynchronisationIsInactive() { if (!TransactionSynchronizationManager.isSynchronizationActive()) { - this.solrOperations.commit(solrCollectionName); + this.solrOperations.commit(); } } + } diff --git a/src/main/java/org/springframework/data/solr/repository/support/SolrEntityInformationCreatorImpl.java b/src/main/java/org/springframework/data/solr/repository/support/SolrEntityInformationCreatorImpl.java index 89b9aa2..8df3a14 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/SolrEntityInformationCreatorImpl.java +++ b/src/main/java/org/springframework/data/solr/repository/support/SolrEntityInformationCreatorImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-207 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,6 +15,8 @@ */ package org.springframework.data.solr.repository.support; +import java.io.Serializable; + import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; import org.springframework.data.solr.core.mapping.SolrPersistentProperty; @@ -24,7 +26,6 @@ /** * @author Christoph Strobl - * @author Mark Paluch */ public class SolrEntityInformationCreatorImpl implements SolrEntityInformationCreator { @@ -38,11 +39,13 @@ public SolrEntityInformationCreatorImpl( @Override @SuppressWarnings("unchecked") - public SolrEntityInformation getEntityInformation(Class domainClass) { + public SolrEntityInformation getEntityInformation(Class domainClass) { + SolrPersistentEntity persistentEntity = (SolrPersistentEntity) mappingContext + .getPersistentEntity(domainClass); - SolrPersistentEntity persistentEntity = (SolrPersistentEntity) mappingContext.getRequiredPersistentEntity(domainClass); + Assert.notNull(persistentEntity, "not an managed type: " + domainClass); - return new MappingSolrEntityInformation<>(persistentEntity); + return new MappingSolrEntityInformation(persistentEntity); } } diff --git a/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactory.java b/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactory.java index e4d1222..d06ebfd 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactory.java +++ b/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactory.java @@ -15,22 +15,21 @@ */ package org.springframework.data.solr.repository.support; -import static org.springframework.data.querydsl.QuerydslUtils.*; +import static org.springframework.data.querydsl.QueryDslUtils.*; +import java.io.Serializable; import java.lang.reflect.Method; import java.util.Collections; import java.util.Map; -import java.util.Optional; import java.util.WeakHashMap; import org.apache.solr.client.solrj.SolrClient; import org.springframework.data.projection.ProjectionFactory; -import org.springframework.data.querydsl.QuerydslPredicateExecutor; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.repository.core.NamedQueries; import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; -import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.data.repository.query.QueryLookupStrategy.Key; import org.springframework.data.repository.query.RepositoryQuery; @@ -45,8 +44,8 @@ import org.springframework.data.solr.repository.query.SolrQueryMethod; import org.springframework.data.solr.repository.query.StringBasedSolrQuery; import org.springframework.data.solr.server.SolrClientFactory; -import org.springframework.data.solr.server.support.HttpSolrClientFactory; -import org.springframework.lang.Nullable; +import org.springframework.data.solr.server.support.MulticoreSolrClientFactory; +import org.springframework.data.solr.server.support.SolrClientUtils; import org.springframework.util.Assert; /** @@ -58,7 +57,7 @@ public class SolrRepositoryFactory extends RepositoryFactorySupport { private SolrOperations solrOperations; private final SolrEntityInformationCreator entityInformationCreator; - private @Nullable SolrClientFactory factory; + private SolrClientFactory factory; private SolrTemplateHolder templateHolder = new SolrTemplateHolder(); private boolean schemaCreationSupport; @@ -79,7 +78,7 @@ public SolrRepositoryFactory(SolrClient solrClient) { this.solrOperations = createTemplate(solrClient, null); - factory = new HttpSolrClientFactory(solrClient); + factory = new MulticoreSolrClientFactory(solrClient); this.entityInformationCreator = new SolrEntityInformationCreatorImpl( this.solrOperations.getConverter().getMappingContext()); @@ -90,13 +89,13 @@ public SolrRepositoryFactory(SolrClient solrClient, SolrConverter converter) { this.solrOperations = createTemplate(solrClient, converter); - factory = new HttpSolrClientFactory(solrClient); + factory = new MulticoreSolrClientFactory(solrClient); this.entityInformationCreator = new SolrEntityInformationCreatorImpl( this.solrOperations.getConverter().getMappingContext()); } - private SolrTemplate createTemplate(SolrClient solrClient, @Nullable SolrConverter converter) { + private SolrTemplate createTemplate(SolrClient solrClient, SolrConverter converter) { SolrTemplate template = new SolrTemplate(solrClient); @@ -109,7 +108,7 @@ private SolrTemplate createTemplate(SolrClient solrClient, @Nullable SolrConvert } @Override - public SolrEntityInformation getEntityInformation(Class domainClass) { + public SolrEntityInformation getEntityInformation(Class domainClass) { return entityInformationCreator.getEntityInformation(domainClass); } @@ -125,13 +124,15 @@ protected Object getTargetRepository(RepositoryInformation metadata) { template.setMappingContext(this.solrOperations.getConverter().getMappingContext()); template.setSolrConverter(this.solrOperations.getConverter()); } + template.setSolrCore(SolrClientUtils.resolveSolrCoreName(metadata.getDomainType())); addSchemaCreationFeaturesIfEnabled(template); template.afterPropertiesSet(); operations = template; } - SimpleSolrRepository repository = getTargetRepositoryViaReflection(metadata, operations, - getEntityInformation(metadata.getDomainType())); + SimpleSolrRepository repository = getTargetRepositoryViaReflection(metadata, + getEntityInformation(metadata.getDomainType()), operations); + repository.setEntityClass(metadata.getDomainType()); this.templateHolder.add(metadata.getDomainType(), operations); return repository; @@ -152,14 +153,12 @@ protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { } private static boolean isQueryDslRepository(Class repositoryInterface) { - return QUERY_DSL_PRESENT && QuerydslPredicateExecutor.class.isAssignableFrom(repositoryInterface); + return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); } @Override - protected Optional getQueryLookupStrategy(@Nullable Key key, - EvaluationContextProvider evaluationContextProvider) { - - return Optional.of(new SolrQueryLookupStrategy()); + protected QueryLookupStrategy getQueryLookupStrategy(Key key) { + return new SolrQueryLookupStrategy(); } /** @@ -186,17 +185,16 @@ public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadata, factory, entityInformationCreator); String namedQueryName = queryMethod.getNamedQueryName(); - String collectionName = getEntityInformation(metadata.getDomainType()).getCollectionName(); SolrOperations solrOperations = selectSolrOperations(metadata); if (namedQueries.hasQuery(namedQueryName)) { String namedQuery = namedQueries.getQuery(namedQueryName); - return new StringBasedSolrQuery(collectionName, namedQuery, queryMethod, solrOperations); + return new StringBasedSolrQuery(namedQuery, queryMethod, solrOperations); } else if (queryMethod.hasAnnotatedQuery()) { - return new StringBasedSolrQuery(collectionName, queryMethod, solrOperations); + return new StringBasedSolrQuery(queryMethod, solrOperations); } else { - return new PartTreeSolrQuery(collectionName, queryMethod, solrOperations); + return new PartTreeSolrQuery(queryMethod, solrOperations); } } @@ -212,7 +210,7 @@ private SolrOperations selectSolrOperations(RepositoryMetadata metadata) { private static class SolrTemplateHolder { - private Map, SolrOperations> operationsMap = new WeakHashMap<>(); + private Map, SolrOperations> operationsMap = new WeakHashMap, SolrOperations>(); void add(Class domainType, SolrOperations repository) { operationsMap.put(domainType, repository); diff --git a/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryBean.java b/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryBean.java index bf58ea4..f93072d 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryBean.java +++ b/src/main/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -25,7 +25,6 @@ import org.springframework.data.solr.core.SolrOperations; import org.springframework.data.solr.core.convert.SolrConverter; import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -37,14 +36,14 @@ public class SolrRepositoryFactoryBean, S, ID extends Serializable> extends TransactionalRepositoryFactoryBeanSupport { - private @Nullable SolrClient solrClient; - private @Nullable SolrOperations operations; + private SolrClient solrClient; + private SolrOperations operations; private boolean schemaCreationSupport; - private @Nullable SimpleSolrMappingContext solrMappingContext; - private @Nullable SolrConverter solrConverter; + private SimpleSolrMappingContext solrMappingContext; + private SolrConverter solrConverter; /** - * Creates a new {@link SolrRepositoryFactoryBean} for the given repository interface. + * Creates a new {@link MongoRepositoryFactoryBean} for the given repository interface. * * @param repositoryInterface must not be {@literal null}. */ @@ -90,7 +89,6 @@ public void setSolrMappingContext(SimpleSolrMappingContext solrMappingContext) { * @return * @since 1.4 */ - @Nullable public SimpleSolrMappingContext getSolrMappingContext() { return solrMappingContext; } @@ -98,7 +96,6 @@ public SimpleSolrMappingContext getSolrMappingContext() { /** * @return SolrOperations to be used for eg. custom implementation */ - @Nullable protected SolrOperations getSolrOperations() { return this.operations; } diff --git a/src/main/java/org/springframework/data/solr/repository/support/package-info.java b/src/main/java/org/springframework/data/solr/repository/support/package-info.java deleted file mode 100644 index 868441e..0000000 --- a/src/main/java/org/springframework/data/solr/repository/support/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Repository support classes for bootstrapping application context. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.repository.support; diff --git a/src/main/java/org/springframework/data/solr/server/SolrClientFactory.java b/src/main/java/org/springframework/data/solr/server/SolrClientFactory.java index e1212f4..cd6e4f3 100644 --- a/src/main/java/org/springframework/data/solr/server/SolrClientFactory.java +++ b/src/main/java/org/springframework/data/solr/server/SolrClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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,6 +15,8 @@ */ package org.springframework.data.solr.server; +import java.util.List; + import org.apache.solr.client.solrj.SolrClient; /** @@ -24,7 +26,6 @@ * @author Christoph Strobl * @since 2.0 */ -@FunctionalInterface public interface SolrClientFactory { /** @@ -34,4 +35,19 @@ public interface SolrClientFactory { */ SolrClient getSolrClient(); + /** + * Get configured {@link SolrClient} for specific core + * + * @param core + * @return + */ + SolrClient getSolrClient(String core); + + /** + * Get list of cores + * + * @return empty list if no cores defined + */ + List getCores(); + } diff --git a/src/main/java/org/springframework/data/solr/server/config/EmbeddedSolrServerBeanDefinitionParser.java b/src/main/java/org/springframework/data/solr/server/config/EmbeddedSolrServerBeanDefinitionParser.java index 5273216..b6c9b1b 100644 --- a/src/main/java/org/springframework/data/solr/server/config/EmbeddedSolrServerBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/solr/server/config/EmbeddedSolrServerBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. @@ -21,7 +21,6 @@ import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.solr.server.support.EmbeddedSolrServerFactoryBean; -import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; import org.w3c.dom.Element; @@ -32,7 +31,6 @@ */ public class EmbeddedSolrServerBeanDefinitionParser extends AbstractBeanDefinitionParser { - @Nullable @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(EmbeddedSolrServerFactoryBean.class); diff --git a/src/main/java/org/springframework/data/solr/server/config/HttpSolrClientBeanDefinitionParser.java b/src/main/java/org/springframework/data/solr/server/config/HttpSolrClientBeanDefinitionParser.java index 8a802ab..551b443 100644 --- a/src/main/java/org/springframework/data/solr/server/config/HttpSolrClientBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/solr/server/config/HttpSolrClientBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012-2015 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,6 @@ import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.solr.server.support.HttpSolrClientFactoryBean; -import org.springframework.lang.Nullable; import org.w3c.dom.Element; /** @@ -31,7 +30,6 @@ */ public class HttpSolrClientBeanDefinitionParser extends AbstractBeanDefinitionParser { - @Nullable @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(HttpSolrClientFactoryBean.class); diff --git a/src/main/java/org/springframework/data/solr/server/config/package-info.java b/src/main/java/org/springframework/data/solr/server/config/package-info.java deleted file mode 100644 index f0c103b..0000000 --- a/src/main/java/org/springframework/data/solr/server/config/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Config support for {@link org.apache.solr.client.solrj.SolrClient}. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.server.config; diff --git a/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java b/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java index da8ac0d..fde6a35 100644 --- a/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java +++ b/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java @@ -32,12 +32,12 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.StringUtils; +import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.core.CoreContainer; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.data.solr.server.SolrClientFactory; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -55,9 +55,9 @@ public class EmbeddedSolrServerFactory implements SolrClientFactory, DisposableB private static final String SOLR_HOME_SYSTEM_PROPERTY = "solr.solr.home"; - private @Nullable String solrHome; - private AtomicReference coreContainer = new AtomicReference<>(null); - private ConcurrentHashMap servers = new ConcurrentHashMap<>(); + private String solrHome; + private AtomicReference coreContainer = new AtomicReference(null); + private ConcurrentHashMap servers = new ConcurrentHashMap(); protected EmbeddedSolrServerFactory() { @@ -83,7 +83,9 @@ public EmbeddedSolrServer getSolrClient() { protected void initCoreContainer() { try { this.coreContainer.compareAndSet(null, createCoreContainer(this.solrHome)); - } catch (FileNotFoundException | UnsupportedEncodingException e) { + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @@ -131,7 +133,7 @@ private CoreContainer createCoreContainerViaConstructor(String solrHomeDirectory } /** - * Create {@link CoreContainer} for Solr version 4.4+ and handle changes in . + * Create {@link CoreContainer} for Solr version 4.4+ and handle changes in {@link CoreContainer#createAndLoad()}. * * @param solrHomeDirectory * @param solrXmlFile @@ -157,8 +159,9 @@ public void shutdownSolrServer() { } } + @Override public List getCores() { - return new ArrayList<>(getCoreContainer().getAllCoreNames()); + return new ArrayList(getCoreContainer().getCoreNames()); } public void setSolrHome(String solrHome) { @@ -171,6 +174,19 @@ public void destroy() throws Exception { shutdownSolrServer(); } + @Override + public SolrClient getSolrClient(String core) { + + String coreName = core != null ? core : "collection1"; + if (servers.get(coreName) != null) { + return servers.get(coreName); + } + + EmbeddedSolrServer server = new EmbeddedSolrServer(getCoreContainer(), coreName); + servers.put(coreName, server); + return server; + } + private CoreContainer getCoreContainer() { if (coreContainer.get() == null) { diff --git a/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactory.java b/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactory.java index 6ff4e17..e45a32e 100644 --- a/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactory.java +++ b/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactory.java @@ -15,7 +15,9 @@ */ package org.springframework.data.solr.server.support; +import java.util.Arrays; import java.util.Collections; +import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.http.auth.AuthScope; @@ -25,7 +27,7 @@ import org.apache.http.impl.client.AbstractHttpClient; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; -import org.springframework.lang.Nullable; +import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.util.Assert; /** @@ -38,18 +40,23 @@ */ public class HttpSolrClientFactory extends SolrClientFactoryBase { - private @Nullable Credentials credentials; - private @Nullable String authPolicy; + private String core; + private Credentials credentials; + private String authPolicy; protected HttpSolrClientFactory() { } public HttpSolrClientFactory(SolrClient solrClient) { - this(solrClient, null, null); + this(solrClient, null); } - public HttpSolrClientFactory(SolrClient solrClient, @Nullable Credentials credentials, @Nullable String authPolicy) { + public HttpSolrClientFactory(SolrClient solrClient, String core) { + this(solrClient, core, null, null); + } + + public HttpSolrClientFactory(SolrClient solrClient, String core, Credentials credentials, String authPolicy) { super(solrClient); Assert.notNull(solrClient, "SolrServer must not be null"); @@ -57,12 +64,38 @@ public HttpSolrClientFactory(SolrClient solrClient, @Nullable Credentials creden Assert.hasText(authPolicy, "AuthPolicy must not be null nor empty!"); } + this.core = core; this.credentials = credentials; this.authPolicy = authPolicy; + appendCoreToBaseUrl(this.core, this.getSolrClient()); appendAuthentication(this.credentials, this.authPolicy, this.getSolrClient()); } + @Override + public List getCores() { + return this.core != null ? Arrays.asList(this.core) : Collections. emptyList(); + } + + /** + * returns the reference {@link SolrClient} + * + * @see SolrClientFactory#getSolrClient() + */ + @Override + public SolrClient getSolrClient(String core) { + return getSolrClient(); + } + + protected void appendCoreToBaseUrl(String core, SolrClient solrClient) { + if (StringUtils.isNotEmpty(core) && isHttpSolrClient(solrClient)) { + HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient; + + String url = SolrClientUtils.appendCoreToBaseUrl(httpSolrClient.getBaseURL(), core); + httpSolrClient.setBaseURL(url); + } + } + private void appendAuthentication(Credentials credentials, String authPolicy, SolrClient solrClient) { if (isHttpSolrClient(solrClient)) { HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient; @@ -71,7 +104,7 @@ private void appendAuthentication(Credentials credentials, String authPolicy, So && assertHttpClientInstance(httpSolrClient.getHttpClient())) { AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials); - httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Collections.singletonList(authPolicy)); + httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy)); } } } diff --git a/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactoryBean.java b/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactoryBean.java index da5c0b0..3581514 100644 --- a/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactoryBean.java +++ b/src/main/java/org/springframework/data/solr/server/support/HttpSolrClientFactoryBean.java @@ -24,7 +24,6 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -33,13 +32,13 @@ * @author Christoph Strobl * @since 2.0 */ -public class HttpSolrClientFactoryBean extends HttpSolrClientFactory - implements FactoryBean, InitializingBean, DisposableBean { +public class HttpSolrClientFactoryBean extends HttpSolrClientFactory implements FactoryBean, + InitializingBean, DisposableBean { private static final String SERVER_URL_SEPARATOR = ","; - private @Nullable String url; - private @Nullable Integer timeout; - private @Nullable Integer maxConnections; + private String url; + private Integer timeout; + private Integer maxConnections; @Override public void afterPropertiesSet() throws Exception { @@ -58,7 +57,7 @@ private void initSolrClient() { private void createHttpSolrClient() { HttpSolrClient httpSolrClient = new HttpSolrClient(this.url); if (timeout != null) { - httpSolrClient.setConnectionTimeout(timeout); + httpSolrClient.setConnectionTimeout(timeout.intValue()); } if (maxConnections != null) { httpSolrClient.setMaxTotalConnections(maxConnections); @@ -70,7 +69,7 @@ private void createLoadBalancedHttpSolrClient() { try { LBHttpSolrClient lbHttpSolrClient = new LBHttpSolrClient(StringUtils.split(this.url, SERVER_URL_SEPARATOR)); if (timeout != null) { - lbHttpSolrClient.setConnectionTimeout(timeout); + lbHttpSolrClient.setConnectionTimeout(timeout.intValue()); } this.setSolrClient(lbHttpSolrClient); } catch (MalformedURLException e) { diff --git a/src/main/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactory.java b/src/main/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactory.java new file mode 100644 index 0000000..d6a4006 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactory.java @@ -0,0 +1,154 @@ +/* + * 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.solr.server.support; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.solr.client.solrj.SolrClient; +import org.springframework.data.solr.core.mapping.SolrDocument; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * {@link MulticoreSolrClientFactory} replaces MulticoreSolrServerFactory from version 1.x. + * + * @author Christoph Strobl + * @since 2.0 + */ +public class MulticoreSolrClientFactory extends SolrClientFactoryBase { + + private boolean createMissingSolrClient = true; + private Map clientMap = new LinkedHashMap(); + + protected MulticoreSolrClientFactory() { + super(); + } + + public MulticoreSolrClientFactory(SolrClient solrServer) { + this(solrServer, Collections. emptyList()); + } + + public MulticoreSolrClientFactory(SolrClient solrServer, String... cores) { + this(solrServer, (cores != null ? Arrays.asList(cores) : Collections. emptyList())); + } + + public MulticoreSolrClientFactory(SolrClient solrServer, List cores) { + super(solrServer); + for (String core : cores) { + addSolrClientForCore(createClientForCore(solrServer, core), core); + } + } + + @Override + public SolrClient getSolrClient(String core) { + if (!StringUtils.hasText(core)) { + return getSolrClient(); + } + + if (createMissingSolrClient && !clientMap.containsKey(core)) { + clientMap.put(core, createClientForCore(getSolrClient(), core)); + } + return clientMap.get(core); + } + + /** + * Add SolrClient for core to factory - Will override existing. + * + * @param solrClient + * @param core + */ + public void addSolrClientForCore(SolrClient solrClient, String core) { + clientMap.put(core, solrClient); + } + + /** + * Remove SolrClient from factory. Calls {@link SolrClient#shutdown()} on remove. + * + * @param core + */ + public void removeSolrClient(String core) { + if (clientMap.containsKey(core)) { + destroy(clientMap.remove(core)); + } + } + + /** + * Get configured {@link SolrClient} for specific class tying to determine core name via {@link SolrDocument} or its + * class name. + * + * @param clazz + * @return + */ + public SolrClient getSolrClient(Class clazz) { + Assert.notNull(clazz, "Clazz must not be null!"); + + String coreName = SolrClientUtils.resolveSolrCoreName(clazz); + return getSolrClient(StringUtils.hasText(coreName) ? coreName : getShortClassName(clazz)); + } + + /** + * Get the class short name. Strips the outer class name in case of an inner class. + * + * @param clazz + * @see ClassUtils#getShortName(Class) + * @return + */ + protected static String getShortClassName(Class clazz) { + String shortName = ClassUtils.getShortName(clazz); + int dotIndex = shortName.lastIndexOf('.'); + return (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName); + } + + @Override + public List getCores() { + return new ArrayList(clientMap.keySet()); + } + + @Override + public void destroy() { + super.destroy(); + for (SolrClient server : clientMap.values()) { + destroy(server); + } + } + + protected SolrClient createClientForCore(SolrClient reference, String core) { + if (StringUtils.hasText(core)) { + return SolrClientUtils.clone(reference, core); + } + return reference; + } + + public boolean isCreateMissingSolrClient() { + return createMissingSolrClient; + } + + /** + * if true missing solrServers for cores will be created + * + * @param createMissingSolrClient default is true + */ + public void setCreateMissingSolrClient(boolean createMissingSolrClient) { + this.createMissingSolrClient = createMissingSolrClient; + } + +} diff --git a/src/main/java/org/springframework/data/solr/server/support/SolrClientFactoryBase.java b/src/main/java/org/springframework/data/solr/server/support/SolrClientFactoryBase.java index 2d2bc7e..03f71f4 100644 --- a/src/main/java/org/springframework/data/solr/server/support/SolrClientFactoryBase.java +++ b/src/main/java/org/springframework/data/solr/server/support/SolrClientFactoryBase.java @@ -19,8 +19,6 @@ import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.springframework.beans.factory.DisposableBean; import org.springframework.data.solr.server.SolrClientFactory; -import org.springframework.lang.Nullable; -import org.springframework.util.Assert; /** * {@link SolrClientFactoryBase} replaces SolrServerFactoryBase from version 1.x. @@ -30,7 +28,7 @@ */ abstract class SolrClientFactoryBase implements SolrClientFactory, DisposableBean { - private @Nullable SolrClient solrClient; + private SolrClient solrClient; public SolrClientFactoryBase() { @@ -46,9 +44,6 @@ protected final boolean isHttpSolrClient(SolrClient solrClient) { @Override public SolrClient getSolrClient() { - - Assert.state(solrClient != null, "SolrClient has not been initialized."); - return this.solrClient; } diff --git a/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java b/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java index 0c27c92..c627710 100644 --- a/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java +++ b/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java @@ -15,17 +15,37 @@ */ package org.springframework.data.solr.server.support; +import java.beans.PropertyDescriptor; import java.io.Closeable; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.lang3.StringUtils; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.HttpParams; import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; +import org.apache.solr.client.solrj.impl.CloudSolrClient; +import org.apache.solr.client.solrj.impl.LBHttpSolrClient; +import org.apache.solr.core.CoreContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanInstantiationException; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeanWrapperImpl; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.data.solr.VersionUtil; import org.springframework.data.solr.core.mapping.SolrDocument; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** @@ -56,6 +76,66 @@ public static String resolveSolrCoreName(Class type) { return ""; } + public static T clone(T solrClient) { + return clone(solrClient, null); + } + + /** + * Create a clone of given {@link SolrClient} and modify baseUrl of clone to point to the given core. + * + * @param solrClient Non null reference {@link SolrClient} to copy properties from. + * @param core Name of solr core to point to. + * @return + * @throws BeanInstantiationException if creating instance failed + */ + @SuppressWarnings("unchecked") + public static T clone(T solrClient, String core) { + Assert.notNull(solrClient, "SolrClient must not be null!"); + String shortName = getSolrClientTypeName(solrClient); + if (shortName.equals("SolrClient")) { // cannot create instance of abstract class, + return solrClient; + } + + SolrClient clone = null; + if (shortName.equals("HttpSolrClient")) { + clone = cloneHttpSolrClient(solrClient, core); + } else if (shortName.equals("LBHttpSolrClient")) { + clone = cloneLBHttpSolrClient(solrClient, core); + } else if (shortName.equals("CloudSolrClient")) { + clone = cloneCloudSolrClient(solrClient, core); + } else if (shortName.equals("EmbeddedSolrServer")) { + clone = cloneEmbeddedSolrServer(solrClient, core); + } + + if (clone == null) { + throw new BeanInstantiationException(solrClient.getClass(), "Cannot create instace of " + shortName + "."); + } + + copyProperties(solrClient, clone); + return (T) clone; + } + + /** + * Append core to given baseUrl + * + * @param baseUrl + * @param core + * @return + */ + public static String appendCoreToBaseUrl(String baseUrl, String core) { + Assert.notNull(baseUrl, "Solr baseUrl must not be null!"); + + if (!org.springframework.util.StringUtils.hasText(core)) { + return baseUrl; + } + String url = baseUrl; + if (!StringUtils.endsWith(baseUrl, SLASH)) { + url = url + SLASH; + } + url = url + core; + return url; + } + /** * Close the {@link SolrClient} by calling {@link SolrClient#close()} or {@code shutdown} for the generation 5 * libraries. @@ -81,4 +161,211 @@ public static void close(SolrClient solrClient) { throw new DataAccessResourceFailureException("Cannot close SolrClient", e); } } + + private static String getSolrClientTypeName(SolrClient solrClient) { + Class solrClientType = ClassUtils.isCglibProxy(solrClient) ? ClassUtils.getUserClass(solrClient) + : solrClient.getClass(); + String shortName = ClassUtils.getShortName(solrClientType); + return shortName; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static SolrClient cloneEmbeddedSolrServer(SolrClient solrClient, String core) { + + CoreContainer coreContainer = ((EmbeddedSolrServer) solrClient).getCoreContainer(); + try { + Constructor constructor = ClassUtils.getConstructorIfAvailable(solrClient.getClass(), CoreContainer.class, + String.class); + return (SolrClient) BeanUtils.instantiateClass(constructor, coreContainer, core); + } catch (Exception e) { + throw new BeanInstantiationException(solrClient.getClass(), + "Cannot create instace of " + solrClient.getClass() + ".", e); + } + } + + private static SolrClient cloneHttpSolrClient(SolrClient solrClient, String core) { + if (solrClient == null) { + return null; + } + + Method baseUrlGetterMethod = ClassUtils.getMethodIfAvailable(solrClient.getClass(), "getBaseURL"); + if (baseUrlGetterMethod == null) { + return null; + } + + String baseUrl = (String) ReflectionUtils.invokeMethod(baseUrlGetterMethod, solrClient); + String url = appendCoreToBaseUrl(baseUrl, core); + + try { + + HttpClient clientToUse = readAndCloneHttpClient(solrClient); + + if (clientToUse != null) { + Constructor constructor = (Constructor) ClassUtils + .getConstructorIfAvailable(solrClient.getClass(), String.class, HttpClient.class); + if (constructor != null) { + return (SolrClient) BeanUtils.instantiateClass(constructor, url, clientToUse); + } + } + + Constructor constructor = (Constructor) ClassUtils + .getConstructorIfAvailable(solrClient.getClass(), String.class); + return (SolrClient) BeanUtils.instantiateClass(constructor, url); + } catch (Exception e) { + throw new BeanInstantiationException(solrClient.getClass(), + "Cannot create instace of " + solrClient.getClass() + ". ", e); + } + } + + private static LBHttpSolrClient cloneLBHttpSolrClient(SolrClient solrClient, String core) { + if (solrClient == null) { + return null; + } + + LBHttpSolrClient clone = null; + try { + if (VersionUtil.isSolr3XAvailable()) { + clone = cloneSolr3LBHttpServer(solrClient, core); + } else if (VersionUtil.isSolr4XAvailable() || VersionUtil.isSolr5XAvailable()) { + clone = cloneSolr4LBHttpServer(solrClient, core); + } + } catch (Exception e) { + throw new BeanInstantiationException(solrClient.getClass(), + "Cannot create instace of " + solrClient.getClass() + ". ", e); + } + Object o = readField(solrClient, "interval"); + if (o != null) { + clone.setAliveCheckInterval(Integer.valueOf(o.toString()).intValue()); + } + return clone; + } + + private static SolrClient cloneCloudSolrClient(SolrClient solrClient, String core) { + if (VersionUtil.isSolr3XAvailable() || solrClient == null) { + return null; + } + + CloudSolrClient cloudServer = (CloudSolrClient) solrClient; + String zkHost = readField(solrClient, "zkHost"); + + Constructor constructor = (Constructor) ClassUtils + .getConstructorIfAvailable(solrClient.getClass(), String.class, LBHttpSolrClient.class); + + CloudSolrClient clone = (CloudSolrClient) BeanUtils.instantiateClass(constructor, zkHost, + cloneLBHttpSolrClient(cloudServer.getLbClient(), core)); + + if (org.springframework.util.StringUtils.hasText(core)) { + clone.setDefaultCollection(core); + } + return clone; + } + + private static LBHttpSolrClient cloneSolr3LBHttpServer(SolrClient solrClient, String core) + throws MalformedURLException { + CopyOnWriteArrayList list = readField(solrClient, "aliveServers"); + + String[] servers = new String[list.size()]; + for (int i = 0; i < list.size(); i++) { + servers[i] = appendCoreToBaseUrl(list.get(i).toString(), core); + } + return new LBHttpSolrClient(servers); + } + + private static LBHttpSolrClient cloneSolr4LBHttpServer(SolrClient solrClient, String core) + throws MalformedURLException, InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException { + Map map = readField(solrClient, "aliveServers"); + + String[] servers = new String[map.size()]; + int i = 0; + for (String key : map.keySet()) { + servers[i] = appendCoreToBaseUrl(key, core); + i++; + } + + Boolean isInternalCient = readField(solrClient, "clientIsInternal"); + + if (isInternalCient != null && !isInternalCient) { + HttpClient clientToUse = readAndCloneHttpClient(solrClient); + return new LBHttpSolrClient(clientToUse, servers); + } + return new LBHttpSolrClient(servers); + } + + private static HttpClient readAndCloneHttpClient(SolrClient solrClient) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + + HttpClient sourceClient = readField(solrClient, "httpClient"); + return cloneHttpClient(sourceClient); + } + + private static HttpClient cloneHttpClient(HttpClient sourceClient) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + + if (sourceClient == null) { + return null; + } + + Class clientType = ClassUtils.getUserClass(sourceClient); + + Constructor constructor = ClassUtils.getConstructorIfAvailable(clientType, ClientConnectionManager.class, + HttpParams.class); + if (constructor != null) { + + HttpClient targetClient = (HttpClient) constructor.newInstance(sourceClient.getConnectionManager(), + sourceClient.getParams()); + BeanUtils.copyProperties(sourceClient, targetClient); + return targetClient; + } + + constructor = ClassUtils.getConstructorIfAvailable(clientType, HttpParams.class); + if (constructor != null) { + + HttpClient targetClient = (HttpClient) constructor.newInstance(sourceClient.getParams()); + BeanUtils.copyProperties(sourceClient, targetClient); + return targetClient; + } else { + return new DefaultHttpClient(sourceClient.getParams()); + } + + } + + @SuppressWarnings("unchecked") + private static T readField(SolrClient solrServer, String fieldName) { + Field field = ReflectionUtils.findField(solrServer.getClass(), fieldName); + if (field == null) { + return null; + } + ReflectionUtils.makeAccessible(field); + return (T) ReflectionUtils.getField(field, solrServer); + } + + /** + * Solr property names do not match the getters/setters used for them. Check on any write method, try to find the + * according property and set the value for it. Will ignore all other, and nested properties + * + * @param source + * @param target + */ + private static void copyProperties(SolrClient source, SolrClient target) { + BeanWrapperImpl wrapperImpl = new BeanWrapperImpl(source); + for (PropertyDescriptor pd : wrapperImpl.getPropertyDescriptors()) { + Method writer = pd.getWriteMethod(); + if (writer != null) { + try { + Field property = ReflectionUtils.findField(source.getClass(), pd.getName()); + if (property != null) { + ReflectionUtils.makeAccessible(property); + Object o = ReflectionUtils.getField(property, source); + if (o != null) { + writer.invoke(target, o); + } + } + } catch (Exception e) { + logger.warn("Could not copy property value for: " + pd.getName(), e); + } + } + } + } + } diff --git a/src/main/java/org/springframework/data/solr/server/support/package-info.java b/src/main/java/org/springframework/data/solr/server/support/package-info.java deleted file mode 100644 index 6612f53..0000000 --- a/src/main/java/org/springframework/data/solr/server/support/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Everything {@link org.apache.solr.client.solrj.SolrClient} and - * {@link org.apache.solr.client.solrj.embedded.EmbeddedSolrServer} related. - */ -@org.springframework.lang.NonNullApi -@org.springframework.lang.NonNullFields -package org.springframework.data.solr.server.support; diff --git a/src/main/resources/META-INF/spring.schemas b/src/main/resources/META-INF/spring.schemas index 6e6d294..0089da1 100644 --- a/src/main/resources/META-INF/spring.schemas +++ b/src/main/resources/META-INF/spring.schemas @@ -1,4 +1,3 @@ http\://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd=org/springframework/data/solr/config/spring-solr-1.0.xsd http\://www.springframework.org/schema/data/solr/spring-solr-2.0.xsd=org/springframework/data/solr/config/spring-solr-2.0.xsd -http\://www.springframework.org/schema/data/solr/spring-solr-3.0.xsd=org/springframework/data/solr/config/spring-solr-3.0.xsd -http\://www.springframework.org/schema/data/solr/spring-solr.xsd=org/springframework/data/solr/config/spring-solr-3.0.xsd +http\://www.springframework.org/schema/data/solr/spring-solr.xsd=org/springframework/data/solr/config/spring-solr-2.0.xsd diff --git a/src/main/resources/changelog.txt b/src/main/resources/changelog.txt index 0dd8b3e..2419c9f 100644 --- a/src/main/resources/changelog.txt +++ b/src/main/resources/changelog.txt @@ -1,23 +1,6 @@ Spring Data Solr Changelog ========================== -Changes in version 3.0.2.RELEASE (2017-11-27) ---------------------------------------------- -* DATASOLR-431 - Release 3.0.2 (Kay SR2). - - -Changes in version 2.1.9.RELEASE (2017-11-27) ---------------------------------------------- -* DATASOLR-433 - Fix mock setup in SimpleSolrPersitentPropertyFieldNameTests after changes in Spring Data Commons. -* DATASOLR-426 - Release 2.1.9 (Ingalls SR9). - - -Changes in version 3.0.1.RELEASE (2017-10-27) ---------------------------------------------- -* DATASOLR-429 - Adapt to changes in AbstractPersistentProperty. -* DATASOLR-424 - Release 3.0.1 (Kay SR1). - - Changes in version 2.1.8.RELEASE (2017-10-11) --------------------------------------------- * DATASOLR-419 - Release 2.1.8 (Ingalls SR8). diff --git a/src/main/resources/notice.txt b/src/main/resources/notice.txt index b300a52..446745e 100644 --- a/src/main/resources/notice.txt +++ b/src/main/resources/notice.txt @@ -1,4 +1,4 @@ -Spring Data for Apache Solr 3.0 GA +Spring Data for Apache Solr 2.1.8 Copyright (c) [2013-2015] Pivotal Software, Inc. This product is licensed to you under the Apache License, Version 2.0 (the "License"). diff --git a/src/main/resources/org/springframework/data/solr/config/spring-solr-3.0.xsd b/src/main/resources/org/springframework/data/solr/config/spring-solr-3.0.xsd deleted file mode 100644 index a184d47..0000000 --- a/src/main/resources/org/springframework/data/solr/config/spring-solr-3.0.xsd +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/test/java/org/springframework/data/solr/AbstractITestWithEmbeddedSolrServer.java b/src/test/java/org/springframework/data/solr/AbstractITestWithEmbeddedSolrServer.java index 3ba7e0e..6163420 100644 --- a/src/test/java/org/springframework/data/solr/AbstractITestWithEmbeddedSolrServer.java +++ b/src/test/java/org/springframework/data/solr/AbstractITestWithEmbeddedSolrServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -29,16 +29,15 @@ */ public abstract class AbstractITestWithEmbeddedSolrServer { - protected static final String COLLECTION_NAME = "collection1"; - protected static final String DEFAULT_BEAN_ID = "1"; + protected static String DEFAULT_BEAN_ID = "1"; public static @ClassRule org.springframework.data.solr.test.util.EmbeddedSolrServer server = org.springframework.data.solr.test.util.EmbeddedSolrServer .configure(new ClassPathResource("static-schema"), ClientCache.ENABLED); public void cleanDataInSolr() throws SolrServerException, IOException { - server.getSolrClient(COLLECTION_NAME).deleteByQuery("*:*"); - server.getSolrClient(COLLECTION_NAME).commit(); + server.getSolrClient("collection1").deleteByQuery("*:*"); + server.getSolrClient("collection1").commit(); } public ExampleSolrBean createDefaultExampleBean() { @@ -54,7 +53,7 @@ public List createBeansWithId(int nrObjectsToCreate) { } public List createBeansWithIdAndPrefix(int nrObjectsToCreate, String idPrefix) { - ArrayList list = new ArrayList<>(nrObjectsToCreate); + ArrayList list = new ArrayList(nrObjectsToCreate); for (int i = 1; i <= nrObjectsToCreate; i++) { list.add(createExampleBeanWithId(idPrefix != null ? (idPrefix + Integer.toString(i)) : Integer.toString(i))); } diff --git a/src/test/java/org/springframework/data/solr/ExampleSolrBean.java b/src/test/java/org/springframework/data/solr/ExampleSolrBean.java index 46e61ce..84da6b4 100644 --- a/src/test/java/org/springframework/data/solr/ExampleSolrBean.java +++ b/src/test/java/org/springframework/data/solr/ExampleSolrBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ public class ExampleSolrBean { @Version @Field("_version_") private Long version; public ExampleSolrBean() { - this.category = new ArrayList<>(); + this.category = new ArrayList(); } public ExampleSolrBean(String id, String name, String category) { diff --git a/src/test/java/org/springframework/data/solr/HttpSolrClientFactoryTests.java b/src/test/java/org/springframework/data/solr/HttpSolrClientFactoryTests.java index 35beff3..5e22a4f 100644 --- a/src/test/java/org/springframework/data/solr/HttpSolrClientFactoryTests.java +++ b/src/test/java/org/springframework/data/solr/HttpSolrClientFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -17,6 +17,7 @@ import java.net.MalformedURLException; +import org.apache.commons.lang3.StringUtils; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.params.AuthPNames; @@ -51,10 +52,39 @@ public void tearDown() { @Test public void testInitFactory() { HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient); + Assert.assertNotNull(factory.getCores()); + Assert.assertThat(factory.getCores(), IsEmptyCollection.emptyCollectionOf(String.class)); Assert.assertEquals(solrClient, factory.getSolrClient()); Assert.assertEquals(URL, ((HttpSolrClient) factory.getSolrClient()).getBaseURL()); } + @Test + public void testFactoryReturnsReferenceSolrClientWhenCallingGetWithCoreNameAndNoCoreSet() { + HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient); + Assert.assertEquals(solrClient, factory.getSolrClient("AnyCoreName")); + } + + @Test + public void testInitFactoryWithCore() throws MalformedURLException { + HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, "core"); + Assert.assertEquals(URL + "/core", ((HttpSolrClient) factory.getSolrClient()).getBaseURL()); + + factory = new HttpSolrClientFactory(new HttpSolrClient(URL + "/"), "core"); + Assert.assertEquals(URL + "/core", ((HttpSolrClient) factory.getSolrClient()).getBaseURL()); + } + + @Test + public void testFactoryReturnsReferenceSolrClientWhenCallingGetWithCoreNameAndCoreSet() { + HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, "core"); + Assert.assertEquals(solrClient, factory.getSolrClient("AnyCoreName")); + } + + @Test + public void testInitFactoryWithEmptyCore() { + HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, StringUtils.EMPTY); + Assert.assertEquals(URL, ((HttpSolrClient) factory.getSolrClient()).getBaseURL()); + } + @Test(expected = IllegalArgumentException.class) public void testInitFactoryWithNullServer() { new HttpSolrClientFactory(null); @@ -62,23 +92,21 @@ public void testInitFactoryWithNullServer() { @Test public void testInitFactoryWithAuthentication() { - HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, - new UsernamePasswordCredentials("username", "password"), "BASIC"); + HttpSolrClientFactory factory = new HttpSolrClientFactory(solrClient, "core", new UsernamePasswordCredentials( + "username", "password"), "BASIC"); AbstractHttpClient solrHttpClient = (AbstractHttpClient) ((HttpSolrClient) factory.getSolrClient()).getHttpClient(); Assert.assertNotNull(solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY)); Assert.assertNotNull(solrHttpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF)); - Assert.assertEquals("username", - ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY)) - .getUserName()); - Assert.assertEquals("password", - ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider().getCredentials(AuthScope.ANY)) - .getPassword()); + Assert.assertEquals("username", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider() + .getCredentials(AuthScope.ANY)).getUserName()); + Assert.assertEquals("password", ((UsernamePasswordCredentials) solrHttpClient.getCredentialsProvider() + .getCredentials(AuthScope.ANY)).getPassword()); } @Test(expected = IllegalArgumentException.class) public void testInitFactoryWithoutAuthenticationSchema() { - new HttpSolrClientFactory(solrClient, new UsernamePasswordCredentials("username", "password"), ""); + new HttpSolrClientFactory(solrClient, "core", new UsernamePasswordCredentials("username", "password"), ""); } } diff --git a/src/test/java/org/springframework/data/solr/SolrRealtimeGetRequestUnitTests.java b/src/test/java/org/springframework/data/solr/SolrRealtimeGetRequestUnitTests.java new file mode 100644 index 0000000..88d8a95 --- /dev/null +++ b/src/test/java/org/springframework/data/solr/SolrRealtimeGetRequestUnitTests.java @@ -0,0 +1,68 @@ +/* + * 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. + * 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.solr; + +import static org.mockito.Mockito.*; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.util.NamedList; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +/** + * @author Francisco Spaeth + * @author Christoph Strobl + */ +@RunWith(MockitoJUnitRunner.class) +public class SolrRealtimeGetRequestUnitTests { + + private @Mock SolrClient solrClientMock; + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExeptionWhenNoIdsGiven() { + new SolrRealtimeGetRequest(); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExeptionWhenIdsContainsNullValue() { + new SolrRealtimeGetRequest(1, 2, null); + } + + @Test // DATASOLR-83 + public void testCreationOfRealtimeGet() throws SolrServerException, IOException { + + // given + NamedList value = new NamedList(); + SolrRealtimeGetRequest request = new SolrRealtimeGetRequest(1L, 2F, 3, "4"); + when(solrClientMock.request(request)).thenReturn(value); + + // when + QueryResponse result = request.process(solrClientMock); + + // then + Assert.assertEquals(value, result.getResponse()); + Assert.assertArrayEquals(new String[] { "1", "2.0", "3", "4" }, request.getParams().getParams("ids")); + verify(solrClientMock).request(request); + } + +} diff --git a/src/test/java/org/springframework/data/solr/core/DefaultQueryParserTests.java b/src/test/java/org/springframework/data/solr/core/DefaultQueryParserTests.java index 3630dac..e7a19a2 100644 --- a/src/test/java/org/springframework/data/solr/core/DefaultQueryParserTests.java +++ b/src/test/java/org/springframework/data/solr/core/DefaultQueryParserTests.java @@ -1081,7 +1081,7 @@ public void pageableUsingZeroShouldBeParsedCorrectlyWhenSetUsingPageable() { @Test // DATASOLR-112 public void pageableUsingZeroShouldBeParsedCorrectlyWhenSetUsingExplititMethods() { - SimpleQuery query = new SimpleQuery("*:*").setOffset(0L).setRows(0); + SimpleQuery query = new SimpleQuery("*:*").setOffset(0).setRows(0); assertPaginationPresent(queryParser.constructSolrQuery(query), 0, 0); } @@ -1526,7 +1526,7 @@ public void testRegularNumericRangeFacets() { assertNull("all", solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_OTHER)); } - @Test // DATASOLR-86, DATASOLR-309 + @Test // DATASOLR-86 public void testRegularDateRangeFacets() { FacetOptions facetOptions = new FacetOptions() // @@ -1563,35 +1563,35 @@ public void testRegularDateRangeFacets() { // RANGE is being used on SolrJ even for DATE fields assertEquals("1970-01-01T00:00:00.100Z", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_START)); assertEquals("+1DAY", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_GAP)); - assertEquals("1970-01-01T02:46:40Z", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_END)); + assertEquals("1970-01-01T02:46:40.000Z", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_END)); assertEquals("true", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_HARD_END)); assertEquals("all", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_INCLUDE)); assertEquals("all", solrQuery.getFieldParam("field1", FacetParams.FACET_RANGE_OTHER)); assertEquals("1970-01-01T00:00:00.100Z", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_START)); assertEquals("+2DAY", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_GAP)); - assertEquals("1970-01-01T02:46:40Z", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_END)); + assertEquals("1970-01-01T02:46:40.000Z", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_END)); assertNull(solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_HARD_END)); assertEquals("outer", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_INCLUDE)); assertEquals("none", solrQuery.getFieldParam("field2", FacetParams.FACET_RANGE_OTHER)); assertEquals("1970-01-01T00:00:00.100Z", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_START)); assertEquals("+2DAY", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_GAP)); - assertEquals("1970-01-01T02:46:40Z", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_END)); + assertEquals("1970-01-01T02:46:40.000Z", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_END)); assertEquals("true", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_HARD_END)); assertNull(solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_INCLUDE)); assertEquals("none", solrQuery.getFieldParam("field3", FacetParams.FACET_RANGE_OTHER)); assertEquals("1970-01-01T00:00:00.100Z", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_START)); assertEquals("+2DAY", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_GAP)); - assertEquals("1970-01-01T02:46:40Z", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_END)); + assertEquals("1970-01-01T02:46:40.000Z", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_END)); assertEquals("true", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_HARD_END)); assertEquals("outer", solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_INCLUDE)); assertNull(solrQuery.getFieldParam("field4", FacetParams.FACET_RANGE_OTHER)); assertEquals("1970-01-01T00:00:00.100Z", solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_START)); assertEquals("+2DAY", solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_GAP)); - assertEquals("1970-01-01T02:46:40Z", solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_END)); + assertEquals("1970-01-01T02:46:40.000Z", solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_END)); assertNull(solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_HARD_END)); assertNull(solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_INCLUDE)); assertNull(solrQuery.getFieldParam("field5", FacetParams.FACET_RANGE_OTHER)); diff --git a/src/test/java/org/springframework/data/solr/core/FunctionQueryFragmentTests.java b/src/test/java/org/springframework/data/solr/core/FunctionQueryFragmentTests.java index 10b0866..3d17a51 100644 --- a/src/test/java/org/springframework/data/solr/core/FunctionQueryFragmentTests.java +++ b/src/test/java/org/springframework/data/solr/core/FunctionQueryFragmentTests.java @@ -97,13 +97,13 @@ public static Collection data() { { DistanceFunction.sparsenessDistance().between(new Point(1, 2, 3), new Point(4, 5, 6)), "{!func}dist(0,1.0,2.0,3.0,4.0,5.0,6.0)" }, { DivideFunction.divide(new Foo()).by(new Bar()), "{!func}div(foo(),bar())" }, - { DivideFunction.divide(new Foo()).by(3L), "{!func}div(foo(),3)" }, + { DivideFunction.divide(new Foo()).by(Long.valueOf(3)), "{!func}div(foo(),3)" }, { DivideFunction.divide(new Foo()).by("field_1"), "{!func}div(foo(),field_1)" }, { DivideFunction.divide(new Foo()).by(new SimpleField("field_1")), "{!func}div(foo(),field_1)" }, - { DivideFunction.divide(3L).by(new Bar()), "{!func}div(3,bar())" }, - { DivideFunction.divide(3L).by(3L), "{!func}div(3,3)" }, - { DivideFunction.divide(3L).by("field_1"), "{!func}div(3,field_1)" }, - { DivideFunction.divide(3L).by(new SimpleField("field_1")), "{!func}div(3,field_1)" }, + { DivideFunction.divide(Long.valueOf(3)).by(new Bar()), "{!func}div(3,bar())" }, + { DivideFunction.divide(Long.valueOf(3)).by(Long.valueOf(3)), "{!func}div(3,3)" }, + { DivideFunction.divide(Long.valueOf(3)).by("field_1"), "{!func}div(3,field_1)" }, + { DivideFunction.divide(Long.valueOf(3)).by(new SimpleField("field_1")), "{!func}div(3,field_1)" }, { DivideFunction.divide("field_1").by(new Bar()), "{!func}div(field_1,bar())" }, { DivideFunction.divide("field_1").by(3), "{!func}div(field_1,3)" }, { DivideFunction.divide("field_1").by("field_2"), "{!func}div(field_1,field_2)" }, @@ -129,28 +129,36 @@ public static Collection data() { { IfFunction.when(new SimpleField("field_1")).then(new Foo()).otherwise(new Bar()), "{!func}if(field_1,foo(),bar())" }, { MaxFunction.max(new Foo(), new Bar()), "{!func}max(foo(),bar())" }, - { MaxFunction.max(new Foo(), 3L), + { MaxFunction.max(new Foo(), Long.valueOf(3)), "{!func}max(foo(),3)" }, - { MaxFunction.max(new Foo(), "field_1"), "{!func}max(foo(),field_1)" }, - { MaxFunction.max(3L, new Bar()), "{!func}max(3,bar())" }, { MaxFunction.max(3L, 4L), "{!func}max(3,4)" }, - { MaxFunction.max(3L, "field_1"), "{!func}max(3,field_1)" }, - { MaxFunction.max("field_1", new Bar()), "{!func}max(field_1,bar())" }, - { MaxFunction.max("field_1", 3L), "{!func}max(field_1,3)" }, - { MaxFunction.max("field_1", "field_2"), "{!func}max(field_1,field_2)" }, + { MaxFunction.max(new Foo(), "field_1"), + "{!func}max(foo(),field_1)" }, + { MaxFunction.max(Long.valueOf(3), new Bar()), + "{!func}max(3,bar())" }, + { MaxFunction.max(Long.valueOf(3), Long.valueOf(4)), + "{!func}max(3,4)" }, + { MaxFunction.max(Long.valueOf(3), "field_1"), + "{!func}max(3,field_1)" }, + { MaxFunction.max("field_1", new Bar()), + "{!func}max(field_1,bar())" }, + { MaxFunction.max("field_1", Long.valueOf(3)), + "{!func}max(field_1,3)" }, + { MaxFunction.max("field_1", "field_2"), + "{!func}max(field_1,field_2)" }, { NotFunction.not("field_1"), "{!func}not(field_1)" }, { NotFunction.not(new Foo()), "{!func}not(foo())" }, { NotFunction.not(new SimpleField("field_1")), "{!func}not(field_1)" }, { ProductFunction.product("field_1").times("field_2").build(), "{!func}product(field_1,field_2)" }, { ProductFunction.product(new SimpleField("field_1")).times("field_2").build(), "{!func}product(field_1,field_2)" }, - { ProductFunction.product(3L).times("field_2").build(), "{!func}product(3,field_2)" }, + { ProductFunction.product(Long.valueOf(3)).times("field_2").build(), "{!func}product(3,field_2)" }, { ProductFunction.product("field_1").times("field_2").build(), "{!func}product(field_1,field_2)" }, { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).build(), "{!func}product(foo(),field_1)" }, { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).times(new Bar()).build(), "{!func}product(foo(),field_1,bar())" }, - { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).times(new Bar()).times(3L).build(), - "{!func}product(foo(),field_1,bar(),3)" }, - { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).times(new Bar()).times(3L) + { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).times(new Bar()).times(Long.valueOf(3)) + .build(), "{!func}product(foo(),field_1,bar(),3)" }, + { ProductFunction.product(new Foo()).times(new SimpleField("field_1")).times(new Bar()).times(Long.valueOf(3)) .times(new SimpleField("field_2")).build(), "{!func}product(foo(),field_1,bar(),3,field_2)" }, { QueryFunction.query(new Criteria("field_1").is("value")), "{!func}query(field_1:value)" }, { QueryFunction.query(new SimpleQuery(new Criteria("field_1").is("value"))), "{!func}query(field_1:value)" }, diff --git a/src/test/java/org/springframework/data/solr/core/ITestSolrTemplate.java b/src/test/java/org/springframework/data/solr/core/ITestSolrTemplate.java index 9eb06d0..8e6ebbe 100644 --- a/src/test/java/org/springframework/data/solr/core/ITestSolrTemplate.java +++ b/src/test/java/org/springframework/data/solr/core/ITestSolrTemplate.java @@ -22,8 +22,6 @@ import static org.hamcrest.core.IsNull.*; import static org.junit.Assert.*; -import lombok.Data; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -33,18 +31,21 @@ import java.util.GregorianCalendar; import java.util.List; import java.util.Map; -import java.util.Optional; import javax.xml.parsers.ParserConfigurationException; +import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.beans.Field; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.FacetParams; +import org.apache.solr.common.params.FacetParams.FacetRangeInclude; +import org.apache.solr.common.params.FacetParams.FacetRangeOther; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; @@ -56,16 +57,42 @@ import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.geo.Point; -import org.springframework.data.mapping.MappingException; +import org.springframework.data.mapping.model.MappingException; import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer; import org.springframework.data.solr.ExampleSolrBean; import org.springframework.data.solr.UncategorizedSolrException; -import org.springframework.data.solr.core.query.*; +import org.springframework.data.solr.core.query.Criteria; +import org.springframework.data.solr.core.query.DistanceField; +import org.springframework.data.solr.core.query.FacetAndHighlightQuery; +import org.springframework.data.solr.core.query.FacetOptions; import org.springframework.data.solr.core.query.FacetOptions.FacetSort; import org.springframework.data.solr.core.query.FacetOptions.FieldWithDateRangeParameters; import org.springframework.data.solr.core.query.FacetOptions.FieldWithFacetParameters; import org.springframework.data.solr.core.query.FacetOptions.FieldWithNumericRangeParameters; +import org.springframework.data.solr.core.query.FacetQuery; +import org.springframework.data.solr.core.query.Function; +import org.springframework.data.solr.core.query.GroupOptions; +import org.springframework.data.solr.core.query.HighlightOptions; +import org.springframework.data.solr.core.query.IfFunction; +import org.springframework.data.solr.core.query.Join; +import org.springframework.data.solr.core.query.PartialUpdate; +import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.Query.Operator; +import org.springframework.data.solr.core.query.QueryFunction; +import org.springframework.data.solr.core.query.SimpleFacetAndHighlightQuery; +import org.springframework.data.solr.core.query.SimpleFacetQuery; +import org.springframework.data.solr.core.query.SimpleField; +import org.springframework.data.solr.core.query.SimpleFilterQuery; +import org.springframework.data.solr.core.query.SimpleHighlightQuery; +import org.springframework.data.solr.core.query.SimpleQuery; +import org.springframework.data.solr.core.query.SimpleStringCriteria; +import org.springframework.data.solr.core.query.SimpleTermsQuery; +import org.springframework.data.solr.core.query.SimpleUpdateField; +import org.springframework.data.solr.core.query.SpellcheckOptions; +import org.springframework.data.solr.core.query.StatsOptions; +import org.springframework.data.solr.core.query.TermsQuery; +import org.springframework.data.solr.core.query.Update; +import org.springframework.data.solr.core.query.UpdateAction; import org.springframework.data.solr.core.query.result.Cursor; import org.springframework.data.solr.core.query.result.FacetFieldEntry; import org.springframework.data.solr.core.query.result.FacetPivotFieldEntry; @@ -80,11 +107,13 @@ import org.springframework.data.solr.core.query.result.StatsResult; import org.springframework.data.solr.core.query.result.TermsFieldEntry; import org.springframework.data.solr.core.query.result.TermsPage; -import org.springframework.data.solr.server.support.HttpSolrClientFactory; +import org.springframework.data.solr.server.support.MulticoreSolrClientFactory; import org.xml.sax.SAXException; import com.google.common.collect.Lists; +import lombok.Data; + /** * @author Christoph Strobl * @author Andrey Paramonov @@ -102,142 +131,132 @@ public class ITestSolrTemplate extends AbstractITestWithEmbeddedSolrServer { @Before public void setUp() throws IOException, ParserConfigurationException, SAXException { - solrTemplate = new SolrTemplate(server); + solrTemplate = new SolrTemplate(server, "collection1"); solrTemplate.afterPropertiesSet(); } @After public void tearDown() { - solrTemplate.delete(COLLECTION_NAME, ALL_DOCUMENTS_QUERY); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.delete(ALL_DOCUMENTS_QUERY); + solrTemplate.commit(); } @Test public void testBeanLifecycle() { ExampleSolrBean toInsert = createDefaultExampleBean(); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, - new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); - assertFalse(recalled.isPresent()); - solrTemplate.commit(COLLECTION_NAME); - - recalled = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery(new Criteria("id").is("1")), + solrTemplate.saveBean(toInsert); + ExampleSolrBean recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); - assertTrue(recalled.isPresent()); - assertEquals(toInsert.getId(), recalled.get().getId()); + Assert.assertNull(recalled); + solrTemplate.commit(); - solrTemplate.deleteByIds(COLLECTION_NAME, toInsert.getId()); - recalled = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery(new Criteria("id").is("1")), - ExampleSolrBean.class); - assertEquals(toInsert.getId(), recalled.get().getId()); + recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - solrTemplate.commit(COLLECTION_NAME); - recalled = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery(new Criteria("id").is("1")), - ExampleSolrBean.class); - assertFalse(recalled.isPresent()); + solrTemplate.deleteById(toInsert.getId()); + recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); + Assert.assertEquals(toInsert.getId(), recalled.getId()); + + solrTemplate.commit(); + recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); + Assert.assertNull(recalled); } @Test public void testPartialUpdateSetSingleValueField() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.add("name", "updated-name"); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(toInsert.getId(), recalled.get().getId()); - assertEquals("updated-name", recalled.get().getName()); - assertEquals(toInsert.getPopularity(), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getId(), recalled.getId()); + Assert.assertEquals("updated-name", recalled.getName()); + Assert.assertEquals(toInsert.getPopularity(), recalled.getPopularity()); } @Test public void testPartialUpdateAddSingleValueToMultivalueField() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - toInsert.setCategory(Collections.singletonList("nosql")); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + toInsert.setCategory(Arrays.asList("nosql")); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.add(new SimpleUpdateField("cat", "spring-data-solr", UpdateAction.ADD)); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(toInsert.getId(), recalled.get().getId()); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - assertEquals(2, recalled.get().getCategory().size()); - assertEquals(Arrays.asList("nosql", "spring-data-solr"), recalled.get().getCategory()); + Assert.assertEquals(2, recalled.getCategory().size()); + Assert.assertEquals(Arrays.asList("nosql", "spring-data-solr"), recalled.getCategory()); - assertEquals(toInsert.getName(), recalled.get().getName()); - assertEquals(toInsert.getPopularity(), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getName(), recalled.getName()); + Assert.assertEquals(toInsert.getPopularity(), recalled.getPopularity()); } @Test public void testPartialUpdateIncSingleValue() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.add(new SimpleUpdateField("popularity", 1, UpdateAction.INC)); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertTrue(recalled.isPresent()); - assertEquals(toInsert.getId(), recalled.get().getId()); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - assertEquals(1, recalled.get().getCategory().size()); + Assert.assertEquals(1, recalled.getCategory().size()); - assertEquals(toInsert.getName(), recalled.get().getName()); - assertEquals(Integer.valueOf(11), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getName(), recalled.getName()); + Assert.assertEquals(Integer.valueOf(11), recalled.getPopularity()); } @Test public void testPartialUpdateSetMultipleValuesToMultivaluedField() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setValueOfField("cat", Arrays.asList("spring", "data", "solr")); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertTrue(recalled.isPresent()); - assertEquals(toInsert.getId(), recalled.get().getId()); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - assertEquals(3, recalled.get().getCategory().size()); - assertEquals(Arrays.asList("spring", "data", "solr"), recalled.get().getCategory()); + Assert.assertEquals(3, recalled.getCategory().size()); + Assert.assertEquals(Arrays.asList("spring", "data", "solr"), recalled.getCategory()); - assertEquals(toInsert.getName(), recalled.get().getName()); - assertEquals(toInsert.getPopularity(), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getName(), recalled.getName()); + Assert.assertEquals(toInsert.getPopularity(), recalled.getPopularity()); } @Test @@ -245,85 +264,82 @@ public void testPartialUpdateSetEmptyCollectionToMultivaluedFieldRemovesValuesFr ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setCategory(Arrays.asList("spring", "data", "solr")); toInsert.setPopularity(10); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setValueOfField("cat", Collections.emptyList()); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); - - assertTrue(recalled.isPresent()); - assertEquals(toInsert.getId(), recalled.get().getId()); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - assertEquals(0, recalled.get().getCategory().size()); + Assert.assertEquals(0, recalled.getCategory().size()); - assertEquals(toInsert.getName(), recalled.get().getName()); - assertEquals(toInsert.getPopularity(), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getName(), recalled.getName()); + Assert.assertEquals(toInsert.getPopularity(), recalled.getPopularity()); } @Test public void testPartialUpdateAddMultipleValuesToMultivaluedField() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.addValueToField("cat", Arrays.asList("spring", "data", "solr")); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - assertEquals(1, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(1, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean recalled = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(toInsert.getId(), recalled.get().getId()); + Assert.assertEquals(toInsert.getId(), recalled.getId()); - assertEquals(4, recalled.get().getCategory().size()); - assertEquals(Arrays.asList(toInsert.getCategory().get(0), "spring", "data", "solr"), recalled.get().getCategory()); + Assert.assertEquals(4, recalled.getCategory().size()); + Assert.assertEquals(Arrays.asList(toInsert.getCategory().get(0), "spring", "data", "solr"), recalled.getCategory()); - assertEquals(toInsert.getName(), recalled.get().getName()); - assertEquals(toInsert.getPopularity(), recalled.get().getPopularity()); + Assert.assertEquals(toInsert.getName(), recalled.getName()); + Assert.assertEquals(toInsert.getPopularity(), recalled.getPopularity()); } @Test public void testPartialUpdateWithMultipleDocuments() { - List values = new ArrayList<>(10); + List values = new ArrayList(10); for (int i = 0; i < 10; i++) { ExampleSolrBean toBeInserted = createExampleBeanWithId(Integer.toString(i)); toBeInserted.setPopularity(10); values.add(toBeInserted); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); - List updates = new ArrayList<>(5); + List updates = new ArrayList(5); for (int i = 0; i < 5; i++) { PartialUpdate update = new PartialUpdate("id", Integer.toString(i)); update.add("popularity", 5); updates.add(update); } - solrTemplate.saveBeans(COLLECTION_NAME, updates); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(updates); + solrTemplate.commit(); - assertEquals(10, solrTemplate.count(COLLECTION_NAME, ALL_DOCUMENTS_QUERY)); + Assert.assertEquals(10, solrTemplate.count(ALL_DOCUMENTS_QUERY)); - Page recalled = solrTemplate.queryForPage(COLLECTION_NAME, - new SimpleQuery(new SimpleStringCriteria("popularity:5")), ExampleSolrBean.class); + Page recalled = solrTemplate + .queryForPage(new SimpleQuery(new SimpleStringCriteria("popularity:5")), ExampleSolrBean.class); - assertEquals(5, recalled.getNumberOfElements()); + Assert.assertEquals(5, recalled.getNumberOfElements()); for (ExampleSolrBean bean : recalled) { - assertEquals("Category must not change on partial update", "category_" + bean.getId(), bean.getCategory().get(0)); + Assert.assertEquals("Category must not change on partial update", "category_" + bean.getId(), + bean.getCategory().get(0)); } } @@ -331,87 +347,84 @@ public void testPartialUpdateWithMultipleDocuments() { public void testPartialUpdateSetWithNullAtTheEnd() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - toInsert.setCategory(Collections.singletonList("cat-1")); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + toInsert.setCategory(Arrays.asList("cat-1")); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); - Optional loaded = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean loaded = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(1, loaded.get().getCategory().size()); + Assert.assertEquals(1, loaded.getCategory().size()); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setValueOfField("popularity", 500); update.setValueOfField("cat", Arrays.asList("cat-1", "cat-2", "cat-3")); update.setValueOfField("name", null); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - loaded = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(Integer.valueOf(500), loaded.get().getPopularity()); - assertEquals(3, loaded.get().getCategory().size()); - assertNull(loaded.get().getName()); + loaded = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); + Assert.assertEquals(Integer.valueOf(500), loaded.getPopularity()); + Assert.assertEquals(3, loaded.getCategory().size()); + Assert.assertNull(loaded.getName()); } @Test public void testPartialUpdateSetWithNullInTheMiddle() { ExampleSolrBean toInsert = createDefaultExampleBean(); toInsert.setPopularity(10); - toInsert.setCategory(Collections.singletonList("cat-1")); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + toInsert.setCategory(Arrays.asList("cat-1")); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); - Optional loaded = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); + ExampleSolrBean loaded = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(1, loaded.get().getCategory().size()); + Assert.assertEquals(1, loaded.getCategory().size()); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setValueOfField("popularity", 500); update.setValueOfField("name", null); update.setValueOfField("cat", Arrays.asList("cat-1", "cat-2", "cat-3")); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - loaded = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); - assertEquals(Integer.valueOf(500), loaded.get().getPopularity()); - assertNull(loaded.get().getName()); - assertEquals(3, loaded.get().getCategory().size()); + loaded = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); + Assert.assertEquals(Integer.valueOf(500), loaded.getPopularity()); + Assert.assertNull(loaded.getName()); + Assert.assertEquals(3, loaded.getCategory().size()); } @Test public void testPartialUpdateWithVersion() { ExampleSolrBean toInsert = createDefaultExampleBean(); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setVersion(1L); update.setValueOfField("popularity", 500); - solrTemplate.saveBean(COLLECTION_NAME, update); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(update); + solrTemplate.commit(); - Optional loaded = solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, - ExampleSolrBean.class); - assertEquals(Integer.valueOf(500), loaded.get().getPopularity()); + ExampleSolrBean loaded = solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, ExampleSolrBean.class); + Assert.assertEquals(Integer.valueOf(500), loaded.getPopularity()); } @Test(expected = UncategorizedSolrException.class) public void testPartialUpdateWithInvalidVersion() { ExampleSolrBean toInsert = createDefaultExampleBean(); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(toInsert); + solrTemplate.commit(); PartialUpdate update = new PartialUpdate("id", DEFAULT_BEAN_ID); update.setVersion(2L); update.setValueOfField("popularity", 500); - solrTemplate.saveBean(COLLECTION_NAME, update); + solrTemplate.saveBean(update); } @Test @@ -422,61 +435,60 @@ public void testPing() throws SolrServerException, IOException { @Test public void testRollback() { ExampleSolrBean toInsert = createDefaultExampleBean(); - solrTemplate.saveBean(COLLECTION_NAME, toInsert); - Optional recalled = solrTemplate.queryForObject(COLLECTION_NAME, - new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); - assertFalse(recalled.isPresent()); - - solrTemplate.rollback(COLLECTION_NAME); - recalled = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery(new Criteria("id").is("1")), + solrTemplate.saveBean(toInsert); + ExampleSolrBean recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); - assertFalse(recalled.isPresent()); + Assert.assertNull(recalled); + + solrTemplate.rollback(); + recalled = solrTemplate.queryForObject(new SimpleQuery(new Criteria("id").is("1")), ExampleSolrBean.class); + Assert.assertNull(recalled); } @Test public void testFacetQueryWithFacetFields() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createExampleBeanWithId(Integer.toString(i))); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); FacetQuery q = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) .setFacetOptions(new FacetOptions().addFacetOnField("name").addFacetOnField("id").setFacetLimit(5)); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); for (Page facetResultPage : page.getFacetResultPages()) { - assertEquals(5, facetResultPage.getNumberOfElements()); + Assert.assertEquals(5, facetResultPage.getNumberOfElements()); } Page facetPage = page.getFacetResultPage(new SimpleField("name")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("name", entry.getField().getName()); - assertEquals(1l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("name", entry.getField().getName()); + Assert.assertEquals(1l, entry.getValueCount()); } facetPage = page.getFacetResultPage(new SimpleField("id")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("id", entry.getField().getName()); - assertEquals(1l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("id", entry.getField().getName()); + Assert.assertEquals(1l, entry.getValueCount()); } } @Test // DATSOLR-86 public void testFacetQueryWithDateFacetRangeField() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { final ExampleSolrBean exampleSolrBean = createExampleBeanWithId(Integer.toString(i)); exampleSolrBean.setLastModified(new GregorianCalendar(2013, Calendar.DECEMBER, (i + 10) / 2).getTime()); values.add(exampleSolrBean); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); final FieldWithDateRangeParameters lastModifiedField = new FieldWithDateRangeParameters("last_modified", new GregorianCalendar(2013, NOVEMBER, 30).getTime(), new GregorianCalendar(2014, JANUARY, 1).getTime(), "+1DAY") // @@ -493,32 +505,32 @@ public void testFacetQueryWithDateFacetRangeField() { .setPageable(new PageRequest(1, 10))); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); - assertEquals(FacetRangeInclude.LOWER, lastModifiedField.getQueryParameterValue(FACET_RANGE_INCLUDE)); + Assert.assertEquals(FacetRangeInclude.LOWER, lastModifiedField.getQueryParameterValue(FACET_RANGE_INCLUDE)); for (Page facetResultPage : page.getFacetResultPages()) { - assertEquals(5, facetResultPage.getNumberOfElements()); + Assert.assertEquals(5, facetResultPage.getNumberOfElements()); } Page facetPage = page.getFacetResultPage(new SimpleField("last_modified")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("last_modified", entry.getField().getName()); - assertEquals(2l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("last_modified", entry.getField().getName()); + Assert.assertEquals(2l, entry.getValueCount()); } } @Test // DATSOLR-86 public void testFacetQueryWithNumericFacetRangeField() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { final ExampleSolrBean exampleSolrBean = createExampleBeanWithId(Integer.toString(i)); exampleSolrBean.setPopularity((i + 1) * 100); values.add(exampleSolrBean); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); final FieldWithNumericRangeParameters popularityField = new FieldWithNumericRangeParameters("popularity", 100, 800, 200) // @@ -535,47 +547,47 @@ public void testFacetQueryWithNumericFacetRangeField() { .setFacetSort(FacetSort.COUNT)); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); for (Page facetResultPage : page.getFacetResultPages()) { - assertEquals(4, facetResultPage.getNumberOfElements()); + Assert.assertEquals(4, facetResultPage.getNumberOfElements()); } Page facetPage = page.getFacetResultPage(new SimpleField("popularity")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("popularity", entry.getField().getName()); - assertEquals(2l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("popularity", entry.getField().getName()); + Assert.assertEquals(2l, entry.getValueCount()); } } @Test public void testFacetQueryWithPivotFields() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createExampleBeanWithId(Integer.toString(i))); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); FacetQuery q = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) .setFacetOptions(new FacetOptions().addFacetOnPivot("cat", "name")); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); List pivotEntries = page.getPivot("cat,name"); - assertNotNull(pivotEntries); - assertEquals(10, pivotEntries.size()); + Assert.assertNotNull(pivotEntries); + Assert.assertEquals(10, pivotEntries.size()); for (FacetPivotFieldEntry entry1 : pivotEntries) { - assertNotNull(entry1.getValue()); - assertEquals("cat", entry1.getField().getName()); - assertEquals(1l, entry1.getValueCount()); + Assert.assertNotNull(entry1.getValue()); + Assert.assertEquals("cat", entry1.getField().getName()); + Assert.assertEquals(1l, entry1.getValueCount()); for (FacetPivotFieldEntry entry2 : entry1.getPivot()) { - assertNotNull(entry2.getValue()); - assertEquals("name", entry2.getField().getName()); - assertEquals(1l, entry2.getValueCount()); + Assert.assertNotNull(entry2.getValue()); + Assert.assertEquals("name", entry2.getField().getName()); + Assert.assertEquals(1l, entry2.getValueCount()); } } @@ -583,31 +595,31 @@ public void testFacetQueryWithPivotFields() { @Test public void testFacetQueryWithFacetQueries() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { ExampleSolrBean bean = createExampleBeanWithId(Integer.toString(i)); bean.setInStock(i % 2 == 0); values.add(bean); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); FacetQuery q = new SimpleFacetQuery(new SimpleStringCriteria("*:*")); q.setFacetOptions(new FacetOptions(new SimpleQuery(new SimpleStringCriteria("inStock:true")), new SimpleQuery(new SimpleStringCriteria("inStock:false")))); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); Page facetQueryResultPage = page.getFacetQueryResult(); - assertEquals(2, facetQueryResultPage.getContent().size()); - assertEquals("inStock:true", facetQueryResultPage.getContent().get(0).getValue()); - assertEquals(5, facetQueryResultPage.getContent().get(0).getValueCount()); + Assert.assertEquals(2, facetQueryResultPage.getContent().size()); + Assert.assertEquals("inStock:true", facetQueryResultPage.getContent().get(0).getValue()); + Assert.assertEquals(5, facetQueryResultPage.getContent().get(0).getValueCount()); - assertEquals("inStock:false", facetQueryResultPage.getContent().get(1).getValue()); - assertEquals(5, facetQueryResultPage.getContent().get(1).getValueCount()); + Assert.assertEquals("inStock:false", facetQueryResultPage.getContent().get(1).getValue()); + Assert.assertEquals(5, facetQueryResultPage.getContent().get(1).getValueCount()); - assertEquals(1, page.getAllFacets().size()); + Assert.assertEquals(1, page.getAllFacets().size()); } @Test @@ -617,19 +629,19 @@ public void testFacetQueryWithFacetPrefix() { ExampleSolrBean island = new ExampleSolrBean("3", "java", "island"); ExampleSolrBean language = new ExampleSolrBean("4", "java", "language"); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(season, framework, island, language)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(season, framework, island, language)); + solrTemplate.commit(); FacetQuery q = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) .setFacetOptions(new FacetOptions().addFacetOnField("name").setFacetLimit(5).setFacetPrefix("spr")); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); Page facetPage = page.getFacetResultPage(new SimpleField("name")); for (FacetFieldEntry entry : facetPage) { - assertEquals("spring", entry.getValue()); - assertEquals("name", entry.getField().getName()); - assertEquals(2l, entry.getValueCount()); + Assert.assertEquals("spring", entry.getValue()); + Assert.assertEquals("name", entry.getField().getName()); + Assert.assertEquals(2l, entry.getValueCount()); } } @@ -640,38 +652,38 @@ public void testFacetQueryWithFieldFacetPrefix() { ExampleSolrBean island = new ExampleSolrBean("3", "java", "island"); ExampleSolrBean language = new ExampleSolrBean("4", "java", "language"); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(season, framework, island, language)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(season, framework, island, language)); + solrTemplate.commit(); FacetQuery q = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) .setFacetOptions(new FacetOptions().addFacetOnField(new FieldWithFacetParameters("name").setPrefix("spr")) .addFacetOnField("cat").setFacetPrefix("lan").setFacetLimit(5)); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); Page facetPage = page.getFacetResultPage(new SimpleField("name")); for (FacetFieldEntry entry : facetPage) { - assertEquals("spring", entry.getValue()); - assertEquals("name", entry.getField().getName()); - assertEquals(2l, entry.getValueCount()); + Assert.assertEquals("spring", entry.getValue()); + Assert.assertEquals("name", entry.getField().getName()); + Assert.assertEquals(2l, entry.getValueCount()); } facetPage = page.getFacetResultPage(new SimpleField("cat")); for (FacetFieldEntry entry : facetPage) { - assertEquals("language", entry.getValue()); - assertEquals("cat", entry.getField().getName()); - assertEquals(1l, entry.getValueCount()); + Assert.assertEquals("language", entry.getValue()); + Assert.assertEquals("cat", entry.getField().getName()); + Assert.assertEquals(1l, entry.getValueCount()); } } @Test // DATASOLR-244 public void testFacetAndHighlightQueryWithFacetFields() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createExampleBeanWithId(Integer.toString(i))); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); FacetAndHighlightQuery q = new SimpleFacetAndHighlightQuery( new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD)) @@ -680,112 +692,112 @@ public void testFacetAndHighlightQueryWithFacetFields() { q.setHighlightOptions(new HighlightOptions().addField("name")); org.springframework.data.solr.core.query.result.FacetQueryResult page = solrTemplate - .queryForFacetPage(COLLECTION_NAME, q, ExampleSolrBean.class); + .queryForFacetPage(q, ExampleSolrBean.class); for (Page facetResultPage : page.getFacetResultPages()) { - assertEquals(5, facetResultPage.getNumberOfElements()); + Assert.assertEquals(5, facetResultPage.getNumberOfElements()); } Page facetPage = page.getFacetResultPage(new SimpleField("name")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("name", entry.getField().getName()); - assertEquals(1l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("name", entry.getField().getName()); + Assert.assertEquals(1l, entry.getValueCount()); } facetPage = page.getFacetResultPage(new SimpleField("id")); for (FacetFieldEntry entry : facetPage) { - assertNotNull(entry.getValue()); - assertEquals("id", entry.getField().getName()); - assertEquals(1l, entry.getValueCount()); + Assert.assertNotNull(entry.getValue()); + Assert.assertEquals("id", entry.getField().getName()); + Assert.assertEquals(1l, entry.getValueCount()); } } @Test public void testQueryWithSort() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createExampleBeanWithId(Integer.toString(i))); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); Query query = new SimpleQuery(new SimpleStringCriteria("*:*")).addSort(new Sort(Sort.Direction.DESC, "name")); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); ExampleSolrBean prev = page.getContent().get(0); for (int i = 1; i < page.getContent().size(); i++) { ExampleSolrBean cur = page.getContent().get(i); - assertTrue(Long.valueOf(cur.getId()) < Long.valueOf(prev.getId())); + Assert.assertTrue(Long.valueOf(cur.getId()) < Long.valueOf(prev.getId())); prev = cur; } } @Test public void testQueryWithMultiSort() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { ExampleSolrBean bean = createExampleBeanWithId(Integer.toString(i)); bean.setInStock(i % 2 == 0); values.add(bean); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); Query query = new SimpleQuery(new SimpleStringCriteria("*:*")).addSort(new Sort(Sort.Direction.DESC, "inStock")) .addSort(new Sort(Sort.Direction.ASC, "name")); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); ExampleSolrBean prev = page.getContent().get(0); for (int i = 1; i < 5; i++) { ExampleSolrBean cur = page.getContent().get(i); - assertTrue(cur.isInStock()); - assertTrue(Long.valueOf(cur.getId()) > Long.valueOf(prev.getId())); + Assert.assertTrue(cur.isInStock()); + Assert.assertTrue(Long.valueOf(cur.getId()) > Long.valueOf(prev.getId())); prev = cur; } prev = page.getContent().get(5); for (int i = 6; i < page.getContent().size(); i++) { ExampleSolrBean cur = page.getContent().get(i); - assertFalse(cur.isInStock()); - assertTrue(Long.valueOf(cur.getId()) > Long.valueOf(prev.getId())); + Assert.assertFalse(cur.isInStock()); + Assert.assertTrue(Long.valueOf(cur.getId()) > Long.valueOf(prev.getId())); prev = cur; } } @Test public void testQueryWithDefaultOperator() { - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { ExampleSolrBean bean = createExampleBeanWithId(Integer.toString(i)); bean.setInStock(i % 2 == 0); values.add(bean); } - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("inStock:(true false)")); query.setDefaultOperator(Operator.AND); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(0, page.getContent().size()); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(0, page.getContent().size()); query.setDefaultOperator(Operator.OR); - page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(10, page.getContent().size()); + page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(10, page.getContent().size()); } @Test public void testQueryWithDefType() { List values = createBeansWithIdAndPrefix(5, "id-"); - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); SimpleQuery query = new SimpleQuery(new Criteria("id").in("id-1", "id-2", "id-3")); query.setDefType("lucene"); query.setDefaultOperator(Operator.OR); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(3, page.getContent().size()); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(3, page.getContent().size()); } @Test @@ -794,18 +806,18 @@ public void testQueryWithRequestHandler() { values.get(0).setInStock(false); values.get(1).setInStock(true); - solrTemplate.saveBeans(COLLECTION_NAME, values); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(values); + solrTemplate.commit(); SimpleQuery query = new SimpleQuery(new Criteria("id").in("rh-1", "rh-2")); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(2, page.getContent().size()); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(2, page.getContent().size()); query = new SimpleQuery(new Criteria("id").in("rh-1", "rh-2")); query.setRequestHandler("/instock"); - page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(1, page.getContent().size()); - assertEquals("rh-2", page.getContent().get(0).getId()); + page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(1, page.getContent().size()); + Assert.assertEquals("rh-2", page.getContent().get(0).getId()); } @Test @@ -816,15 +828,15 @@ public void testQueryWithJoinOperation() { ExampleSolrBean ipod = new ExampleSolrBean("F8V7067-APL-KIT", "Belkin Mobile Power Cord for iPod", null); ipod.setManufacturerId(belkin.getId()); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(belkin, apple, ipod)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(belkin, apple, ipod)); + solrTemplate.commit(); SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("text:ipod")); query.setJoin(Join.from("manu_id_s").to("id")); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(1, page.getContent().size()); - assertEquals(belkin.getId(), page.getContent().get(0).getId()); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(1, page.getContent().size()); + Assert.assertEquals(belkin.getId(), page.getContent().get(0).getId()); } @Test // DATASOLR-176 @@ -835,15 +847,15 @@ public void testQueryWithJoinFromIndexOperation() { ExampleSolrBean ipod = new ExampleSolrBean("F8V7067-APL-KIT", "Belkin Mobile Power Cord for iPod", null); ipod.setManufacturerId(belkin.getId()); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(belkin, apple, ipod)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(belkin, apple, ipod)); + solrTemplate.commit(); SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("text:ipod")); query.setJoin(Join.from("manu_id_s").fromIndex("collection1").to("id")); - Page page = solrTemplate.queryForPage(COLLECTION_NAME, query, ExampleSolrBean.class); - assertEquals(1, page.getContent().size()); - assertEquals(belkin.getId(), page.getContent().get(0).getId()); + Page page = solrTemplate.queryForPage(query, ExampleSolrBean.class); + Assert.assertEquals(1, page.getContent().size()); + Assert.assertEquals(belkin.getId(), page.getContent().get(0).getId()); } @Test @@ -851,18 +863,17 @@ public void testQueryWithHighlights() { ExampleSolrBean belkin = new ExampleSolrBean("GB18030TEST", "Test with some GB18030TEST", null); ExampleSolrBean apple = new ExampleSolrBean("UTF8TEST", "Test with some UTF8TEST", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(belkin, apple)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(belkin, apple)); + solrTemplate.commit(); SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("name:with")); query.setHighlightOptions(new HighlightOptions()); - HighlightQueryResult page = solrTemplate.queryForHighlightPage(COLLECTION_NAME, query, - ExampleSolrBean.class); - assertEquals(2, page.getHighlighted().size()); + HighlightQueryResult page = solrTemplate.queryForHighlightPage(query, ExampleSolrBean.class); + Assert.assertEquals(2, page.getHighlighted().size()); - assertEquals("name", page.getHighlighted().get(0).getHighlights().get(0).getField().getName()); - assertEquals("Test with some GB18030TEST", + Assert.assertEquals("name", page.getHighlighted().get(0).getHighlights().get(0).getField().getName()); + Assert.assertEquals("Test with some GB18030TEST", page.getHighlighted().get(0).getHighlights().get(0).getSnipplets().get(0)); } @@ -874,65 +885,64 @@ public void testTermsQuery() { ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two three", null); ExampleSolrBean bean3 = new ExampleSolrBean("id-3", "three", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2, bean3)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2, bean3)); + solrTemplate.commit(); - TermsPage page = solrTemplate.queryForTermsPage(COLLECTION_NAME, query); + TermsPage page = solrTemplate.queryForTermsPage(query); ArrayList values = Lists.newArrayList(page.getTermsForField("name")); - assertEquals("three", values.get(0).getValue()); - assertEquals(3, values.get(0).getValueCount()); + Assert.assertEquals("three", values.get(0).getValue()); + Assert.assertEquals(3, values.get(0).getValueCount()); - assertEquals("two", values.get(1).getValue()); - assertEquals(2, values.get(1).getValueCount()); + Assert.assertEquals("two", values.get(1).getValue()); + Assert.assertEquals(2, values.get(1).getValueCount()); - assertEquals("one", values.get(2).getValue()); - assertEquals(1, values.get(2).getValueCount()); + Assert.assertEquals("one", values.get(2).getValue()); + Assert.assertEquals(1, values.get(2).getValueCount()); } @Test public void testFuctionQueryInFilterReturnsProperResult() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "one", null); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); + solrTemplate.commit(); Query q = new SimpleQuery("*:*") .addFilterQuery(new SimpleFilterQuery(new Criteria(QueryFunction.query("{!query v = 'one'}")))); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, q, ExampleSolrBean.class); - assertThat(result.getContent().get(0).getId(), equalTo(bean1.getId())); + Page result = solrTemplate.queryForPage(q, ExampleSolrBean.class); + Assert.assertThat(result.getContent().get(0).getId(), equalTo(bean1.getId())); } @Test public void testFuctionQueryReturnsProperResult() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "one", null); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); + solrTemplate.commit(); Query q = new SimpleQuery(new Criteria(QueryFunction.query("{!query v='two'}"))); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, q, ExampleSolrBean.class); - assertThat(result.getContent().get(0).getId(), is(bean2.getId())); + Page result = solrTemplate.queryForPage(q, ExampleSolrBean.class); + Assert.assertThat(result.getContent().get(0).getId(), is(bean2.getId())); } @Test - @Ignore("No longer supported in Solr 6 - A ValueSource isn't directly available from this field. Instead try a query using the distance as the score.") public void testFunctionQueryInFieldProjection() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "one", null); bean1.setStore("45.17614,-93.87341"); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "one two", null); bean2.setStore("40.7143,-74.006"); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); + solrTemplate.commit(); Query q = new SimpleQuery("*:*"); q.addProjectionOnField(new DistanceField("distance", "store", new Point(45.15, -93.85))); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, q, ExampleSolrBean.class); + Page result = solrTemplate.queryForPage(q, ExampleSolrBean.class); for (ExampleSolrBean bean : result) { - assertThat(bean.getDistance(), notNullValue()); + Assert.assertThat(bean.getDistance(), notNullValue()); } } @@ -940,11 +950,11 @@ public void testFunctionQueryInFieldProjection() { @Test // DATASOLR-162 public void testDelegatingCursorLoadsAllElements() throws IOException { - solrTemplate.saveBeans(COLLECTION_NAME, createBeansWithId(100)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(createBeansWithId(100)); + solrTemplate.commit(); - Cursor cursor = solrTemplate.queryForCursor(COLLECTION_NAME, - new SimpleQuery("*:*").addSort(new Sort(Direction.DESC, "id")), ExampleSolrBean.class); + Cursor cursor = solrTemplate + .queryForCursor(new SimpleQuery("*:*").addSort(new Sort(Direction.DESC, "id")), ExampleSolrBean.class); int i = 0; while (cursor.hasNext()) { @@ -953,16 +963,16 @@ public void testDelegatingCursorLoadsAllElements() throws IOException { } cursor.close(); - assertThat(i, is(100)); + Assert.assertThat(i, is(100)); } @Test // DATASOLR-121 public void testRegularGroupQuery() { - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_1", "name1", "category1", 2, true)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_2", "name1", "category2")); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_3", "name2", "category2", 1, true)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_4", "name3", "category2")); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(new ExampleSolrBean("id_1", "name1", "category1", 2, true)); + solrTemplate.saveBean(new ExampleSolrBean("id_2", "name1", "category2")); + solrTemplate.saveBean(new ExampleSolrBean("id_3", "name2", "category2", 1, true)); + solrTemplate.saveBean(new ExampleSolrBean("id_4", "name3", "category2")); + solrTemplate.commit(); Function f = IfFunction.when("inStock").then("1").otherwise("2"); Query q1 = new SimpleQuery("cat:category2"); @@ -979,8 +989,7 @@ public void testRegularGroupQuery() { groupOptions.setLimit(2); // asserts result page - GroupPage groupResultPage = solrTemplate.queryForGroupPage(COLLECTION_NAME, groupQuery, - ExampleSolrBean.class); + GroupPage groupResultPage = solrTemplate.queryForGroupPage(groupQuery, ExampleSolrBean.class); GroupResult groupResultName = groupResultPage.getGroupResult("name"); GroupResult groupResultFunction = groupResultPage.getGroupResult(f); GroupResult groupResultQuery1 = groupResultPage.getGroupResult(q1); @@ -988,7 +997,7 @@ public void testRegularGroupQuery() { // asserts field group Page> nameGroupEntries = groupResultName.getGroupEntries(); - assertEquals(3, nameGroupEntries.getTotalElements()); + Assert.assertEquals(3, nameGroupEntries.getTotalElements()); List> nameGroupEntriesContent = nameGroupEntries.getContent(); assertGroupEntry(nameGroupEntriesContent.get(0), 2, "name1", 2, "id_1", "id_2"); assertGroupEntry(nameGroupEntriesContent.get(1), 1, "name2", 1, "id_3"); @@ -996,21 +1005,21 @@ public void testRegularGroupQuery() { // asserts function group Page> functionGroupEntries = groupResultFunction.getGroupEntries(); - assertEquals(2, functionGroupEntries.getNumberOfElements()); + Assert.assertEquals(2, functionGroupEntries.getNumberOfElements()); List> functionGroupEntriesContent = functionGroupEntries.getContent(); assertGroupEntry(functionGroupEntriesContent.get(0), 2, "1.0", 2, "id_1", "id_3"); assertGroupEntry(functionGroupEntriesContent.get(1), 2, "2.0", 2, "id_2", "id_4"); // asserts first query group Page> query1GroupEntries = groupResultQuery1.getGroupEntries(); - assertEquals(1, query1GroupEntries.getNumberOfElements()); + Assert.assertEquals(1, query1GroupEntries.getNumberOfElements()); GroupEntry query1GroupEntry = query1GroupEntries.getContent().get(0); assertGroupEntry(query1GroupEntry, 3, "cat:category2", 2, "id_2", "id_3"); assertTrue(query1GroupEntry.getResult().hasNext()); // asserts second query group Page> query2GroupEntries = groupResultQuery2.getGroupEntries(); - assertEquals(1, query2GroupEntries.getNumberOfElements()); + Assert.assertEquals(1, query2GroupEntries.getNumberOfElements()); GroupEntry query2GroupEntry = query2GroupEntries.getContent().get(0); assertGroupEntry(query2GroupEntry, 1, "cat:category1", 1, "id_1"); assertFalse(query2GroupEntry.getResult().hasNext()); @@ -1019,13 +1028,13 @@ public void testRegularGroupQuery() { @Test // DATASOLR-121 @Ignore("Seems to be broken on solr side") public void testGroupQueryWithFacets() { - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_1", "name1", "category1", 2, true)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_2", "name1", "category1", 2, true)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_3", "name1", "category1", 1, true)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_4", "name2", "category2", 1, false)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_5", "name2", "category2", 2, false)); - solrTemplate.saveBean(COLLECTION_NAME, new ExampleSolrBean("id_6", "name2", "category1", 1, true)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(new ExampleSolrBean("id_1", "name1", "category1", 2, true)); + solrTemplate.saveBean(new ExampleSolrBean("id_2", "name1", "category1", 2, true)); + solrTemplate.saveBean(new ExampleSolrBean("id_3", "name1", "category1", 1, true)); + solrTemplate.saveBean(new ExampleSolrBean("id_4", "name2", "category2", 1, false)); + solrTemplate.saveBean(new ExampleSolrBean("id_5", "name2", "category2", 2, false)); + solrTemplate.saveBean(new ExampleSolrBean("id_6", "name2", "category1", 1, true)); + solrTemplate.commit(); SimpleFacetQuery groupQuery = new SimpleFacetQuery(new SimpleStringCriteria("*:*")); GroupOptions groupOptions = new GroupOptions(); @@ -1034,29 +1043,29 @@ public void testGroupQueryWithFacets() { groupOptions.addGroupByField("name"); groupOptions.setGroupFacets(true); org.springframework.data.solr.core.query.result.FacetQueryResult groupResultPage = solrTemplate - .queryForFacetPage(COLLECTION_NAME, groupQuery, ExampleSolrBean.class); + .queryForFacetPage(groupQuery, ExampleSolrBean.class); Page facetResultPage = groupResultPage.getFacetResultPage("inStock"); List facetContent = facetResultPage.getContent(); - assertEquals("true", facetContent.get(0).getValue()); - assertEquals("false", facetContent.get(1).getValue()); - assertEquals(2, facetContent.get(0).getValueCount()); - assertEquals(1, facetContent.get(1).getValueCount()); + Assert.assertEquals("true", facetContent.get(0).getValue()); + Assert.assertEquals("false", facetContent.get(1).getValue()); + Assert.assertEquals(2, facetContent.get(0).getValueCount()); + Assert.assertEquals(1, facetContent.get(1).getValueCount()); } private void assertGroupEntryContentIds(GroupEntry groupEntry, String... ids) { for (int i = 0; i < ids.length; i++) { - assertEquals(ids[i], groupEntry.getResult().getContent().get(i).getId()); + Assert.assertEquals(ids[i], groupEntry.getResult().getContent().get(i).getId()); } } private void assertGroupEntry(GroupEntry entry, long totalElements, String groupValue, int numberOfDocuments, String... ids) { - assertEquals(totalElements, entry.getResult().getTotalElements()); - assertEquals(groupValue, entry.getGroupValue()); - assertEquals(numberOfDocuments, entry.getResult().getContent().size()); + Assert.assertEquals(totalElements, entry.getResult().getTotalElements()); + Assert.assertEquals(groupValue, entry.getGroupValue()); + Assert.assertEquals(numberOfDocuments, entry.getResult().getContent().size()); assertGroupEntryContentIds(entry, ids); } @@ -1065,11 +1074,11 @@ public void testGetById() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "one", null); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); - Optional beanReturned = solrTemplate.getById(COLLECTION_NAME, "id-1", ExampleSolrBean.class); + ExampleSolrBean beanReturned = solrTemplate.getById("id-1", ExampleSolrBean.class); - assertEquals(bean1.getId(), beanReturned.get().getId()); + Assert.assertEquals(bean1.getId(), beanReturned.getId()); } @Test // DATASOLR-83 @@ -1077,15 +1086,15 @@ public void testGetByIds() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "one", null); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two", null); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); List ids = Arrays. asList("id-1", "id-2"); - Collection beansReturned = solrTemplate.getByIds(COLLECTION_NAME, ids, ExampleSolrBean.class); - List listBeansReturned = new ArrayList<>(beansReturned); + Collection beansReturned = solrTemplate.getById(ids, ExampleSolrBean.class); + List listBeansReturned = new ArrayList(beansReturned); - assertEquals(2, beansReturned.size()); - assertEquals(bean1.getId(), listBeansReturned.get(0).getId()); - assertEquals(bean2.getId(), listBeansReturned.get(1).getId()); + Assert.assertEquals(2, beansReturned.size()); + Assert.assertEquals(bean1.getId(), listBeansReturned.get(0).getId()); + Assert.assertEquals(bean2.getId(), listBeansReturned.get(1).getId()); } @Test // DATASOLR-160 @@ -1114,26 +1123,25 @@ public void testDistinctStatsRequest() { bean3.setPrice(20); bean1.setPopularity(2); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2, bean3)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2, bean3)); + solrTemplate.commit(); StatsOptions statsOptions = new StatsOptions().addField("popularity").addField("price") .setSelectiveCalcDistinct(true); SimpleQuery statsQuery = new SimpleQuery(new SimpleStringCriteria("*:*")); statsQuery.setStatsOptions(statsOptions); - StatsPage statResultPage = solrTemplate.queryForStatsPage(COLLECTION_NAME, statsQuery, - ExampleSolrBean.class); + StatsPage statResultPage = solrTemplate.queryForStatsPage(statsQuery, ExampleSolrBean.class); FieldStatsResult priceStatResult = statResultPage.getFieldStatsResult("price"); FieldStatsResult popularityStatResult = statResultPage.getFieldStatsResult("popularity"); - assertEquals(Long.valueOf(2), priceStatResult.getDistinctCount()); + Assert.assertEquals(Long.valueOf(2), priceStatResult.getDistinctCount()); Collection distinctValues = priceStatResult.getDistinctValues(); - assertEquals(2, distinctValues.size()); - assertTrue(distinctValues.contains(10.0F)); - assertTrue(distinctValues.contains(20.0F)); - assertEquals(null, popularityStatResult.getDistinctCount()); + Assert.assertEquals(2, distinctValues.size()); + Assert.assertTrue(distinctValues.contains(10.0F)); + Assert.assertTrue(distinctValues.contains(20.0F)); + Assert.assertEquals(null, popularityStatResult.getDistinctCount()); } @Test // DATASOLR-86 @@ -1149,8 +1157,8 @@ public void testRangeFacetRequest() { bean3.setPrice(20); bean1.setPopularity(2); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2, bean3)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2, bean3)); + solrTemplate.commit(); FacetOptions facetOptions = new FacetOptions() .addFacetByRange(new FieldWithNumericRangeParameters("price", 5, 20, 5).setInclude(FacetRangeInclude.ALL)); @@ -1159,88 +1167,98 @@ public void testRangeFacetRequest() { SimpleFacetQuery statsQuery = new SimpleFacetQuery(new SimpleStringCriteria("*:*")); statsQuery.setFacetOptions(facetOptions); org.springframework.data.solr.core.query.result.FacetQueryResult statResultPage = solrTemplate - .queryForFacetPage(COLLECTION_NAME, statsQuery, ExampleSolrBean.class); + .queryForFacetPage(statsQuery, ExampleSolrBean.class); Page priceRangeResult = statResultPage.getRangeFacetResultPage("price"); List content = priceRangeResult.getContent(); - assertEquals(3, priceRangeResult.getTotalElements()); - assertEquals(2, content.get(2).getValueCount()); - assertEquals(1, content.get(1).getValueCount()); + Assert.assertEquals(3, priceRangeResult.getTotalElements()); + Assert.assertEquals(2, content.get(2).getValueCount()); + Assert.assertEquals(1, content.get(1).getValueCount()); - assertEquals("5.0", content.get(0).getValue()); - assertEquals("10.0", content.get(1).getValue()); - assertEquals("15.0", content.get(2).getValue()); + Assert.assertEquals("5.0", content.get(0).getValue()); + Assert.assertEquals("10.0", content.get(1).getValue()); + Assert.assertEquals("15.0", content.get(2).getValue()); } @Test // DATASOLR-248 public void shouldAllowReadingMultivaluedFieldWithOnlyOneEntryIntoSingleValuedProperty() { - solrTemplate.execute((SolrCallback) solrClient -> { + solrTemplate.execute(new SolrCallback() { + + @Override + public Object doInSolr(SolrClient solrClient) throws SolrServerException, IOException { - SolrInputDocument sid = new SolrInputDocument(); - sid.addField("id", "id-1"); - sid.addField("title", "title"); - solrClient.add(sid).getStatus(); - return solrClient.commit(COLLECTION_NAME); + SolrInputDocument sid = new SolrInputDocument(); + sid.addField("id", "id-1"); + sid.addField("title", "title"); + solrClient.add(sid).getStatus(); + return solrClient.commit(); + } }); - Optional document = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery("id:id-1"), - SomeDoc.class); - assertThat(document.get().title, is(equalTo("title"))); + SomeDoc document = solrTemplate.queryForObject(new SimpleQuery("id:id-1"), SomeDoc.class); + assertThat(document.title, is(equalTo("title"))); } @Test // DATASOLR-248 public void shouldThrowExceptionReadingMultivaluedFieldWithManyEntriesIntoSingleValuedProperty() { - solrTemplate.execute((SolrCallback) solrClient -> { + solrTemplate.execute(new SolrCallback() { + + @Override + public Object doInSolr(SolrClient solrClient) throws SolrServerException, IOException { - SolrInputDocument sid = new SolrInputDocument(); - sid.addField("id", "id-1"); - sid.addField("title", new String[] { "title-1", "title-2" }); - solrClient.add(sid).getStatus(); - return solrClient.commit(COLLECTION_NAME); + SolrInputDocument sid = new SolrInputDocument(); + sid.addField("id", "id-1"); + sid.addField("title", new String[] { "title-1", "title-2" }); + solrClient.add(sid).getStatus(); + return solrClient.commit(); + } }); exception.expect(MappingException.class); exception.expectMessage("title-1"); exception.expectMessage("title-2"); - solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery("id:id-1"), SomeDoc.class); + solrTemplate.queryForObject(new SimpleQuery("id:id-1"), SomeDoc.class); } @Test // DATASOLR-248 public void shouldAllowReadingMultivaluedFieldWithNoEntriesIntoSingleValuedProperty() { - solrTemplate.execute((SolrCallback) solrClient -> { + solrTemplate.execute(new SolrCallback() { + + @Override + public Object doInSolr(SolrClient solrClient) throws SolrServerException, IOException { - SolrInputDocument sid = new SolrInputDocument(); - sid.addField("id", "id-1"); - solrClient.add(sid).getStatus(); - return solrClient.commit(COLLECTION_NAME); + SolrInputDocument sid = new SolrInputDocument(); + sid.addField("id", "id-1"); + solrClient.add(sid).getStatus(); + return solrClient.commit(); + } }); - Optional document = solrTemplate.queryForObject(COLLECTION_NAME, new SimpleQuery("id:id-1"), - SomeDoc.class); - assertThat(document.get().title, is(nullValue())); + SomeDoc document = solrTemplate.queryForObject(new SimpleQuery("id:id-1"), SomeDoc.class); + assertThat(document.title, is(nullValue())); } @Test // DATASOLR-137 public void testFindByNameWithSpellcheckSeggestion() { ExampleSolrBean bean1 = new ExampleSolrBean("id-1", "green", null); - solrTemplate.saveBean(COLLECTION_NAME, bean1); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(bean1); + solrTemplate.commit(); SimpleQuery q = new SimpleQuery("name:gren"); q.setSpellcheckOptions(SpellcheckOptions.spellcheck()); q.setRequestHandler("/spell"); - SpellcheckedPage found = solrTemplate.query(COLLECTION_NAME, q, ExampleSolrBean.class); - assertThat(found.hasContent(), Is.is(false)); - assertThat(found.getSuggestions().size(), Is.is(Matchers.greaterThan(0))); - assertThat(found.getSuggestions(), Matchers.contains("green")); + SpellcheckedPage found = solrTemplate.query(q, ExampleSolrBean.class); + Assert.assertThat(found.hasContent(), Is.is(false)); + Assert.assertThat(found.getSuggestions().size(), Is.is(Matchers.greaterThan(0))); + Assert.assertThat(found.getSuggestions(), Matchers.contains("green")); } @Test // DATSOLR-364 @@ -1248,12 +1266,15 @@ public void shouldUseBaseUrlInCollectionCallbackWhenExecutingCommands() { final HttpSolrClient client = new HttpSolrClient("http://127.0.0.1/solr/"); - SolrTemplate solrTemplate = new SolrTemplate(new HttpSolrClientFactory(client)); + SolrTemplate solrTemplate = new SolrTemplate(new MulticoreSolrClientFactory(client), "collection-1"); - solrTemplate.execute(solrClient -> { + solrTemplate.execute("collection-1", new CollectionCallback() { + @Override + public Object doInSolr(SolrClient solrClient, String collection) throws SolrServerException, IOException { - assertThat(((HttpSolrClient) solrClient).getBaseURL(), is("http://127.0.0.1/solr")); - return null; + Assert.assertThat(((HttpSolrClient)solrClient).getBaseURL(), is("http://127.0.0.1/solr")); + return null; + } }); } @@ -1263,43 +1284,42 @@ private void executeAndCheckStatsRequest(StatsOptions statsOptions) { bean1.setPrice(10f); ExampleSolrBean bean2 = new ExampleSolrBean("id-2", "two", null); bean2.setPrice(20.5f); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(bean1, bean2)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(bean1, bean2)); + solrTemplate.commit(); SimpleQuery statsQuery = new SimpleQuery(new SimpleStringCriteria("*:*")); statsQuery.setStatsOptions(statsOptions); - StatsPage statResultPage = solrTemplate.queryForStatsPage(COLLECTION_NAME, statsQuery, - ExampleSolrBean.class); + StatsPage statResultPage = solrTemplate.queryForStatsPage(statsQuery, ExampleSolrBean.class); FieldStatsResult priceStats = statResultPage.getFieldStatsResult("price"); - assertEquals(Long.valueOf(2), priceStats.getCount()); - assertEquals(10D, priceStats.getMin()); - assertEquals(20.50, priceStats.getMax()); - assertEquals(Double.valueOf(10), priceStats.getMinAsDouble()); - assertEquals(Double.valueOf(20.50), priceStats.getMaxAsDouble()); - assertEquals("10.0", priceStats.getMinAsString()); - assertEquals("20.5", priceStats.getMaxAsString()); - assertNull(priceStats.getMinAsDate()); - assertNull(priceStats.getMaxAsDate()); - assertEquals(15.25, priceStats.getMean()); - assertEquals(30.50, priceStats.getSum()); - assertEquals(Long.valueOf(0), priceStats.getMissing()); - assertEquals(Double.valueOf(7.424621202458749), priceStats.getStddev()); - assertEquals(Double.valueOf(520.25), priceStats.getSumOfSquares()); + Assert.assertEquals(Long.valueOf(2), priceStats.getCount()); + Assert.assertEquals(10D, priceStats.getMin()); + Assert.assertEquals(20.50, priceStats.getMax()); + Assert.assertEquals(Double.valueOf(10), priceStats.getMinAsDouble()); + Assert.assertEquals(Double.valueOf(20.50), priceStats.getMaxAsDouble()); + Assert.assertEquals("10.0", priceStats.getMinAsString()); + Assert.assertEquals("20.5", priceStats.getMaxAsString()); + Assert.assertNull(priceStats.getMinAsDate()); + Assert.assertNull(priceStats.getMaxAsDate()); + Assert.assertEquals(Double.valueOf(15.25), priceStats.getMean()); + Assert.assertEquals(Double.valueOf(30.50), priceStats.getSum()); + Assert.assertEquals(Long.valueOf(0), priceStats.getMissing()); + Assert.assertEquals(Double.valueOf(7.424621202458749), priceStats.getStddev()); + Assert.assertEquals(Double.valueOf(520.25), priceStats.getSumOfSquares()); Map facetStatsResult = priceStats.getFacetStatsResult(new SimpleField("name")); - assertEquals(2, facetStatsResult.size()); + Assert.assertEquals(2, facetStatsResult.size()); { StatsResult nameFacetStatsResult = facetStatsResult.get("one"); - assertEquals(Long.valueOf(1), nameFacetStatsResult.getCount()); - assertEquals(10D, nameFacetStatsResult.getMin()); - assertEquals(10D, nameFacetStatsResult.getMax()); + Assert.assertEquals(Long.valueOf(1), nameFacetStatsResult.getCount()); + Assert.assertEquals(10D, nameFacetStatsResult.getMin()); + Assert.assertEquals(10D, nameFacetStatsResult.getMax()); } { StatsResult nameFacetStatsResult = facetStatsResult.get("two"); - assertEquals(Long.valueOf(1), nameFacetStatsResult.getCount()); - assertEquals(20.5D, nameFacetStatsResult.getMin()); - assertEquals(20.5D, nameFacetStatsResult.getMax()); + Assert.assertEquals(Long.valueOf(1), nameFacetStatsResult.getCount()); + Assert.assertEquals(20.5D, nameFacetStatsResult.getMin()); + Assert.assertEquals(20.5D, nameFacetStatsResult.getMax()); } } diff --git a/src/test/java/org/springframework/data/solr/core/QueryParserBaseTests.java b/src/test/java/org/springframework/data/solr/core/QueryParserBaseTests.java index d53b805..e28b7d4 100644 --- a/src/test/java/org/springframework/data/solr/core/QueryParserBaseTests.java +++ b/src/test/java/org/springframework/data/solr/core/QueryParserBaseTests.java @@ -152,7 +152,7 @@ public void testFunctionFragmemtAppendsMultipleArgumentsCorrectly() { @Test public void testFunctionFragmemtAppendsSingleArgumentCorrectly() { - Foo function = new Foo(Collections.singletonList("one")); + Foo function = new Foo(Arrays.asList("one")); Assert.assertThat(parser.createFunctionFragment(function, 0), Is.is("{!func}foo(one)")); } @@ -173,7 +173,7 @@ public void testFunctionFragmemtIgnoresEmptyArguments() { @Test public void testCreateFunctionFragmemtThrowsExceptionOnNullInArguments() { - List args = new ArrayList<>(1); + List args = new ArrayList(1); args.add(null); thrown.expect(IllegalArgumentException.class); @@ -183,27 +183,27 @@ public void testCreateFunctionFragmemtThrowsExceptionOnNullInArguments() { @Test public void testCreateFunctionFragementsWihtNetsedFunction() { - Foo function = new Foo(Collections.singletonList(new Bar(Collections.singletonList("nested")))); + Foo function = new Foo(Arrays.asList(new Bar(Arrays.asList("nested")))); Assert.assertThat(parser.createFunctionFragment(function, 0), Is.is("{!func}foo(bar(nested))")); } @Test public void testCreateFunctionFragmentConvertsPointProperty() { - Foo function = new Foo(Collections.singletonList(new Point(37.767624D, -122.48526D))); + Foo function = new Foo(Arrays.asList(new Point(37.767624D, -122.48526D))); Assert.assertThat(parser.createFunctionFragment(function, 0), Is.is("{!func}foo(37.767624,-122.48526)")); } @Test public void testCreateFunctionFragmentConvertsDistanceProperty() { - Foo function = new Foo(Collections.singletonList(new Distance(5, Metrics.KILOMETERS))); + Foo function = new Foo(Arrays.asList(new Distance(5, Metrics.KILOMETERS))); Assert.assertThat(parser.createFunctionFragment(function, 0), Is.is("{!func}foo(5.0)")); } @Test public void testCreateFunctionFragmentUsesToStringForUnknowObject() { - Foo function = new Foo(Collections.singletonList(new FooBar())); + Foo function = new Foo(Arrays.asList(new FooBar())); Assert.assertThat(parser.createFunctionFragment(function, 0), Is.is("{!func}foo(FooBar [])")); } diff --git a/src/test/java/org/springframework/data/solr/core/ResultHelperTests.java b/src/test/java/org/springframework/data/solr/core/ResultHelperTests.java index 83f91d9..cb9868e 100644 --- a/src/test/java/org/springframework/data/solr/core/ResultHelperTests.java +++ b/src/test/java/org/springframework/data/solr/core/ResultHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * 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. @@ -44,11 +44,23 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.annotation.Id; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.data.solr.core.query.*; +import org.springframework.data.solr.core.query.Criteria; +import org.springframework.data.solr.core.query.FacetOptions; +import org.springframework.data.solr.core.query.FacetQuery; +import org.springframework.data.solr.core.query.Field; +import org.springframework.data.solr.core.query.GroupOptions; +import org.springframework.data.solr.core.query.PivotField; +import org.springframework.data.solr.core.query.Query; +import org.springframework.data.solr.core.query.SimpleFacetQuery; +import org.springframework.data.solr.core.query.SimpleField; +import org.springframework.data.solr.core.query.SimplePivotField; +import org.springframework.data.solr.core.query.SimpleQuery; +import org.springframework.data.solr.core.query.SimpleStringCriteria; +import org.springframework.data.solr.core.query.SolrDataQuery; import org.springframework.data.solr.core.query.result.FacetFieldEntry; import org.springframework.data.solr.core.query.result.FacetPivotFieldEntry; import org.springframework.data.solr.core.query.result.FacetQueryEntry; @@ -65,15 +77,15 @@ * @author Christoph Strobl * @author Francisco Spaeth */ -@RunWith(MockitoJUnitRunner.Silent.class) +@RunWith(MockitoJUnitRunner.class) public class ResultHelperTests { @Mock private QueryResponse response; @Test public void testConvertFacetQueryResponseForNullQueryResponse() { - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(createFacetQuery("field_1"), null); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + createFacetQuery("field_1"), null); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -85,8 +97,8 @@ public void testConvertFacetQueryResponseForNullQuery() { @Test public void testConvertFacetQueryResponseForQueryWithoutFacetOptions() { - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(new SimpleFacetQuery(new Criteria("field_1")), null); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + new SimpleFacetQuery(new Criteria("field_1")), null); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -94,8 +106,8 @@ public void testConvertFacetQueryResponseForQueryWithoutFacetOptions() { @Test public void testConvertFacetQueryResponseForQueryResultWithNullFacetFields() { Mockito.when(response.getFacetFields()).thenReturn(null); - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -103,22 +115,22 @@ public void testConvertFacetQueryResponseForQueryResultWithNullFacetFields() { @Test public void testConvertFacetQueryResponseForQueryResultWithEmptyFacetFields() { Mockito.when(response.getFacetFields()).thenReturn(Collections. emptyList()); - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @Test public void testConvertFacetQueryResponseForQueryResultWithSingleFacetFieldWithoutValues() { - List fieldList = new ArrayList<>(1); + List fieldList = new ArrayList(1); FacetField ffield = new FacetField("field_1"); fieldList.add(ffield); Mockito.when(response.getFacetFields()).thenReturn(fieldList); - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Entry> resultEntry = result.entrySet().iterator().next(); @@ -129,14 +141,14 @@ public void testConvertFacetQueryResponseForQueryResultWithSingleFacetFieldWitho @Test public void testConvertFacetQueryResponseForQueryResultWithSingeFacetField() { - List fieldList = new ArrayList<>(1); + List fieldList = new ArrayList(1); FacetField ffield = createFacetField("field_1", 1, 2); fieldList.add(ffield); Mockito.when(response.getFacetFields()).thenReturn(fieldList); - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Entry> resultEntry = result.entrySet().iterator().next(); @@ -165,15 +177,14 @@ public void testConvertFacetQueryResponseForQueryResultWithEmptyFacetQueries() { @Test public void testConvertFacetQueryResponseForQueryResultWithFacetQueries() { - Map resultMap = new LinkedHashMap<>(2); + Map resultMap = new LinkedHashMap(2); resultMap.put("field_1:[* TO 5]", 5); resultMap.put("field_1:[6 TO *]", 10); Mockito.when(response.getFacetQuery()).thenReturn(resultMap); List result = ResultHelper.convertFacetQueryResponseToFacetQueryResult( - createFacetQuery(new SimpleQuery(new SimpleStringCriteria("field_1:[* TO 5]")), - new SimpleQuery(new SimpleStringCriteria("field_1:[6 TO *]"))), - response); + createFacetQuery(new SimpleQuery(new SimpleStringCriteria("field_1:[* TO 5]")), new SimpleQuery( + new SimpleStringCriteria("field_1:[6 TO *]"))), response); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); @@ -192,28 +203,28 @@ public void testConvertFacetQueryResponseForQueryResultWithFacetQueries() { public void testParseAndAddHighlightQueryResponseToResultPageWithEmptyHighlighting() { Mockito.when(response.getHighlighting()).thenReturn(Collections.>> emptyMap()); Assert.assertTrue(ResultHelper.convertAndAddHighlightQueryResponseToResultPage(response, - new SolrResultPage<>(Collections.singletonList(new Object()))).isEmpty()); + new SolrResultPage(Arrays.asList(new Object()))).isEmpty()); } @Test public void testParseAndAddHighlightQueryResponseToResultPageWithNullHighlighting() { Mockito.when(response.getHighlighting()).thenReturn(null); Assert.assertTrue(ResultHelper.convertAndAddHighlightQueryResponseToResultPage(response, - new SolrResultPage<>(Collections.singletonList(new Object()))).isEmpty()); + new SolrResultPage(Arrays.asList(new Object()))).isEmpty()); } @Test public void testParseAndAddHighlightQueryResponseToResultPageWithNullResponse() { Assert.assertTrue(ResultHelper.convertAndAddHighlightQueryResponseToResultPage(null, - new SolrResultPage<>(Collections.singletonList(new Object()))).isEmpty()); + new SolrResultPage(Arrays.asList(new Object()))).isEmpty()); } @Test public void testParseAndAddHighlightQueryResponseToResultPage() { - Map>> highlightingData = new LinkedHashMap<>(); - Map> fieldHighlights = new LinkedHashMap<>(); + Map>> highlightingData = new LinkedHashMap>>(); + Map> fieldHighlights = new LinkedHashMap>(); fieldHighlights.put("field_1", Arrays.asList("highlight 1", "highlight 2")); - fieldHighlights.put("field_2", Collections.singletonList("highlight 3")); + fieldHighlights.put("field_2", Arrays.asList("highlight 3")); highlightingData.put("entity-id-1", fieldHighlights); Mockito.when(response.getHighlighting()).thenReturn(highlightingData); @@ -222,7 +233,7 @@ public void testParseAndAddHighlightQueryResponseToResultPage() { List> result = ResultHelper .convertAndAddHighlightQueryResponseToResultPage(response, - new SolrResultPage<>(Collections.singletonList(resultBean))); + new SolrResultPage(Arrays.asList(resultBean))); Assert.assertEquals(1, result.size()); Assert.assertEquals(resultBean, result.get(0).getEntity()); @@ -238,15 +249,15 @@ public void testParseAndAddHighlightQueryResponseToResultPage() { @Test public void testParseAndAddHighlightQueryResponseWithMultipleEntriesToResultPage() { - Map>> highlightingData = new LinkedHashMap<>(); + Map>> highlightingData = new LinkedHashMap>>(); - Map> fieldHighlightsEntity1 = new LinkedHashMap<>(); + Map> fieldHighlightsEntity1 = new LinkedHashMap>(); fieldHighlightsEntity1.put("field_1", Arrays.asList("highlight 1", "highlight 2")); - fieldHighlightsEntity1.put("field_2", Collections.singletonList("highlight 3")); + fieldHighlightsEntity1.put("field_2", Arrays.asList("highlight 3")); highlightingData.put("entity-id-1", fieldHighlightsEntity1); - Map> fieldHighlightsEntity2 = new LinkedHashMap<>(); - fieldHighlightsEntity2.put("field_3", Collections.singletonList("highlight 3")); + Map> fieldHighlightsEntity2 = new LinkedHashMap>(); + fieldHighlightsEntity2.put("field_3", Arrays.asList("highlight 3")); highlightingData.put("entity-id-2", fieldHighlightsEntity2); Mockito.when(response.getHighlighting()).thenReturn(highlightingData); @@ -256,7 +267,7 @@ public void testParseAndAddHighlightQueryResponseWithMultipleEntriesToResultPage List> result = ResultHelper .convertAndAddHighlightQueryResponseToResultPage(response, - new SolrResultPage<>(Arrays.asList(resultBean1, resultBean2))); + new SolrResultPage(Arrays.asList(resultBean1, resultBean2))); Assert.assertEquals(2, result.size()); Assert.assertEquals(resultBean1, result.get(0).getEntity()); @@ -267,10 +278,10 @@ public void testParseAndAddHighlightQueryResponseWithMultipleEntriesToResultPage @Test public void testParseAndAddHighlightQueryResponseForBeanWithAnnotatedId() { - Map>> highlightingData = new LinkedHashMap<>(); - Map> fieldHighlights = new LinkedHashMap<>(); + Map>> highlightingData = new LinkedHashMap>>(); + Map> fieldHighlights = new LinkedHashMap>(); fieldHighlights.put("field_1", Arrays.asList("highlight 1", "highlight 2")); - fieldHighlights.put("field_2", Collections.singletonList("highlight 3")); + fieldHighlights.put("field_2", Arrays.asList("highlight 3")); highlightingData.put("entity-id-1", fieldHighlights); Mockito.when(response.getHighlighting()).thenReturn(highlightingData); @@ -279,7 +290,7 @@ public void testParseAndAddHighlightQueryResponseForBeanWithAnnotatedId() { List> result = ResultHelper .convertAndAddHighlightQueryResponseToResultPage(response, - new SolrResultPage<>(Collections.singletonList(resultBean))); + new SolrResultPage(Arrays.asList(resultBean))); Assert.assertEquals(1, result.size()); Assert.assertEquals(resultBean, result.get(0).getEntity()); @@ -295,8 +306,8 @@ public void testParseAndAddHighlightQueryResponseForBeanWithAnnotatedId() { @Test public void testConvertFacetRangeQueryResponseToFacetPageMapForNullQueryResponse() { - Map> result = ResultHelper - .convertFacetQueryResponseToRangeFacetPageMap(this.createFacetQuery("field_1"), null); + Map> result = ResultHelper.convertFacetQueryResponseToRangeFacetPageMap( + this.createFacetQuery("field_1"), null); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -308,8 +319,8 @@ public void testConvertFacetRangeQueryResponseForNullQuery() { @Test public void testConvertFacetRangeQueryResponseForQueryWithoutFacetOptions() { - Map> result = ResultHelper - .convertFacetQueryResponseToRangeFacetPageMap(new SimpleFacetQuery(new SimpleStringCriteria("*:*")), null); + Map> result = ResultHelper.convertFacetQueryResponseToRangeFacetPageMap( + new SimpleFacetQuery(new SimpleStringCriteria("*:*")), null); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -317,8 +328,8 @@ public void testConvertFacetRangeQueryResponseForQueryWithoutFacetOptions() { @Test public void testConvertFacetRangeQueryResponseForQueryResultWithNullFacetFields() { Mockito.when(response.getFacetFields()).thenReturn(null); - Map> result = ResultHelper - .convertFacetQueryResponseToRangeFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToRangeFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @@ -326,18 +337,18 @@ public void testConvertFacetRangeQueryResponseForQueryResultWithNullFacetFields( @Test public void testConvertFacetRangeQueryResponseForQueryResultWithEmptyFacetFields() { Mockito.when(response.getFacetFields()).thenReturn(Collections. emptyList()); - Map> result = ResultHelper - .convertFacetQueryResponseToRangeFacetPageMap(createFacetQuery("field_1"), response); + Map> result = ResultHelper.convertFacetQueryResponseToRangeFacetPageMap( + createFacetQuery("field_1"), response); Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } @Test public void testConvertFacetQueryResponseToFacetPivotMap() { - NamedList> pivotData = new NamedList<>(); - List vals = new ArrayList<>(); + NamedList> pivotData = new NamedList>(); + List vals = new ArrayList(); { - List pivotValues = new ArrayList<>(); + List pivotValues = new ArrayList(); pivotValues .add(new org.apache.solr.client.solrj.response.PivotField("field_2", "value_1_1", 7, null, null, null, null)); pivotValues @@ -346,7 +357,7 @@ public void testConvertFacetQueryResponseToFacetPivotMap() { null)); } { - List pivotValues = new ArrayList<>(); + List pivotValues = new ArrayList(); pivotValues .add(new org.apache.solr.client.solrj.response.PivotField("field_2", "value_2_1", 2, null, null, null, null)); vals.add( @@ -356,8 +367,8 @@ public void testConvertFacetQueryResponseToFacetPivotMap() { Mockito.when(response.getFacetPivot()).thenReturn(pivotData); - Map> result = ResultHelper - .convertFacetQueryResponseToFacetPivotMap(createFacetPivotQuery("field_1", "field_2"), response); + Map> result = ResultHelper.convertFacetQueryResponseToFacetPivotMap( + createFacetPivotQuery("field_1", "field_2"), response); List resultPivot = result.get(new SimplePivotField("field_1", "field_2")); Assert.assertNotNull(result); @@ -377,12 +388,12 @@ public void testConvertFacetQueryResponseToFacetPivotMap() { Assert.assertNotNull(pivot.get(0).getField()); Assert.assertEquals("field_2", pivot.get(0).getField().getName()); Assert.assertEquals(7, pivot.get(0).getValueCount()); - Assert.assertEquals(pivot.get(0).getPivot(), Collections.emptyList()); + Assert.assertNull(pivot.get(0).getPivot()); Assert.assertEquals("value_1_2", pivot.get(1).getValue()); Assert.assertNotNull(pivot.get(1).getField()); Assert.assertEquals("field_2", pivot.get(1).getField().getName()); Assert.assertEquals(3, pivot.get(1).getValueCount()); - Assert.assertEquals(pivot.get(1).getPivot(), Collections.emptyList()); + Assert.assertNull(pivot.get(1).getPivot()); } { @@ -391,7 +402,7 @@ public void testConvertFacetQueryResponseToFacetPivotMap() { Assert.assertNotNull(pivot.get(0).getField()); Assert.assertEquals("field_2", pivot.get(0).getField().getName()); Assert.assertEquals(2, pivot.get(0).getValueCount()); - Assert.assertEquals(pivot.get(0).getPivot(), Collections.emptyList()); + Assert.assertNull(pivot.get(0).getPivot()); } Assert.assertNotNull(resultPivot.get(0).getPivot().get(0)); @@ -400,7 +411,7 @@ public void testConvertFacetQueryResponseToFacetPivotMap() { @Test public void testConvertTermsQueryResponseReturnsTermsMapCorrectlyWhenOneFieldReturned() { - TermsResponse termsResponse = new TermsResponse(new NamedList<>()); + TermsResponse termsResponse = new TermsResponse(new NamedList>()); termsResponse.getTermMap().put("field_1", Arrays.asList(new Term("term_1", 10), new Term("term_2", 5))); Mockito.when(response.getTermsResponse()).thenReturn(termsResponse); @@ -419,7 +430,7 @@ public void testConvertTermsQueryResponseReturnsTermsMapCorrectlyWhenOneFieldRet @Test public void testConvertTermsQueryResponseReturnsTermsMapCorrectlyWhenMultipleFieldsReturned() { - TermsResponse termsResponse = new TermsResponse(new NamedList<>()); + TermsResponse termsResponse = new TermsResponse(new NamedList>()); termsResponse.getTermMap().put("field_1", Arrays.asList(new Term("term_1", 10), new Term("term_2", 5))); termsResponse.getTermMap().put("field_2", Arrays.asList(new Term("term_2", 2), new Term("term_3", 1))); @@ -448,7 +459,7 @@ public void testConvertTermsQueryResponseReturnsEmtpyMapWhenTermsResponseIsNull( @Test public void testConvertTermsQueryResponseReturnsEmtpyMapWhenTermsMapIsEmpty() { - TermsResponse termsResponse = new TermsResponse(new NamedList<>()); + TermsResponse termsResponse = new TermsResponse(new NamedList>()); Mockito.when(response.getTermsResponse()).thenReturn(termsResponse); Assert.assertThat(ResultHelper.convertTermsQueryResponseToTermsMap(response), @@ -463,16 +474,16 @@ public void testConvertGroupQueryResponseToGroupResultList() { GroupCommand groupCommand1 = Mockito.mock(GroupCommand.class); Group group1_1 = Mockito.mock(Group.class); SolrDocumentList group1_1DocumentList = Mockito.mock(SolrDocumentList.class); - List documents1_1 = Collections.singletonList(new Object()); + List documents1_1 = Arrays.asList(new Object()); Mockito.when(response.getGroupResponse()).thenReturn(groupResponse); - Mockito.when(groupResponse.getValues()).thenReturn(Collections.singletonList(groupCommand1)); - Mockito.when(groupCommand1.getValues()).thenReturn(Collections.singletonList(group1_1)); + Mockito.when(groupResponse.getValues()).thenReturn(Arrays.asList(groupCommand1)); + Mockito.when(groupCommand1.getValues()).thenReturn(Arrays.asList(group1_1)); Mockito.when(group1_1.getResult()).thenReturn(group1_1DocumentList); Mockito.when(group1_1.getGroupValue()).thenReturn("group1_1_value"); Mockito.when(group1_1DocumentList.getNumFound()).thenReturn(3L); - Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)) - .thenReturn(documents1_1); + Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)).thenReturn( + documents1_1); Mockito.when(groupCommand1.getMatches()).thenReturn(1); Mockito.when(groupCommand1.getName()).thenReturn("group1_name"); Mockito.when(groupCommand1.getNGroups()).thenReturn(2); @@ -484,11 +495,11 @@ public void testConvertGroupQueryResponseToGroupResultList() { Mockito.when(query.getGroupOptions()).thenReturn(groupOptions); Object group1Key = new Object(); - Map objectNames = new HashMap<>(); + Map objectNames = new HashMap(); objectNames.put("group1_name", group1Key); - Map> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectNames, - response, solrTemplate, Object.class); + Map> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, + objectNames, response, solrTemplate, Object.class); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); @@ -524,16 +535,16 @@ public void testConvertGroupQueryResponseToGroupResultListWhenNoCountOfGroups() GroupCommand groupCommand1 = Mockito.mock(GroupCommand.class); Group group1_1 = Mockito.mock(Group.class); SolrDocumentList group1_1DocumentList = Mockito.mock(SolrDocumentList.class); - List documents1_1 = Collections.singletonList(new Object()); + List documents1_1 = Arrays.asList(new Object()); Mockito.when(response.getGroupResponse()).thenReturn(groupResponse); - Mockito.when(groupResponse.getValues()).thenReturn(Collections.singletonList(groupCommand1)); - Mockito.when(groupCommand1.getValues()).thenReturn(Collections.singletonList(group1_1)); + Mockito.when(groupResponse.getValues()).thenReturn(Arrays.asList(groupCommand1)); + Mockito.when(groupCommand1.getValues()).thenReturn(Arrays.asList(group1_1)); Mockito.when(group1_1.getResult()).thenReturn(group1_1DocumentList); Mockito.when(group1_1.getGroupValue()).thenReturn("group1_1_value"); Mockito.when(group1_1DocumentList.getNumFound()).thenReturn(3L); - Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)) - .thenReturn(documents1_1); + Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)).thenReturn( + documents1_1); Mockito.when(groupCommand1.getMatches()).thenReturn(1); Mockito.when(groupCommand1.getName()).thenReturn("group1_name"); Mockito.when(groupCommand1.getNGroups()).thenReturn(null); @@ -545,11 +556,11 @@ public void testConvertGroupQueryResponseToGroupResultListWhenNoCountOfGroups() Mockito.when(query.getGroupOptions()).thenReturn(groupOptions); Object group1Key = new Object(); - Map objectNames = new HashMap<>(); + Map objectNames = new HashMap(); objectNames.put("group1_name", group1Key); - Map> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectNames, - response, solrTemplate, Object.class); + Map> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, + objectNames, response, solrTemplate, Object.class); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); @@ -581,7 +592,7 @@ public void testConvertGroupQueryResponseToGroupResultListWhenNoCountOfGroups() @Test // DATASOLR-160 public void testConvertSingleFieldStatsInfoToStatsResultMap() { - Map fieldStatsInfos = new HashMap<>(); + Map fieldStatsInfos = new HashMap(); NamedList nl = createFieldStatNameList("min", "max", 20D, 10L, 5L, 22.5D, 15.5D, 1D); @@ -593,8 +604,8 @@ public void testConvertSingleFieldStatsInfoToStatsResultMap() { Assert.assertEquals("min", fieldStatsResult.getMin()); Assert.assertEquals("max", fieldStatsResult.getMax()); - Assert.assertEquals(20d, fieldStatsResult.getSum()); - Assert.assertEquals(22.5, fieldStatsResult.getMean()); + Assert.assertEquals(Double.valueOf(20), fieldStatsResult.getSum()); + Assert.assertEquals(Double.valueOf(22.5), fieldStatsResult.getMean()); Assert.assertEquals(Long.valueOf(10), fieldStatsResult.getCount()); Assert.assertEquals(Long.valueOf(5), fieldStatsResult.getMissing()); Assert.assertEquals(Double.valueOf(15.5), fieldStatsResult.getStddev()); @@ -613,7 +624,8 @@ public void testConvertNullFieldStatsInfoToStatsResultMap() { @Test // DATASOLR-160 public void testConvertEmptyFieldStatsInfoMapToStatsResultMap() { - Map converted = ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(new HashMap<>()); + Map converted = ResultHelper + .convertFieldStatsInfoToFieldStatsResultMap(new HashMap()); Assert.assertThat(converted, IsNull.notNullValue()); Assert.assertThat(converted.entrySet(), IsEmptyIterable.emptyIterable()); @@ -622,8 +634,8 @@ public void testConvertEmptyFieldStatsInfoMapToStatsResultMap() { @Test // DATASOLR-160 public void testConvertFieldStatsInfoMapWithNullToStatsResultMap() { - Map converted = ResultHelper - .convertFieldStatsInfoToFieldStatsResultMap(Collections. singletonMap("field", null)); + Map converted = ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(Collections + . singletonMap("field", null)); Assert.assertThat(converted, IsNull.notNullValue()); Assert.assertThat(converted.keySet(), IsIterableContainingInOrder.contains("field")); @@ -632,8 +644,8 @@ public void testConvertFieldStatsInfoMapWithNullToStatsResultMap() { @Test // DATASOLR-160 public void testConvertFieldStatsInfoMapWithEmptyNamedListToStatsResultMap() { - Map converted = ResultHelper.convertFieldStatsInfoToFieldStatsResultMap( - Collections. singletonMap("field", new FieldStatsInfo(new NamedList<>(), "field"))); + Map converted = ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(Collections + . singletonMap("field", new FieldStatsInfo(new NamedList(), "field"))); Assert.assertThat(converted, IsNull.notNullValue()); Assert.assertThat(converted.keySet(), IsIterableContainingInOrder.contains("field")); @@ -642,10 +654,10 @@ public void testConvertFieldStatsInfoMapWithEmptyNamedListToStatsResultMap() { @Test // DATASOLR-160 public void testConvertFieldStatsInfoToStatsResultMap() { - Map fieldStatsInfos = new HashMap<>(); + Map fieldStatsInfos = new HashMap(); - NamedList values = new NamedList<>(); - NamedList facets = new NamedList<>(); + NamedList values = new NamedList(); + NamedList facets = new NamedList(); NamedList nl = createFieldStatNameList("min", "max", 20D, 10L, 5L, 22.5D, 15.5D, 1D); nl.add("facets", facets); facets.add("facetField", values); @@ -661,8 +673,8 @@ public void testConvertFieldStatsInfoToStatsResultMap() { FieldStatsResult fieldStatsResult = converted.get("field"); Assert.assertEquals("min", fieldStatsResult.getMin()); Assert.assertEquals("max", fieldStatsResult.getMax()); - Assert.assertEquals(20d, fieldStatsResult.getSum()); - Assert.assertEquals(22.5, fieldStatsResult.getMean()); + Assert.assertEquals(Double.valueOf(20), fieldStatsResult.getSum()); + Assert.assertEquals(Double.valueOf(22.5), fieldStatsResult.getMean()); Assert.assertEquals(Long.valueOf(10), fieldStatsResult.getCount()); Assert.assertEquals(Long.valueOf(5), fieldStatsResult.getMissing()); Assert.assertEquals(Double.valueOf(15.5), fieldStatsResult.getStddev()); @@ -679,8 +691,8 @@ public void testConvertFieldStatsInfoToStatsResultMap() { StatsResult facetValue1StatsResult = facetStatsResult.get("value1"); Assert.assertEquals("f1v1min", facetValue1StatsResult.getMin()); Assert.assertEquals("f1v1max", facetValue1StatsResult.getMax()); - Assert.assertEquals(110d, facetValue1StatsResult.getSum()); - Assert.assertEquals(113d, facetValue1StatsResult.getMean()); + Assert.assertEquals(Double.valueOf(110), facetValue1StatsResult.getSum()); + Assert.assertEquals(Double.valueOf(113), facetValue1StatsResult.getMean()); Assert.assertEquals(Long.valueOf(111), facetValue1StatsResult.getCount()); Assert.assertEquals(Long.valueOf(112), facetValue1StatsResult.getMissing()); Assert.assertEquals(Double.valueOf(11.3), facetValue1StatsResult.getStddev()); @@ -688,8 +700,8 @@ public void testConvertFieldStatsInfoToStatsResultMap() { StatsResult facetValue2StatsResult = facetStatsResult.get("value2"); Assert.assertEquals("f1v2min", facetValue2StatsResult.getMin()); Assert.assertEquals("f1v2max", facetValue2StatsResult.getMax()); - Assert.assertEquals(120d, facetValue2StatsResult.getSum()); - Assert.assertEquals(123d, facetValue2StatsResult.getMean()); + Assert.assertEquals(Double.valueOf(120), facetValue2StatsResult.getSum()); + Assert.assertEquals(Double.valueOf(123), facetValue2StatsResult.getMean()); Assert.assertEquals(Long.valueOf(121), facetValue2StatsResult.getCount()); Assert.assertEquals(Long.valueOf(122), facetValue2StatsResult.getMissing()); Assert.assertEquals(Double.valueOf(12.3), facetValue2StatsResult.getStddev()); @@ -717,7 +729,7 @@ public void testConvertFacetRangeQueryResponseToFacetPageMap() { RangeFacet.Numeric rangeFacet2 = new RangeFacet.Numeric("", 10, 20, 2, 4, 6, 8); @SuppressWarnings("rawtypes") - List value = new ArrayList<>(); + List value = new ArrayList(); value.add(rangeFacet1); value.add(rangeFacet2); Mockito.when(response.getFacetRanges()).thenReturn(value); @@ -741,7 +753,7 @@ public void testConvertFacetRangeQueryResponseToFacetPageMap() { @Test // DATASOLR-305 public void testConvertFacetQueryResponseForNegativeFacetLimit() { - List fieldList = new ArrayList<>(1); + List fieldList = new ArrayList(1); FacetField ffield = createFacetField("field_1", 1, 2); fieldList.add(ffield); @@ -757,7 +769,7 @@ public void testConvertFacetQueryResponseForNegativeFacetLimit() { private NamedList createFieldStatNameList(Object min, Object max, Double sum, Long count, Long missing, Object mean, Double stddev, Double sumOfSquares) { - NamedList nl = new NamedList<>(); + NamedList nl = new NamedList(); nl.add("min", min); nl.add("max", max); nl.add("sum", sum); @@ -797,7 +809,7 @@ private FacetField createFacetField(String fieldName, long... values) { private static class SolrBeanWithIdNamedField { - @SuppressWarnings("unused") // + @SuppressWarnings("unused")// private String id; public SolrBeanWithIdNamedField(String id) { diff --git a/src/test/java/org/springframework/data/solr/core/SolrTemplateTests.java b/src/test/java/org/springframework/data/solr/core/SolrTemplateTests.java index 71df05a..bab2119 100644 --- a/src/test/java/org/springframework/data/solr/core/SolrTemplateTests.java +++ b/src/test/java/org/springframework/data/solr/core/SolrTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * 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. @@ -15,20 +15,11 @@ */ package org.springframework.data.solr.core; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyCollection; -import static org.mockito.Mockito.anyString; -import static org.mockito.Mockito.nullable; +import static org.mockito.Matchers.*; import java.io.IOException; -import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -36,8 +27,8 @@ import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; +import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrClient.RemoteSolrException; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest.SchemaVersion; import org.apache.solr.client.solrj.response.QueryResponse; @@ -51,6 +42,7 @@ import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.hamcrest.core.Is; +import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.Assert; @@ -58,25 +50,33 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.convert.converter.Converter; -import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.annotation.Id; import org.springframework.data.domain.PageRequest; +import org.springframework.data.solr.ExampleSolrBean; import org.springframework.data.solr.UncategorizedSolrException; import org.springframework.data.solr.core.mapping.Indexed; import org.springframework.data.solr.core.mapping.SolrDocument; +import org.springframework.data.solr.core.query.AnyCriteria; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.PartialUpdate; import org.springframework.data.solr.core.query.Query; +import org.springframework.data.solr.core.query.SimpleFacetAndHighlightQuery; +import org.springframework.data.solr.core.query.SimpleFacetQuery; +import org.springframework.data.solr.core.query.SimpleHighlightQuery; import org.springframework.data.solr.core.query.SimpleQuery; import org.springframework.data.solr.core.query.SimpleStringCriteria; +import org.springframework.data.solr.core.query.SimpleTermsQuery; import org.springframework.data.solr.core.query.SolrDataQuery; import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator.Feature; +import org.springframework.data.solr.repository.ProductBean; import org.springframework.data.solr.repository.Score; import org.springframework.data.solr.server.SolrClientFactory; @@ -85,7 +85,7 @@ * @author Joachim Uhrlass * @author Francisco Spaeth */ -@RunWith(MockitoJUnitRunner.Silent.class) +@RunWith(MockitoJUnitRunner.class) public class SolrTemplateTests { private SolrTemplate solrTemplate; @@ -94,13 +94,12 @@ public class SolrTemplateTests { private static final SimpleBoostedJavaObject SIMPLE_BOOSTED_OBJECT = new SimpleBoostedJavaObject("simple-string-id", 123l, "simple-string-boost"); private static final SolrInputDocument SIMPLE_DOCUMENT = new SolrInputDocument(); - private static final String COLLECTION_NAME = "collection-1"; private @Mock SolrClient solrClientMock; @Before public void setUp() { - solrTemplate = new SolrTemplate(solrClientMock); + solrTemplate = new SolrTemplate(solrClientMock, "core1"); solrTemplate.afterPropertiesSet(); } @@ -111,176 +110,173 @@ public void testNullServerFactory() { @Test public void testPing() throws SolrServerException, IOException { - when(solrClientMock.ping()).thenReturn(new SolrPingResponse()); + Mockito.when(solrClientMock.ping()).thenReturn(new SolrPingResponse()); SolrPingResponse pingResult = solrTemplate.ping(); - assertNotNull(pingResult); - verify(solrClientMock, times(1)).ping(); + Assert.assertNotNull(pingResult); + Mockito.verify(solrClientMock, Mockito.times(1)).ping(); } - @Test(expected = DataAccessResourceFailureException.class) + @Test(expected = DataAccessException.class) public void testPingThrowsException() throws SolrServerException, IOException { - when(solrClientMock.ping()) + Mockito.when(solrClientMock.ping()) .thenThrow(new SolrServerException("error", new SolrException(ErrorCode.NOT_FOUND, "not found"))); solrTemplate.ping(); } - @Test(expected = DataAccessResourceFailureException.class) // DATASOLR-414 - public void testPingThrowsExceptionCorrectlyWhenMimeTypeDoesNotMatch() throws SolrServerException, IOException { - - when(solrClientMock.ping()).thenThrow(new RemoteSolrException("localhost", 404, - "Error from server at http://localhost:8983: Expected mime type application/octet-stream but got text/html.", - null)); - solrTemplate.ping(); - } - @Test(expected = InvalidDataAccessApiUsageException.class) public void testQueryThrowsParseException() throws SolrServerException, IOException { - when(solrClientMock.query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.GET))).thenThrow( + Mockito.when(solrClientMock.query(Matchers.any(SolrParams.class), Mockito.eq(SolrRequest.METHOD.GET))).thenThrow( new SolrServerException("error", new SolrException(ErrorCode.BAD_REQUEST, new ParseException("parse error")))); solrTemplate.executeSolrQuery(new SolrQuery(), SolrRequest.METHOD.GET); } @Test(expected = UncategorizedSolrException.class) public void testQueryThrowsUntranslateableException() throws SolrServerException, IOException { - when(solrClientMock.query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.GET))) + Mockito.when(solrClientMock.query(Matchers.any(SolrParams.class), Mockito.eq(SolrRequest.METHOD.GET))) .thenThrow(new SecurityException()); solrTemplate.executeSolrQuery(new SolrQuery(), SolrRequest.METHOD.GET); } @Test public void testSaveBean() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), any(SolrInputDocument.class), eq(-1))) + Mockito.when(solrClientMock.add(Mockito.anyString(), Mockito.any(SolrInputDocument.class), Mockito.eq(-1))) .thenReturn(new UpdateResponse()); - UpdateResponse updateResponse = solrTemplate.saveBean(COLLECTION_NAME, SIMPLE_OBJECT); - assertNotNull(updateResponse); + UpdateResponse updateResponse = solrTemplate.saveBean(SIMPLE_OBJECT); + Assert.assertNotNull(updateResponse); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); - assertEquals(SIMPLE_OBJECT.getId(), captor.getValue().getFieldValue("id")); - assertEquals(SIMPLE_OBJECT.getValue(), captor.getValue().getFieldValue("value")); + Assert.assertEquals(SIMPLE_OBJECT.getId(), captor.getValue().getFieldValue("id")); + Assert.assertEquals(SIMPLE_OBJECT.getValue(), captor.getValue().getFieldValue("value")); } @Test public void testSaveBeanCommitWithin() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), any(SolrInputDocument.class), eq(10000))) + Mockito.when(solrClientMock.add(Mockito.anyString(), Mockito.any(SolrInputDocument.class), Mockito.eq(10000))) .thenReturn(new UpdateResponse()); - UpdateResponse updateResponse = solrTemplate.saveBean(COLLECTION_NAME, SIMPLE_OBJECT, Duration.ofSeconds(10)); - assertNotNull(updateResponse); + UpdateResponse updateResponse = solrTemplate.saveBean(SIMPLE_OBJECT, 10000); + Assert.assertNotNull(updateResponse); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(10000)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(10000)); - assertEquals(SIMPLE_OBJECT.getId(), captor.getValue().getFieldValue("id")); - assertEquals(SIMPLE_OBJECT.getValue(), captor.getValue().getFieldValue("value")); + Assert.assertEquals(SIMPLE_OBJECT.getId(), captor.getValue().getFieldValue("id")); + Assert.assertEquals(SIMPLE_OBJECT.getValue(), captor.getValue().getFieldValue("value")); } @SuppressWarnings("unchecked") @Test public void testPartialUpdate() throws SolrServerException, IOException { - when(solrClientMock.add(eq(COLLECTION_NAME), any(SolrInputDocument.class), eq(-1))) + Mockito.when(solrClientMock.add(Mockito.anyString(), Mockito.any(SolrInputDocument.class), Mockito.eq(-1))) .thenReturn(new UpdateResponse()); PartialUpdate update = new PartialUpdate("id", "update-id"); update.add("field_1", "update"); - solrTemplate.saveBean(COLLECTION_NAME, update); + solrTemplate.saveBean(update); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); Assert.assertTrue(captor.getValue().getFieldValue("field_1") instanceof Map); - assertEquals("update", ((Map) captor.getValue().getFieldValue("field_1")).get("set")); + Assert.assertEquals("update", ((Map) captor.getValue().getFieldValue("field_1")).get("set")); } @SuppressWarnings("unchecked") @Test public void testSaveBeans() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), anyCollection(), eq(-1))).thenReturn(new UpdateResponse()); + Mockito + .when(solrClientMock.add(Mockito.anyString(), Mockito.anyCollectionOf(SolrInputDocument.class), Mockito.eq(-1))) + .thenReturn(new UpdateResponse()); List collection = Arrays.asList(new SimpleJavaObject("1", 1l), new SimpleJavaObject("2", 2l), new SimpleJavaObject("3", 3l)); - UpdateResponse updateResponse = solrTemplate.saveBeans(COLLECTION_NAME, collection); - assertNotNull(updateResponse); + UpdateResponse updateResponse = solrTemplate.saveBeans(collection); + Assert.assertNotNull(updateResponse); @SuppressWarnings("rawtypes") ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); - assertEquals(3, captor.getValue().size()); + Assert.assertEquals(3, captor.getValue().size()); } @SuppressWarnings("unchecked") @Test public void testSaveBeansCommitWithin() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), anyCollection(), eq(10000))).thenReturn(new UpdateResponse()); + Mockito.when( + solrClientMock.add(Mockito.anyString(), Mockito.anyCollectionOf(SolrInputDocument.class), Mockito.eq(10000))) + .thenReturn(new UpdateResponse()); List collection = Arrays.asList(new SimpleJavaObject("1", 1l), new SimpleJavaObject("2", 2l), new SimpleJavaObject("3", 3l)); - UpdateResponse updateResponse = solrTemplate.saveBeans(COLLECTION_NAME, collection, Duration.ofSeconds(10)); - assertNotNull(updateResponse); + UpdateResponse updateResponse = solrTemplate.saveBeans(collection, 10000); + Assert.assertNotNull(updateResponse); @SuppressWarnings("rawtypes") ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(10000)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(10000)); - assertEquals(3, captor.getValue().size()); + Assert.assertEquals(3, captor.getValue().size()); } @Test public void testSaveDocument() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), any(SolrInputDocument.class), eq(-1))) + Mockito.when(solrClientMock.add(Mockito.any(SolrInputDocument.class), Mockito.eq(-1))) .thenReturn(new UpdateResponse()); - UpdateResponse updateResponse = solrTemplate.saveDocument(COLLECTION_NAME, SIMPLE_DOCUMENT); - assertNotNull(updateResponse); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), eq(SIMPLE_DOCUMENT), eq(-1)); + UpdateResponse updateResponse = solrTemplate.saveDocument(SIMPLE_DOCUMENT); + Assert.assertNotNull(updateResponse); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq(SIMPLE_DOCUMENT), Mockito.eq(-1)); } @Test public void testSaveDocumentCommitWithin() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), any(SolrInputDocument.class), eq(10000))) + Mockito.when(solrClientMock.add(Mockito.any(SolrInputDocument.class), Mockito.eq(10000))) .thenReturn(new UpdateResponse()); - UpdateResponse updateResponse = solrTemplate.saveDocument(COLLECTION_NAME, SIMPLE_DOCUMENT, Duration.ofSeconds(10)); - assertNotNull(updateResponse); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), eq(SIMPLE_DOCUMENT), eq(10000)); + UpdateResponse updateResponse = solrTemplate.saveDocument(SIMPLE_DOCUMENT, 10000); + Assert.assertNotNull(updateResponse); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq(SIMPLE_DOCUMENT), Mockito.eq(10000)); } @Test public void testSaveDocuments() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), anyCollection(), eq(-1))).thenReturn(new UpdateResponse()); - List collection = Collections.singletonList(SIMPLE_DOCUMENT); - UpdateResponse updateResponse = solrTemplate.saveDocuments(COLLECTION_NAME, collection); - assertNotNull(updateResponse); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), eq(collection), eq(-1)); + Mockito.when(solrClientMock.add(Mockito.anyCollectionOf(SolrInputDocument.class), Mockito.eq(-1))) + .thenReturn(new UpdateResponse()); + List collection = Arrays.asList(SIMPLE_DOCUMENT); + UpdateResponse updateResponse = solrTemplate.saveDocuments(collection); + Assert.assertNotNull(updateResponse); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq(collection), Mockito.eq(-1)); } @Test public void testSaveDocumentsCommitWithin() throws IOException, SolrServerException { - when(solrClientMock.add(eq(COLLECTION_NAME), anyCollection(), eq(10000))).thenReturn(new UpdateResponse()); - List collection = Collections.singletonList(SIMPLE_DOCUMENT); - UpdateResponse updateResponse = solrTemplate.saveDocuments(COLLECTION_NAME, collection, Duration.ofSeconds(10)); - assertNotNull(updateResponse); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), eq(collection), eq(10000)); + Mockito.when(solrClientMock.add(Mockito.anyCollectionOf(SolrInputDocument.class), Mockito.eq(10000))) + .thenReturn(new UpdateResponse()); + List collection = Arrays.asList(SIMPLE_DOCUMENT); + UpdateResponse updateResponse = solrTemplate.saveDocuments(collection, 10000); + Assert.assertNotNull(updateResponse); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq(collection), Mockito.eq(10000)); } @Test public void testDeleteById() throws IOException, SolrServerException { - when(solrClientMock.deleteById(eq(COLLECTION_NAME), Mockito.anyString())).thenReturn(new UpdateResponse()); - UpdateResponse updateResponse = solrTemplate.deleteByIds(COLLECTION_NAME, "1"); - assertNotNull(updateResponse); - verify(solrClientMock, times(1)).deleteById(eq(COLLECTION_NAME), eq("1")); + Mockito.when(solrClientMock.deleteById(Mockito.anyString())).thenReturn(new UpdateResponse()); + UpdateResponse updateResponse = solrTemplate.deleteById("1"); + Assert.assertNotNull(updateResponse); + Mockito.verify(solrClientMock, Mockito.times(1)).deleteById(Mockito.eq("1")); } @Test public void testDeleteByIdWithCollection() throws IOException, SolrServerException { - when(solrClientMock.deleteById(eq(COLLECTION_NAME), anyList())).thenReturn(new UpdateResponse()); + Mockito.when(solrClientMock.deleteById(Mockito.anyListOf(String.class))).thenReturn(new UpdateResponse()); List idsToDelete = Arrays.asList("1", "2"); - UpdateResponse updateResponse = solrTemplate.deleteByIds(COLLECTION_NAME, idsToDelete); - assertNotNull(updateResponse); + UpdateResponse updateResponse = solrTemplate.deleteById(idsToDelete); + Assert.assertNotNull(updateResponse); @SuppressWarnings("unchecked") ArgumentCaptor> captor = (ArgumentCaptor>) (Object) ArgumentCaptor.forClass(List.class); - verify(solrClientMock, times(1)).deleteById(eq(COLLECTION_NAME), captor.capture()); + Mockito.verify(solrClientMock, Mockito.times(1)).deleteById(captor.capture()); - assertEquals(idsToDelete.size(), captor.getValue().size()); + Assert.assertEquals(idsToDelete.size(), captor.getValue().size()); for (String s : idsToDelete) { Assert.assertTrue(captor.getValue().contains(s)); } @@ -292,17 +288,17 @@ public void testCount() throws SolrServerException, IOException { QueryResponse responseMock = Mockito.mock(QueryResponse.class); SolrDocumentList resultList = new SolrDocumentList(); resultList.setNumFound(10); - when(responseMock.getResults()).thenReturn(resultList); - when(solrClientMock.query(eq(COLLECTION_NAME), any(SolrQuery.class), eq(SolrRequest.METHOD.GET))) + Mockito.when(responseMock.getResults()).thenReturn(resultList); + Mockito.when(solrClientMock.query(Mockito.any(SolrQuery.class), Mockito.eq(SolrRequest.METHOD.GET))) .thenReturn(responseMock); - long result = solrTemplate.count(COLLECTION_NAME, new SimpleQuery(new Criteria("field_1").is("value1"))); - assertEquals(resultList.getNumFound(), result); + long result = solrTemplate.count(new SimpleQuery(new Criteria("field_1").is("value1"))); + Assert.assertEquals(resultList.getNumFound(), result); - verify(solrClientMock, times(1)).query(eq(COLLECTION_NAME), captor.capture(), eq(SolrRequest.METHOD.GET)); + Mockito.verify(solrClientMock, Mockito.times(1)).query(captor.capture(), Mockito.eq(SolrRequest.METHOD.GET)); - assertEquals(Integer.valueOf(0), captor.getValue().getStart()); - assertEquals(Integer.valueOf(0), captor.getValue().getRows()); + Assert.assertEquals(Integer.valueOf(0), captor.getValue().getStart()); + Assert.assertEquals(Integer.valueOf(0), captor.getValue().getRows()); } @Test @@ -311,47 +307,48 @@ public void testCountWhenPagingSet() throws SolrServerException, IOException { QueryResponse responseMock = Mockito.mock(QueryResponse.class); SolrDocumentList resultList = new SolrDocumentList(); resultList.setNumFound(10); - when(responseMock.getResults()).thenReturn(resultList); - when(solrClientMock.query(eq(COLLECTION_NAME), any(SolrQuery.class), eq(SolrRequest.METHOD.GET))) + Mockito.when(responseMock.getResults()).thenReturn(resultList); + Mockito.when(solrClientMock.query(Mockito.any(SolrQuery.class), Mockito.eq(SolrRequest.METHOD.GET))) .thenReturn(responseMock); Query query = new SimpleQuery(new Criteria("field_1").is("value1")); - query.setPageRequest(PageRequest.of(0, 5)); - long result = solrTemplate.count(COLLECTION_NAME, query); - assertEquals(resultList.getNumFound(), result); + query.setPageRequest(new PageRequest(0, 5)); + long result = solrTemplate.count(query); + Assert.assertEquals(resultList.getNumFound(), result); - verify(solrClientMock, times(1)).query(eq(COLLECTION_NAME), captor.capture(), eq(SolrRequest.METHOD.GET)); + Mockito.verify(solrClientMock, Mockito.times(1)).query(captor.capture(), Mockito.eq(SolrRequest.METHOD.GET)); - assertEquals(Integer.valueOf(0), captor.getValue().getStart()); - assertEquals(Integer.valueOf(0), captor.getValue().getRows()); + Assert.assertEquals(Integer.valueOf(0), captor.getValue().getStart()); + Assert.assertEquals(Integer.valueOf(0), captor.getValue().getRows()); } @Test(expected = IllegalArgumentException.class) public void testCountNullQuery() { - solrTemplate.count(COLLECTION_NAME, null); + solrTemplate.count(null); } @Test public void testCommit() throws SolrServerException, IOException { - solrTemplate.commit(COLLECTION_NAME); - verify(solrClientMock, times(1)).commit(eq(COLLECTION_NAME)); + solrTemplate.commit(); + Mockito.verify(solrClientMock, Mockito.times(1)).commit(); } @Test public void testSoftCommit() throws SolrServerException, IOException { - solrTemplate.softCommit(COLLECTION_NAME); - verify(solrClientMock, times(1)).commit(eq(COLLECTION_NAME), eq(true), eq(true), eq(true)); + solrTemplate.softCommit(); + Mockito.verify(solrClientMock, Mockito.times(1)).commit(Matchers.eq(true), Matchers.eq(true), Matchers.eq(true)); } @Test public void testRollback() throws SolrServerException, IOException { - solrTemplate.rollback(COLLECTION_NAME); - verify(solrClientMock, times(1)).rollback(); + solrTemplate.rollback(); + Mockito.verify(solrClientMock, Mockito.times(1)).rollback(); } @Test public void testDifferentQueryParser() throws SolrServerException, IOException { - QueryParser parser = new QueryParser() { + + QueryParser parser = new QueryParser() { @Override public void registerConverter(Converter converter) {} @@ -368,140 +365,391 @@ public SolrQuery constructSolrQuery(SolrDataQuery query) { }; + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + solrTemplate.registerQueryParser(SimpleQuery.class, parser); - solrTemplate.querySolr("collection-1", new SimpleQuery(new SimpleStringCriteria("my:criteria")), null, null); + solrTemplate.query("core1", new SimpleQuery(new SimpleStringCriteria("my:criteria")), ProductBean.class); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrParams.class); - verify(solrClientMock, times(1)).query(nullable(String.class), captor.capture(), eq(SolrRequest.METHOD.GET)); - assertEquals("*:*", captor.getValue().getParams(CommonParams.Q)[0]); + Mockito.verify(solrClientMock, Mockito.times(1)).query(Mockito.eq("core1"), captor.capture(), + Mockito.eq(SolrRequest.METHOD.GET)); + Assert.assertEquals("*:*", captor.getValue().getParams(CommonParams.Q)[0]); } @Test // DATASOLR-88 public void testSaveBoostedShouldUseDocumentBoost() throws IOException, SolrServerException, SecurityException, NoSuchFieldException { - solrTemplate.saveBean(COLLECTION_NAME, SIMPLE_BOOSTED_OBJECT); + solrTemplate.saveBean(SIMPLE_BOOSTED_OBJECT); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); - assertEquals(SIMPLE_BOOSTED_OBJECT.getId(), captor.getValue().getFieldValue("id")); - assertEquals(SIMPLE_BOOSTED_OBJECT.getValue(), captor.getValue().getFieldValue("value")); + Assert.assertEquals(SIMPLE_BOOSTED_OBJECT.getId(), captor.getValue().getFieldValue("id")); + Assert.assertEquals(SIMPLE_BOOSTED_OBJECT.getValue(), captor.getValue().getFieldValue("value")); float entityBoost = AnnotationUtils.getAnnotation(SIMPLE_BOOSTED_OBJECT.getClass(), SolrDocument.class).boost(); - assertThat(captor.getValue().getDocumentBoost(), Is.is(entityBoost)); + Assert.assertThat(captor.getValue().getDocumentBoost(), Is.is(entityBoost)); } @Test // DATASOLR-88 public void testSaveBoostedShouldUseFieldBoostViaIndexedAnnotation() throws IOException, SolrServerException, SecurityException, NoSuchFieldException { - solrTemplate.saveBean(COLLECTION_NAME, SIMPLE_BOOSTED_OBJECT); + solrTemplate.saveBean(SIMPLE_BOOSTED_OBJECT); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); - assertEquals(SIMPLE_BOOSTED_OBJECT.getId(), captor.getValue().getFieldValue("id")); - assertEquals(SIMPLE_BOOSTED_OBJECT.getValue(), captor.getValue().getFieldValue("value")); + Assert.assertEquals(SIMPLE_BOOSTED_OBJECT.getId(), captor.getValue().getFieldValue("id")); + Assert.assertEquals(SIMPLE_BOOSTED_OBJECT.getValue(), captor.getValue().getFieldValue("value")); float fieldBoost = AnnotationUtils .getAnnotation(SIMPLE_BOOSTED_OBJECT.getClass().getDeclaredField("boostedField"), Indexed.class).boost(); - assertThat(captor.getValue().getField("boostedField").getBoost(), Is.is(fieldBoost)); + Assert.assertThat(captor.getValue().getField("boostedField").getBoost(), Is.is(fieldBoost)); } - @Test // DATASOLR-72, DATASOLR-313, DATASOLR-309 + @Test // DATASOLR-72, DATASOLR-313 public void schemaShouldBeUpdatedPriorToSavingEntity() throws SolrServerException, IOException { - NamedList nl = new NamedList<>(); - Map schema = new LinkedHashMap<>(); + NamedList nl = new NamedList(); + NamedList schema = new NamedList(); nl.add("version", 1.5F); nl.add("schema", schema); - schema.put("version", 1.5F); - schema.put("name", "mock"); - schema.put("fields", Collections.> emptyList()); - schema.put("dynamicFields", Collections.> emptyList()); - schema.put("fieldTypes", Collections.> emptyList()); - schema.put("copyFields", Collections.> emptyList()); + schema.add("version", 1.5F); + schema.add("name", "mock"); + schema.add("fields", Collections.> emptyList()); + schema.add("dynamicFields", Collections.> emptyList()); + schema.add("fieldTypes", Collections.> emptyList()); + schema.add("copyFields", Collections.> emptyList()); // schema.add(name, val); - when(solrClientMock.request((SchemaVersion) any(), anyString())).thenReturn(nl); - when(solrClientMock.request((SchemaRequest) any(), anyString())).thenReturn(nl); + Mockito.when(solrClientMock.request(Mockito.any(SchemaVersion.class), Mockito.anyString())).thenReturn(nl); + Mockito.when(solrClientMock.request(Mockito.any(SchemaRequest.class), Mockito.anyString())).thenReturn(nl); - solrTemplate = new SolrTemplate(solrClientMock); + solrTemplate = new SolrTemplate(solrClientMock, "core1"); solrTemplate.setSchemaCreationFeatures(Collections.singletonList(Feature.CREATE_MISSING_FIELDS)); solrTemplate.afterPropertiesSet(); - solrTemplate.saveBean(COLLECTION_NAME, new DocumentWithIndexAnnotations()); + solrTemplate.saveBean(new DocumentWithIndexAnnotations()); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(SolrRequest.class); - verify(solrClientMock, times(4)).request(requestCaptor.capture(), Mockito.anyString()); + Mockito.verify(solrClientMock, Mockito.times(4)).request(requestCaptor.capture(), Mockito.anyString()); SolrRequest capturedRequest = requestCaptor.getValue(); - assertThat(capturedRequest.getMethod(), IsEqual.equalTo(SolrRequest.METHOD.POST)); - assertThat(capturedRequest.getPath(), IsEqual.equalTo("/schema")); - assertThat(capturedRequest.getContentStreams(), IsNull.notNullValue()); + Assert.assertThat(capturedRequest.getMethod(), IsEqual.equalTo(SolrRequest.METHOD.POST)); + Assert.assertThat(capturedRequest.getPath(), IsEqual.equalTo("/schema")); + Assert.assertThat(capturedRequest.getContentStreams(), IsNull.notNullValue()); } - @Test // DATASOLR-83 + @Test // DATASOLR-83, DATASOLR-321 + @SuppressWarnings({ "rawtypes", "unchecked" }) public void testGetById() throws SolrServerException, IOException { - when(solrClientMock.getById(eq(COLLECTION_NAME), anyCollection())).thenReturn(new SolrDocumentList()); + ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); - solrTemplate.getById(COLLECTION_NAME, "myId", DocumentWithIndexAnnotations.class); + solrTemplate.getById("myId", DocumentWithIndexAnnotations.class); - verify(solrClientMock, times(1)).getById(eq(COLLECTION_NAME), eq(Collections.singletonList("myId"))); + Mockito.verify(solrClientMock, Mockito.times(1)).getById(eq("core1"), captor.capture()); + Assert.assertThat((List) captor.getValue(), IsCollectionContaining.hasItems("myId")); } - @Test // DATASOLR-83 + @Test // DATASOLR-83, DATASOLR-321 + @SuppressWarnings({ "rawtypes", "unchecked" }) public void testGetByIds() throws SolrServerException, IOException { - when(solrClientMock.getById(eq(COLLECTION_NAME), anyCollection())).thenReturn(new SolrDocumentList()); + ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); List ids = Arrays.asList("myId1", "myId2"); - solrTemplate.getByIds(COLLECTION_NAME, ids, DocumentWithIndexAnnotations.class); + solrTemplate.getById(ids, DocumentWithIndexAnnotations.class); - verify(solrClientMock, times(1)).getById(eq(COLLECTION_NAME), eq(ids)); + Mockito.verify(solrClientMock, Mockito.times(1)).getById(eq("core1"), captor.capture()); + Assert.assertThat((List) captor.getValue(), IsCollectionContaining.hasItems("myId1", "myId2")); } @Test // DATASOLR-160 public void testSaveShouldNotSaveScoreField() throws IOException, SolrServerException, SecurityException, NoSuchFieldException { - solrTemplate.saveBean(COLLECTION_NAME, new DocumentWithScoreAnnotation()); + solrTemplate.saveBean(new DocumentWithScoreAnnotation()); ArgumentCaptor captor = ArgumentCaptor.forClass(SolrInputDocument.class); - verify(solrClientMock, times(1)).add(eq(COLLECTION_NAME), captor.capture(), eq(-1)); + Mockito.verify(solrClientMock, Mockito.times(1)).add(Mockito.eq("core1"), captor.capture(), Mockito.eq(-1)); - assertNull(captor.getValue().getFieldValue("score")); + Assert.assertNull(captor.getValue().getFieldValue("score")); } @Test // DATASOLR-215 public void usesTemplateDefaultRequestMethodForQuery() throws SolrServerException, IOException { - solrTemplate = new SolrTemplate(solrClientMock, RequestMethod.POST); + solrTemplate = new SolrTemplate(solrClientMock, "core1", RequestMethod.POST); solrTemplate.afterPropertiesSet(); - when(solrClientMock.query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.POST))) - .thenReturn(new QueryResponse()); - solrTemplate.querySolr(COLLECTION_NAME, new SimpleQuery("*:*"), DocumentWithIndexAnnotations.class, null); + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); - verify(solrClientMock, times(1)).query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.POST)); + solrTemplate.query("core1", new SimpleQuery("*:*"), DocumentWithIndexAnnotations.class); + + Mockito.verify(solrClientMock, Mockito.times(1)).query(Mockito.eq("core1"), Matchers.any(SolrParams.class), + Mockito.eq(SolrRequest.METHOD.POST)); } @Test // DATASOLR-215 public void usesTemplateMethodRequetsParameterForQuery() throws SolrServerException, IOException { - solrTemplate = new SolrTemplate(solrClientMock, RequestMethod.POST); + solrTemplate = new SolrTemplate(solrClientMock, "core1", RequestMethod.POST); solrTemplate.afterPropertiesSet(); - when(solrClientMock.query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.PUT))) - .thenReturn(new QueryResponse()); - solrTemplate.querySolr(COLLECTION_NAME, new SimpleQuery("*:*"), DocumentWithIndexAnnotations.class, - RequestMethod.PUT); + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.query("core1", new SimpleQuery("*:*"), DocumentWithIndexAnnotations.class, RequestMethod.PUT); + + Mockito.verify(solrClientMock, Mockito.times(1)).query(Mockito.eq("core1"), Matchers.any(SolrParams.class), + Mockito.eq(SolrRequest.METHOD.PUT)); + } + + @Test // DATASOLR-321 + public void countUsesDedicatedCollectionName() throws SolrServerException, IOException { + + SolrDocumentList sdl = Mockito.mock(SolrDocumentList.class); + QueryResponse response = Mockito.mock(QueryResponse.class); + Mockito.when(response.getResults()).thenReturn(sdl); + Mockito.when(sdl.getNumFound()).thenReturn(1L); + + Mockito.when(solrClientMock.query(Mockito.anyString(), Mockito.any(SolrParams.class), Mockito.any(METHOD.class))) + .thenReturn(response); + + solrTemplate.count("foo", new SimpleQuery(AnyCriteria.any())); + + Mockito.verify(solrClientMock, Mockito.times(1)).query(Mockito.eq("foo"), Mockito.any(SolrParams.class), + Mockito.any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void countUsesDedicatedCollectionNameAndRequestMethod() throws SolrServerException, IOException { + + SolrDocumentList sdl = Mockito.mock(SolrDocumentList.class); + QueryResponse response = Mockito.mock(QueryResponse.class); + Mockito.when(response.getResults()).thenReturn(sdl); + Mockito.when(sdl.getNumFound()).thenReturn(1L); + + Mockito.when(solrClientMock.query(Mockito.anyString(), Mockito.any(SolrParams.class), Mockito.any(METHOD.class))) + .thenReturn(response); + + solrTemplate.count("foo", new SimpleQuery(AnyCriteria.any()), RequestMethod.POST); + + Mockito.verify(solrClientMock, Mockito.times(1)).query(Mockito.eq("foo"), Mockito.any(SolrParams.class), + Mockito.eq(METHOD.POST)); + } + + @Test // DATASOLR-321 + public void saveBeanShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.saveBean("foo", new ProductBean()); + + Mockito.verify(solrClientMock).add(Mockito.eq("foo"), Mockito.any(SolrInputDocument.class), anyInt()); + } + + @Test // DATASOLR-321 + public void saveBeansShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.saveBeans("foo", Arrays.asList(new ProductBean(), new ProductBean())); + + Mockito.verify(solrClientMock).add(Mockito.eq("foo"), Mockito.anyCollectionOf(SolrInputDocument.class), anyInt()); + } + + @Test // DATASOLR-321 + public void saveDocumentShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.saveDocument("foo", new SolrInputDocument()); + + Mockito.verify(solrClientMock).add(Mockito.eq("foo"), any(SolrInputDocument.class), anyInt()); + } + + @Test // DATASOLR-321 + public void saveDocumentsShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.saveDocuments("foo", Arrays.asList(new SolrInputDocument(), new SolrInputDocument())); + + Mockito.verify(solrClientMock).add(Mockito.eq("foo"), anyCollectionOf(SolrInputDocument.class), anyInt()); + } + + @Test // DATASOLR-321 + public void deleteShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.delete("foo", new SimpleQuery(AnyCriteria.any())); + + Mockito.verify(solrClientMock).deleteByQuery(Mockito.eq("foo"), anyString()); + } + + @Test // DATASOLR-321 + public void deleteByIdShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.deleteById("foo", "one"); + + Mockito.verify(solrClientMock).deleteById(Mockito.eq("foo"), anyString()); + } + + @Test // DATASOLR-321 + public void deleteByIdsShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.deleteById("foo", Arrays.asList("one")); + + Mockito.verify(solrClientMock).deleteById(Mockito.eq("foo"), anyListOf(String.class)); + } + + @Test // DATASOLR-321 + public void queryForObjectShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForObject("foo", new SimpleQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForPageShouldUseDerivedCollectionName() throws SolrServerException, IOException { + + solrTemplate = new SolrTemplate(solrClientMock); + solrTemplate.afterPropertiesSet(); + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForPage(new SimpleQuery(AnyCriteria.any()), ExampleSolrBean.class); + + Mockito.verify(solrClientMock).query(eq("collection1"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForPage("foo", new SimpleQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + // TODO: go on with query for group page here! + @Test // DATASOLR-321 + public void queryForGroupPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForGroupPage("foo", new SimpleQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForStatsPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForStatsPage("foo", new SimpleQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForFacetPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForFacetPage("foo", new SimpleFacetQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForHighlightPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForHighlightPage("foo", new SimpleHighlightQuery(AnyCriteria.any()), ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForFacetAndHighlightPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForFacetAndHighlightPage("foo", new SimpleFacetAndHighlightQuery(AnyCriteria.any()), + ProductBean.class); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void queryForTermsPageShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + QueryResponse response = createAndInitEmptySolrQueryReponseMock(); + Mockito.when(solrClientMock.query(anyString(), any(SolrParams.class), any(METHOD.class))).thenReturn(response); + + solrTemplate.queryForTermsPage("foo", new SimpleTermsQuery()); + + Mockito.verify(solrClientMock).query(eq("foo"), any(SolrParams.class), any(METHOD.class)); + } + + @Test // DATASOLR-321 + public void commitShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.commit("foo"); + + Mockito.verify(solrClientMock).commit(eq("foo")); + } + + @Test // DATASOLR-321 + public void softCommitShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.softCommit("foo"); + + Mockito.verify(solrClientMock).commit(eq("foo"), eq(true), eq(true), eq(true)); + } + + @Test // DATASOLR-321 + public void rollbackShouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + solrTemplate.rollback("foo"); + + Mockito.verify(solrClientMock).rollback(eq("foo")); + } + + @Test // DATASOLR-321 + public void getByIdhouldUseDedicatedCollectionName() throws SolrServerException, IOException { + + Mockito.when(solrClientMock.getById(anyString(), anyCollectionOf(String.class))) + .thenReturn(new org.apache.solr.common.SolrDocumentList()); + + solrTemplate.getById("foo", "id-1", ProductBean.class); + + Mockito.verify(solrClientMock).getById(eq("foo"), eq(Collections.singletonList("id-1"))); + } + + private QueryResponse createAndInitEmptySolrQueryReponseMock() { + + SolrDocumentList sdl = Mockito.mock(SolrDocumentList.class); + Mockito.when(sdl.isEmpty()).thenReturn(true); + QueryResponse response = Mockito.mock(QueryResponse.class); + Mockito.when(response.getResults()).thenReturn(sdl); + Mockito.when(sdl.getNumFound()).thenReturn(0L); - verify(solrClientMock, times(1)).query(any(), any(SolrParams.class), eq(SolrRequest.METHOD.PUT)); + return response; } static class DocumentWithIndexAnnotations { diff --git a/src/test/java/org/springframework/data/solr/core/convert/CustomConversionsTests.java b/src/test/java/org/springframework/data/solr/core/convert/CustomConversionsTests.java new file mode 100644 index 0000000..f985c15 --- /dev/null +++ b/src/test/java/org/springframework/data/solr/core/convert/CustomConversionsTests.java @@ -0,0 +1,93 @@ +/* + * Copyright 2012 - 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.solr.core.convert; + +import java.util.Arrays; +import java.util.Date; +import java.util.Locale; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; +import org.springframework.util.NumberUtils; + +/** + * @author Christoph Strobl + */ +public class CustomConversionsTests { + + private CustomConversions conversions; + + @Test + public void testFindReadingConverter() { + conversions = new CustomConversions(Arrays.asList(StringToNumberConverter.INSTANCE)); + Assert.assertTrue(conversions.hasCustomReadTarget(String.class, Number.class)); + Assert.assertFalse(conversions.hasCustomReadTarget(Date.class, Number.class)); + } + + @Test + public void testFindWritingConverter() { + conversions = new CustomConversions(Arrays.asList(NumberToStringConverter.INSTANCE)); + Assert.assertTrue(conversions.hasCustomWriteTarget(Number.class, String.class)); + Assert.assertFalse(conversions.hasCustomWriteTarget(Date.class, String.class)); + } + + @Test + public void testFindReadWriteConverter() { + conversions = new CustomConversions(Arrays.asList(StringToLocaleConverter.INSTANCE)); + Assert.assertTrue(conversions.hasCustomReadTarget(String.class, Locale.class)); + Assert.assertTrue(conversions.hasCustomWriteTarget(String.class, Locale.class)); + } + + @Test + public void testFindMostRecentConverter() { + conversions = new CustomConversions(Arrays.asList(NumberToStringConverter.INSTANCE)); + Assert.assertThat(conversions.getCustomWriteTarget(Number.class), + Matchers.is(Matchers.typeCompatibleWith(String.class))); + } + + @WritingConverter + enum NumberToStringConverter implements Converter { + INSTANCE; + + public String convert(Number source) { + return source.toString(); + } + } + + @ReadingConverter + enum StringToNumberConverter implements Converter { + INSTANCE; + + public Number convert(String source) { + return NumberUtils.parseNumber(source, Integer.class); + } + } + + enum StringToLocaleConverter implements Converter { + INSTANCE; + + @Override + public Locale convert(String source) { + return Locale.GERMAN; + } + + } + +} diff --git a/src/test/java/org/springframework/data/solr/core/convert/DateTimeConvertersTests.java b/src/test/java/org/springframework/data/solr/core/convert/DateTimeConvertersTests.java index 236a9aa..9b47ad1 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/DateTimeConvertersTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/DateTimeConvertersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -30,9 +30,9 @@ */ public class DateTimeConvertersTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testJodaDateTimeConverterWithNullValue() { - DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null)); } @Test @@ -49,24 +49,24 @@ public void testStringToJodaDateTime() { Assert.assertThat(dateTime, IsEqual.equalTo(new DateTime(2013, 6, 18, 6, 0, 0, DateTimeZone.UTC))); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDateToJodaDateTimeConverterWithNull() { - DateTimeConverters.DateToJodaDateTimeConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.DateToJodaDateTimeConverter.INSTANCE.convert(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDateToJodaLocalDateTimeConverter() { - DateTimeConverters.DateToLocalDateTimeConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.DateToLocalDateTimeConverter.INSTANCE.convert(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testStringToJodaDateTimeWithNullValue() { - DateTimeConverters.StringToJodaDateTimeConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.StringToJodaDateTimeConverter.INSTANCE.convert(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testJodaLocalDateTimeConverterWithNullValue() { - DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null)); } @Test @@ -77,9 +77,9 @@ public void testJodaLocalDateTimeConverter() { DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testJavaDateConverterWithNullValue() { - DateTimeConverters.JavaDateConverter.INSTANCE.convert(null); + Assert.assertNull(DateTimeConverters.JavaDateConverter.INSTANCE.convert(null)); } @Test diff --git a/src/test/java/org/springframework/data/solr/core/convert/GeoConverterTests.java b/src/test/java/org/springframework/data/solr/core/convert/GeoConverterTests.java index ab6549b..b291c40 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/GeoConverterTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/GeoConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * 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. @@ -36,9 +36,9 @@ public class GeoConverterTests { public static class DistanceConverterTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testConvertDistanceToStringWithNull() { - GeoConverters.DistanceToStringConverter.INSTANCE.convert(null); + Assert.assertNull(GeoConverters.DistanceToStringConverter.INSTANCE.convert(null)); } @Test @@ -52,18 +52,17 @@ public void testConvertMilesDistanceToString() { GeoConverters.DistanceToStringConverter.INSTANCE.convert(new Distance(1, Metrics.MILES))); } - @Test // DATASOLR-31, DATASOLR-408 - public void testConvertDistanceWithNeutralUnitToString() { - Assert.assertEquals("1.0", - GeoConverters.DistanceToStringConverter.INSTANCE.convert(new Distance(1, Metrics.NEUTRAL))); + @Test + public void testConvertDistanceWithNullUnitToString() { + Assert.assertEquals("1.0", GeoConverters.DistanceToStringConverter.INSTANCE.convert(new Distance(1, null))); } } public static class PointConverterTests { - @Test(expected = IllegalArgumentException.class) + @Test public void testConvertPointToStringWithNull() { - GeoConverters.Point3DToStringConverter.INSTANCE.convert(null); + Assert.assertNull(GeoConverters.Point3DToStringConverter.INSTANCE.convert(null)); } @Test diff --git a/src/test/java/org/springframework/data/solr/core/convert/ITestMappingSolrConverter.java b/src/test/java/org/springframework/data/solr/core/convert/ITestMappingSolrConverter.java index b7c2422..3db779b 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/ITestMappingSolrConverter.java +++ b/src/test/java/org/springframework/data/solr/core/convert/ITestMappingSolrConverter.java @@ -15,42 +15,34 @@ */ package org.springframework.data.solr.core.convert; -import static org.hamcrest.collection.IsIterableWithSize.*; import static org.hamcrest.core.IsEqual.*; import static org.junit.Assert.*; -import lombok.Data; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import javax.xml.parsers.ParserConfigurationException; -import org.apache.solr.client.solrj.SolrQuery; -import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.beans.Field; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.data.annotation.Id; import org.springframework.data.geo.Point; import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer; import org.springframework.data.solr.core.SolrTemplate; -import org.springframework.data.solr.core.mapping.ChildDocument; import org.springframework.data.solr.core.mapping.Dynamic; import org.springframework.data.solr.core.mapping.Indexed; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.Query; -import org.springframework.data.solr.core.query.SimpleField; import org.springframework.data.solr.core.query.SimpleQuery; import org.springframework.data.solr.core.query.SimpleStringCriteria; import org.springframework.data.solr.core.query.result.ScoredPage; @@ -70,14 +62,14 @@ public class ITestMappingSolrConverter extends AbstractITestWithEmbeddedSolrServ @Before public void setUp() throws IOException, ParserConfigurationException, SAXException { - solrTemplate = new SolrTemplate(server); + solrTemplate = new SolrTemplate(server, "collection1"); solrTemplate.afterPropertiesSet(); } @After public void tearDown() { - solrTemplate.delete(COLLECTION_NAME, ALL_DOCUMENTS_QUERY); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.delete(ALL_DOCUMENTS_QUERY); + solrTemplate.commit(); } @Test // DATASOLR-142 @@ -150,123 +142,76 @@ public void testProcessesEnumCorrectly() { Query query = new SimpleQuery(new Criteria("enumProperty_s").is(LiteralNumberEnum.TWO)); - BeanWithEnum loadedViaProperty = solrTemplate.queryForObject(COLLECTION_NAME, query, BeanWithEnum.class).get(); + BeanWithEnum loadedViaProperty = solrTemplate.queryForObject(query, BeanWithEnum.class); assertEquals(bean.id, loadedViaProperty.id); assertEquals(bean.enumProperty, loadedViaProperty.enumProperty); } - @Test // DATASOLR-210, DATASOLR-309 + @Test // DATASOLR-210 public void testProcessesScoreCorrectly() { - Collection beans = new ArrayList<>(); + Collection beans = new ArrayList(); beans.add(new BeanWithScore("1", "spring")); beans.add(new BeanWithScore("2", "spring data solr")); beans.add(new BeanWithScore("3", "apache solr")); beans.add(new BeanWithScore("4", "apache lucene")); - solrTemplate.saveBeans(COLLECTION_NAME, beans); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(beans); + solrTemplate.commit(); - ScoredPage page = solrTemplate.queryForPage(COLLECTION_NAME, - new SimpleQuery("description:spring solr"), BeanWithScore.class); + ScoredPage page = solrTemplate.queryForPage(new SimpleQuery("description:spring solr"), + BeanWithScore.class); List content = page.getContent(); assertEquals(3, page.getTotalElements()); - - assertNotNull(content.get(0).score); + assertEquals(Float.valueOf(0.9105287f), content.get(0).score); assertEquals("spring data solr", content.get(0).description); - assertNotNull(content.get(1).score); + assertEquals(Float.valueOf(0.45526436f), content.get(1).score); assertEquals("spring", content.get(1).description); - assertNotNull(content.get(2).score); + assertEquals(Float.valueOf(0.28454024f), content.get(2).score); assertEquals("apache solr", content.get(2).description); } @Test // DATASOLR-202 public void testDynamicMap() { - Map map = new HashMap<>(); + Map map = new HashMap(); map.put("key_1", "value 1"); map.put("key_2", "value 2"); BeanWithDynamicMap bean = new BeanWithDynamicMap("bean-id", map); - solrTemplate.saveBean(COLLECTION_NAME, bean); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(bean); + solrTemplate.commit(); - BeanWithDynamicMap loaded = solrTemplate.getById(COLLECTION_NAME, "bean-id", BeanWithDynamicMap.class).get(); - assertEquals("value 1", loaded.values.get("key_1")); - assertEquals("value 2", loaded.values.get("key_2")); + BeanWithDynamicMap loaded = solrTemplate.getById("bean-id", BeanWithDynamicMap.class); + Assert.assertEquals("value 1", loaded.values.get("key_1")); + Assert.assertEquals("value 2", loaded.values.get("key_2")); } @Test // DATASOLR-308 public void testDynamicMapList() { - Map> map = new HashMap<>(); + Map> map = new HashMap>(); map.put("key_1", Arrays.asList("value 11", "value 12")); map.put("key_2", Arrays.asList("value 21", "value 22")); BeanWithDynamicMapList bean = new BeanWithDynamicMapList("bean-id", map); - solrTemplate.saveBean(COLLECTION_NAME, bean); - solrTemplate.commit(COLLECTION_NAME); - - BeanWithDynamicMapList loaded = solrTemplate.getById(COLLECTION_NAME, "bean-id", BeanWithDynamicMapList.class) - .get(); - assertEquals(Arrays.asList("value 11", "value 12"), loaded.values.get("key_1")); - assertEquals(Arrays.asList("value 21", "value 22"), loaded.values.get("key_2")); + solrTemplate.saveBean(bean); + solrTemplate.commit(); - } + BeanWithDynamicMapList loaded = solrTemplate.getById("bean-id", BeanWithDynamicMapList.class); + Assert.assertEquals(Arrays.asList("value 11", "value 12"), loaded.values.get("key_1")); + Assert.assertEquals(Arrays.asList("value 21", "value 22"), loaded.values.get("key_2")); - @Test // DATASOLR-394 - public void writeAndReadDocumentWithNestedChildObjectsCorrectly() throws IOException, SolrServerException { - - Book theWayOfKings = new Book(); - theWayOfKings.id = "book1"; - theWayOfKings.type = "book"; - theWayOfKings.title = "The Way of Kings"; - theWayOfKings.author = "Brandon Sanderson"; - theWayOfKings.category = "fantasy"; - theWayOfKings.publicationYear = 2010; - theWayOfKings.publisher = "Tor"; - theWayOfKings.reviews = new ArrayList<>(); - - BookReview review1 = new BookReview(); - review1.id = "review1"; - review1.type = "review"; - review1.author = "yonik"; - review1.date = new Date(); - review1.stars = 5; - review1.comment = "A great start to what looks like an epic series!"; - theWayOfKings.reviews.add(review1); - - BookReview review2 = new BookReview(); - review2.id = "review2"; - review2.type = "review"; - review2.author = "dan"; - review2.date = new Date(); - review2.stars = 3; - review2.comment = "This book was too long."; - theWayOfKings.reviews.add(review2); - - solrTemplate.saveBean(COLLECTION_NAME, theWayOfKings); - solrTemplate.commit(COLLECTION_NAME); - - assertThat(solrTemplate.getSolrClient().query(new SolrQuery("*:*")).getResults(), iterableWithSize(3)); - - Query query = new SimpleQuery(); - query.addCriteria(Criteria.where("id").is(theWayOfKings.id)); - query.addProjectionOnField(new SimpleField("*")); - query.addProjectionOnField(new SimpleField("[child parentFilter=type_s:book]")); - - Optional result = solrTemplate.queryForObject(COLLECTION_NAME, query, Book.class); - assertThat(result.orElse(null), equalTo(theWayOfKings)); } @SuppressWarnings("unchecked") private T saveAndLoad(T o) { - solrTemplate.saveBean(COLLECTION_NAME, o); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(o); + solrTemplate.commit(); - return (T) solrTemplate.queryForObject(COLLECTION_NAME, DEFAULT_BEAN_OBJECT_QUERY, o.getClass()).orElse(null); + return (T) solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, o.getClass()); } private static class BeanWithPoint { @@ -327,7 +272,7 @@ private static class BeanWithBaseClass extends BeanBaseClass { } private enum LiteralNumberEnum { - ONE, TWO, THREE + ONE, TWO, THREE; } private static class BeanWithEnum { @@ -383,29 +328,4 @@ public BeanWithDynamicMapList(String id, Map> values) { } - @Data - static class Book { - - @Id String id; - @Indexed("type_s") String type; - @Indexed("title_t") String title; - @Indexed("author_s") String author; - @Indexed("cat_s") String category; - @Indexed("pubyear_i") int publicationYear; - @Indexed("publisher_s") String publisher; - - @ChildDocument List reviews; - } - - @Data - static class BookReview { - - String id; - @Indexed("type_s") String type; - @Indexed("review_dt") Date date; - @Indexed("stars_i") int stars; - @Indexed("author_s") String author; - @Indexed("comment_t") String comment; - } - } diff --git a/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConvertDocumentObjectBinderCompatibilityTests.java b/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConvertDocumentObjectBinderCompatibilityTests.java index eb50b83..244aec4 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConvertDocumentObjectBinderCompatibilityTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConvertDocumentObjectBinderCompatibilityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.convert; -import static org.junit.Assert.*; - import java.io.StringReader; import java.util.Arrays; import java.util.Collection; @@ -33,7 +31,9 @@ import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.apache.solr.common.util.NamedList; +import org.hamcrest.core.IsInstanceOf; import org.junit.Assert; +import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -59,7 +59,7 @@ public MappingSolrConvertDocumentObjectBinderCompatibilityTests(SolrConverter co this.converter = converter; } - @Parameters(name = "{0}") + @Parameters public static Collection data() { Object[][] data = new Object[][] { { new SolrJConverter() }, { new MappingSolrConverter(new SimpleSolrMappingContext()) } }; @@ -75,8 +75,8 @@ public void testSimple() throws Exception { SolrDocumentList solDocList = res.getResults(); List l = getBeans(solDocList); - assertEquals(solDocList.size(), l.size()); - assertEquals(solDocList.get(0).getFieldValue("features"), l.get(0).features); + Assert.assertEquals(solDocList.size(), l.size()); + Assert.assertEquals(solDocList.get(0).getFieldValue("features"), l.get(0).features); Item item = new Item(); item.id = "aaa"; @@ -84,14 +84,14 @@ public void testSimple() throws Exception { SolrInputDocument out = new SolrInputDocument(); converter.write(item, out); - assertEquals(item.id, out.getFieldValue("id")); + Assert.assertEquals(item.id, out.getFieldValue("id")); SolrInputField catfield = out.getField("cat"); - assertEquals(3, catfield.getValueCount()); + Assert.assertEquals(3, catfield.getValueCount()); List catValues = (List) catfield.getValue(); - assertEquals("aaa", catValues.get(0)); - assertEquals("bbb", catValues.get(1)); - assertEquals("ccc", catValues.get(2)); + Assert.assertEquals("aaa", catValues.get(0)); + Assert.assertEquals("bbb", catValues.get(1)); + Assert.assertEquals("ccc", catValues.get(2)); } @Test @@ -99,7 +99,7 @@ public void testSingleVal4Array() { SolrDocument d = new SolrDocument(); d.setField("cat", "hello"); Item item = converter.read(Item.class, d); - assertEquals("hello", item.categories[0]); + Assert.assertEquals("hello", item.categories[0]); } @Test @@ -115,19 +115,18 @@ public void testDynamicFieldBinding() { Assert.assertArrayEquals(new String[] { "Mobile Store", "iPod Store", "CCTV Store" }, item.getAllSuppliers()); Assert.assertTrue(item.supplier.containsKey("supplier_1")); Assert.assertTrue(item.supplier.containsKey("supplier_2")); - assertEquals(2, item.supplier.size()); + Assert.assertEquals(2, item.supplier.size()); List supplierOne = item.supplier.get("supplier_1"); - assertEquals("Mobile Store", supplierOne.get(0)); - assertEquals("iPod Store", supplierOne.get(1)); + Assert.assertEquals("Mobile Store", supplierOne.get(0)); + Assert.assertEquals("iPod Store", supplierOne.get(1)); List supplierTwo = item.supplier.get("supplier_2"); - assertEquals("CCTV Store", supplierTwo.get(0)); + Assert.assertEquals("CCTV Store", supplierTwo.get(0)); } - @Test // DATASOLR-87, DATASOLR-309 + @Test public void testToAndFromSolrDocument() { - Item item = new Item(); item.id = "one"; item.inStock = false; @@ -135,11 +134,11 @@ public void testToAndFromSolrDocument() { item.features = Arrays.asList(item.categories); List supA = Arrays.asList("supA1", "supA2", "supA3"); List supB = Arrays.asList("supB1", "supB2", "supB3"); - item.supplier = new HashMap<>(); + item.supplier = new HashMap>(); item.supplier.put("supplier_supA", supA); item.supplier.put("supplier_supB", supB); - item.supplier_simple = new HashMap<>(); + item.supplier_simple = new HashMap(); item.supplier_simple.put("sup_simple_supA", "supA_val"); item.supplier_simple.put("sup_simple_supB", "supB_val"); @@ -152,13 +151,13 @@ public void testToAndFromSolrDocument() { Item out = converter.read(Item.class, docs.get(0)); // make sure it came out the same - assertEquals(item.id, out.id); - assertEquals(item.inStock, out.inStock); - assertEquals(item.categories.length, out.categories.length); - assertEquals(item.features, out.features); - assertEquals(supA, out.supplier.get("supplier_supA")); - assertEquals(supB, out.supplier.get("supplier_supB")); - assertEquals(item.supplier_simple.get("sup_simple_supB"), out.supplier_simple.get("sup_simple_supB")); + Assert.assertEquals(item.id, out.id); + Assert.assertEquals(item.inStock, out.inStock); + Assert.assertEquals(item.categories.length, out.categories.length); + Assert.assertEquals(item.features, out.features); + Assert.assertEquals(supA, out.supplier.get("supplier_supA")); + Assert.assertEquals(supB, out.supplier.get("supplier_supB")); + Assert.assertEquals(item.supplier_simple.get("sup_simple_supB"), out.supplier_simple.get("sup_simple_supB")); // put back "out" as Bean, to see if both ways work as you would expect // but the Field that "allSuppliers" need to be cleared, as it is just for @@ -171,24 +170,22 @@ public void testToAndFromSolrDocument() { docs1.add(toSolrDocument(doc1)); Item out1 = converter.read(Item.class, docs1.get(0)); - assertEquals(item.id, out1.id); - assertEquals(item.inStock, out1.inStock); - assertEquals(item.categories.length, out1.categories.length); - assertEquals(item.features, out1.features); + Assert.assertEquals(item.id, out1.id); + Assert.assertEquals(item.inStock, out1.inStock); + Assert.assertEquals(item.categories.length, out1.categories.length); + Assert.assertEquals(item.features, out1.features); - assertEquals(item.supplier_simple.get("sup_simple_supB"), out1.supplier_simple.get("sup_simple_supB")); + Assert.assertEquals(item.supplier_simple.get("sup_simple_supB"), out1.supplier_simple.get("sup_simple_supB")); - assertEquals(supA, out1.supplier.get("supplier_supA")); - assertEquals(supB, out1.supplier.get("supplier_supB")); - } - - private List getBeans(SolrDocumentList solDocList) { - return converter.read(solDocList, Item.class); + Assert.assertEquals(supA, out1.supplier.get("supplier_supA")); + Assert.assertEquals(supB, out1.supplier.get("supplier_supB")); } @Test // DATASOLR-394 public void testChild() throws Exception { + Assume.assumeThat("Needs to be SolrJConverter", converter, IsInstanceOf.instanceOf(SolrJConverter.class)); + SingleValueChild in = new SingleValueChild(); in.id = "1"; in.child = new Child(); @@ -199,14 +196,14 @@ public void testChild() throws Exception { new SolrJConverter().write(in, solrInputDoc); SolrDocument solrDoc = toSolrDocument(solrInputDoc); - assertEquals(1, solrInputDoc.getChildDocuments().size()); - assertEquals(1, solrDoc.getChildDocuments().size()); + Assert.assertEquals(1, solrInputDoc.getChildDocuments().size()); + Assert.assertEquals(1, solrDoc.getChildDocuments().size()); SingleValueChild out = converter.read(SingleValueChild.class, toSolrDocument(solrInputDoc)); - assertEquals(in.id, out.id); - assertEquals(in.child.id, out.child.id); - assertEquals(in.child.name, out.child.name); + Assert.assertEquals(in.id, out.id); + Assert.assertEquals(in.child.id, out.child.id); + Assert.assertEquals(in.child.name, out.child.name); ListChild listIn = new ListChild(); listIn.id = "2"; @@ -220,16 +217,16 @@ public void testChild() throws Exception { solrDoc = toSolrDocument(solrInputDoc); - assertEquals(2, solrInputDoc.getChildDocuments().size()); - assertEquals(2, solrDoc.getChildDocuments().size()); + Assert.assertEquals(2, solrInputDoc.getChildDocuments().size()); + Assert.assertEquals(2, solrDoc.getChildDocuments().size()); ListChild listOut = converter.read(ListChild.class, toSolrDocument(solrInputDoc)); - assertEquals(listIn.id, listOut.id); - assertEquals(listIn.child.get(0).id, listOut.child.get(0).id); - assertEquals(listIn.child.get(0).name, listOut.child.get(0).name); - assertEquals(listIn.child.get(1).id, listOut.child.get(1).id); - assertEquals(listIn.child.get(1).name, listOut.child.get(1).name); + Assert.assertEquals(listIn.id, listOut.id); + Assert.assertEquals(listIn.child.get(0).id, listOut.child.get(0).id); + Assert.assertEquals(listIn.child.get(0).name, listOut.child.get(0).name); + Assert.assertEquals(listIn.child.get(1).id, listOut.child.get(1).id); + Assert.assertEquals(listIn.child.get(1).name, listOut.child.get(1).name); ArrayChild arrIn = new ArrayChild(); arrIn.id = "3"; @@ -240,17 +237,16 @@ public void testChild() throws Exception { solrDoc = toSolrDocument(solrInputDoc); - assertEquals(2, solrInputDoc.getChildDocuments().size()); - assertEquals(2, solrDoc.getChildDocuments().size()); + Assert.assertEquals(2, solrInputDoc.getChildDocuments().size()); + Assert.assertEquals(2, solrDoc.getChildDocuments().size()); ArrayChild arrOut = converter.read(ArrayChild.class, solrDoc); - assertEquals(arrIn.id, arrOut.id); - assertEquals(arrIn.child[0].id, arrOut.child[0].id); - assertEquals(arrIn.child[0].name, arrOut.child[0].name); - assertEquals(arrIn.child[1].id, arrOut.child[1].id); - assertEquals(arrIn.child[1].name, arrOut.child[1].name); - + Assert.assertEquals(arrIn.id, arrOut.id); + Assert.assertEquals(arrIn.child[0].id, arrOut.child[0].id); + Assert.assertEquals(arrIn.child[0].name, arrOut.child[0].name); + Assert.assertEquals(arrIn.child[1].id, arrOut.child[1].id); + Assert.assertEquals(arrIn.child[1].name, arrOut.child[1].name); } public static class Child { @@ -297,6 +293,10 @@ private static SolrDocument toSolrDocument(SolrInputDocument d) { return doc; } + private List getBeans(SolrDocumentList solDocList) { + return converter.read(solDocList, Item.class); + } + public static class Item { @Field String id; @@ -344,10 +344,10 @@ public boolean isInStock() { } public static class NotGettableItem { - @Field // + @Field// String id; - @SuppressWarnings("unused") // + @SuppressWarnings("unused")// private boolean inStock; private String aaa; @@ -367,7 +367,8 @@ public void setAaa(String aaa) { } } - public static final String xml = "\n" + "" + public static final String xml = "\n" + + "" + "000*:*\n" + "2.24" + "electronicshard drive7200RPM, 8MB cache, IDE Ultra ATA-133" diff --git a/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConverterTests.java b/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConverterTests.java index 2f72d43..8f55e8e 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConverterTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/MappingSolrConverterTests.java @@ -18,7 +18,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; @@ -28,6 +27,7 @@ import org.apache.solr.client.solrj.beans.Field; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; +import org.apache.solr.common.SolrInputField; import org.hamcrest.Matchers; import org.hamcrest.collection.IsArrayContainingInAnyOrder; import org.hamcrest.collection.IsCollectionWithSize; @@ -172,7 +172,7 @@ public void testWriteWithFieldsExcludedFromIndexing() { @Test public void testWriteMappedProperty() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", "value_1"); values.put("key_2", "value_2"); @@ -188,8 +188,8 @@ public void testWriteMappedProperty() { @Test public void testWriteMappedListProperty() { - Map> values = new HashMap<>(2); - values.put("key_1", Collections.singletonList("value_1")); + Map> values = new HashMap>(2); + values.put("key_1", Arrays.asList("value_1")); values.put("key_2", Arrays.asList("value_2", "value_3")); BeanWithWildcards bean = new BeanWithWildcards(); @@ -204,7 +204,7 @@ public void testWriteMappedListProperty() { @Test public void testWriteMappedArrayProperty() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", new String[] { "value_1" }); values.put("key_2", new String[] { "value_2", "value_3" }); @@ -239,7 +239,7 @@ public void testWriteSingeValuedFieldWithTrailingWildcard() { @Test(expected = IllegalArgumentException.class) public void testWriteListWithLeadingWildcard() { BeanWithWildcards bean = new BeanWithWildcards(); - bean.listFieldWithLeadingWildcard = Collections.singletonList("leading_1"); + bean.listFieldWithLeadingWildcard = Arrays.asList("leading_1"); SolrInputDocument solrDocument = new SolrInputDocument(); converter.write(bean, solrDocument); @@ -257,7 +257,7 @@ public void testWriteArrayWithLeadingWildcard() { @Test(expected = IllegalArgumentException.class) public void testWriteListWithTrailingWildcard() { BeanWithWildcards bean = new BeanWithWildcards(); - bean.listFieldWithTrailingWildcard = Collections.singletonList("trailing_1"); + bean.listFieldWithTrailingWildcard = Arrays.asList("trailing_1"); SolrInputDocument solrDocument = new SolrInputDocument(); converter.write(bean, solrDocument); @@ -275,7 +275,7 @@ public void testWriteArrayWithTailingWildcard() { @Test(expected = IllegalArgumentException.class) public void testWriteListWithWildcard() { BeanWithWildcards bean = new BeanWithWildcards(); - bean.listFieldWithLeadingWildcard = Collections.singletonList("leading_1"); + bean.listFieldWithLeadingWildcard = Arrays.asList("leading_1"); bean.arrayFieldWithLeadingWildcard = new String[] { "leading_2" }; SolrInputDocument solrDocument = new SolrInputDocument(); @@ -320,14 +320,16 @@ public void testWriteUpdate() { Assert.assertEquals(1995, ((Map) solrDocument.getFieldValue("since")).get("set")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testWriteNullToSolrInputDocumentColletion() { - converter.write(null); + Collection result = converter.write((Iterable) null); + Assert.assertNotNull(result); + Assert.assertThat(result, IsEmptyCollection.empty()); } @Test public void testWriteEmptyCollectionToSolrInputDocumentColletion() { - Collection result = converter.write(new ArrayList<>()); + Collection result = converter.write(new ArrayList()); Assert.assertNotNull(result); Assert.assertThat(result, IsEmptyCollection.empty()); } @@ -614,8 +616,7 @@ public void testReadMultivaluedFieldWithLeadingWildcardToListInMap() { Assert.assertEquals(2, target.multivaluedFieldMapWithLeadingWildcardList.size()); Assert.assertThat(target.multivaluedFieldMapWithLeadingWildcardList, Matchers.allOf( - Matchers.hasEntry("1_multivaluedFieldMapWithLeadingWildcard", - Collections.singletonList("leading-map-value-1")), + Matchers.hasEntry("1_multivaluedFieldMapWithLeadingWildcard", Arrays.asList("leading-map-value-1")), Matchers.hasEntry("2_multivaluedFieldMapWithLeadingWildcard", Arrays.asList("leading-map-value-2", "leading-map-value-3")))); } @@ -647,8 +648,7 @@ public void testReadMultivaluedFieldWithTrailingWildcardToListInMap() { Assert.assertEquals(2, target.multivaluedFieldMapWithTrailingWildcardArray.size()); Assert.assertThat(target.multivaluedFieldMapWithTrailingWildcardList, Matchers.allOf( - Matchers.hasEntry("multivaluedFieldMapWithTrailingWildcard_1", - Collections.singletonList("trailing-map-value-1")), + Matchers.hasEntry("multivaluedFieldMapWithTrailingWildcard_1", Arrays.asList("trailing-map-value-1")), Matchers.hasEntry("multivaluedFieldMapWithTrailingWildcard_2", Arrays.asList("trailing-map-value-2", "trailing-map-value-3")))); } @@ -656,7 +656,7 @@ public void testReadMultivaluedFieldWithTrailingWildcardToListInMap() { @Test // DATASOLR-202 public void testWriteDynamicMappedPropertyWithLeadingWildcard() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", "value_1"); values.put("key_2", "value_2"); @@ -675,8 +675,8 @@ public void testWriteDynamicMappedPropertyWithLeadingWildcard() { @Test // DATASOLR-202 public void testWriteDynamicMappedListPropertyWithLeadingWildcard() { - Map> values = new HashMap<>(2); - values.put("key_1", Collections.singletonList("value_1")); + Map> values = new HashMap>(2); + values.put("key_1", Arrays.asList("value_1")); values.put("key_2", Arrays.asList("value_2", "value_3")); BeanWithDynamicMapsWildcards bean = new BeanWithDynamicMapsWildcards(); @@ -696,7 +696,7 @@ public void testWriteDynamicMappedListPropertyWithLeadingWildcard() { @Test // DATASOLR-202 public void testWriteDynamicMappedArrayPropertyWithLeadingWildcard() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", new String[] { "value_1" }); values.put("key_2", new String[] { "value_2", "value_3" }); @@ -717,7 +717,7 @@ public void testWriteDynamicMappedArrayPropertyWithLeadingWildcard() { @Test // DATASOLR-308 public void testWriteDynamicMappedPropertyWithTrailingWildcard() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", "value_1"); values.put("key_2", "value_2"); @@ -736,8 +736,8 @@ public void testWriteDynamicMappedPropertyWithTrailingWildcard() { @Test // DATASOLR-308 public void testWriteDynamicMappedListPropertyWithTrailingWildcard() { - Map> values = new HashMap<>(2); - values.put("key_1", Collections.singletonList("value_1")); + Map> values = new HashMap>(2); + values.put("key_1", Arrays.asList("value_1")); values.put("key_2", Arrays.asList("value_2", "value_3")); BeanWithDynamicMapsWildcards bean = new BeanWithDynamicMapsWildcards(); @@ -757,7 +757,7 @@ public void testWriteDynamicMappedListPropertyWithTrailingWildcard() { @Test // DATASOLR-308 public void testWriteDynamicMappedArrayPropertyWithTrailingWildcard() { - Map values = new HashMap<>(2); + Map values = new HashMap(2); values.put("key_1", new String[] { "value_1" }); values.put("key_2", new String[] { "value_2", "value_3" }); @@ -846,7 +846,7 @@ public void testReadMultivaluedFieldWithLeadingWildcardToListInDynamicMap() { Assert.assertEquals(2, target.multivaluedFieldMapWithLeadingWildcardList.size()); Assert.assertThat(target.multivaluedFieldMapWithLeadingWildcardList, - Matchers.allOf(Matchers.hasEntry("1", Collections.singletonList("leading-map-value-1")), + Matchers.allOf(Matchers.hasEntry("1", Arrays.asList("leading-map-value-1")), Matchers.hasEntry("2", Arrays.asList("leading-map-value-2", "leading-map-value-3")))); } @@ -878,7 +878,7 @@ public void testReadMultivaluedFieldWithTrailingWildcardToListInDynamicMap() { Assert.assertEquals(2, target.multivaluedFieldMapWithTrailingWildcardArray.size()); Assert.assertThat(target.multivaluedFieldMapWithTrailingWildcardList, - Matchers.allOf(Matchers.hasEntry("1", Collections.singletonList("trailing-map-value-1")), + Matchers.allOf(Matchers.hasEntry("1", Arrays.asList("trailing-map-value-1")), Matchers.hasEntry("2", Arrays.asList("trailing-map-value-2", "trailing-map-value-3")))); } @@ -1012,7 +1012,7 @@ public void testRegularFieldBoosting() { bean.boostedRegularField = "value"; bean.regularField = "value"; - SolrInputDocument target = new SolrInputDocument(); + Map target = new HashMap(); converter.write(bean, target); // configured boost @@ -1026,15 +1026,15 @@ public void testMapWildcardFieldBoosting() { BeanWithBoost bean = new BeanWithBoost(); - bean.boostedMapWildcardField = new HashMap<>(); + bean.boostedMapWildcardField = new HashMap(); bean.boostedMapWildcardField.put("val1_boostedMapWildcardField", "value"); bean.boostedMapWildcardField.put("val2_boostedMapWildcardField", "value"); - bean.mapWildcardField = new HashMap<>(); + bean.mapWildcardField = new HashMap(); bean.mapWildcardField.put("val1_mapWildcardField", "value"); bean.mapWildcardField.put("val2_mapWildcardField", "value"); - SolrInputDocument target = new SolrInputDocument(); + Map target = new HashMap(); converter.write(bean, target); // configured boost @@ -1068,7 +1068,7 @@ public void writeEnumValues() { SolrInputDocument sink = new SolrInputDocument(); converter.write(source, sink); - Assert.assertThat(sink.getFieldValue("enumProperty"), IsEqual.equalTo(SomeEnum.E2.name())); + Assert.assertThat(sink.getFieldValue("enumProperty"), IsEqual.equalTo((Object) SomeEnum.E2.name())); } @Test // DATASOLR-407 @@ -1080,7 +1080,7 @@ public void writeListOfEnumValues() { SolrInputDocument sink = new SolrInputDocument(); converter.write(source, sink); - Assert.assertThat(sink.getFieldValues("enumList"), IsIterableContainingInOrder.contains("E2", "E1")); + Assert.assertThat(sink.getFieldValues("enumList"), IsIterableContainingInOrder.contains("E2", "E1")); } @Test // DATASOLR-407 diff --git a/src/test/java/org/springframework/data/solr/core/convert/NumberConvertersTests.java b/src/test/java/org/springframework/data/solr/core/convert/NumberConvertersTests.java index 13bddd7..f37d185 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/NumberConvertersTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/NumberConvertersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. @@ -25,32 +25,32 @@ public class NumberConvertersTests { @Test public void testConvertPositiveLong() { - Assert.assertEquals("100", NumberConverters.NumberConverter.INSTANCE.convert(100l)); + Assert.assertEquals("100", NumberConverters.NumberConverter.INSTANCE.convert(Long.valueOf(100l))); } @Test public void testConvertNegativeLong() { - Assert.assertEquals("\\-100", NumberConverters.NumberConverter.INSTANCE.convert(-100l)); + Assert.assertEquals("\\-100", NumberConverters.NumberConverter.INSTANCE.convert(Long.valueOf(-100l))); } @Test public void testConvertPositiveInteger() { - Assert.assertEquals("100", NumberConverters.NumberConverter.INSTANCE.convert(100)); + Assert.assertEquals("100", NumberConverters.NumberConverter.INSTANCE.convert(Integer.valueOf(100))); } @Test public void testConvertNegativeInteger() { - Assert.assertEquals("\\-100", NumberConverters.NumberConverter.INSTANCE.convert(-100)); + Assert.assertEquals("\\-100", NumberConverters.NumberConverter.INSTANCE.convert(Integer.valueOf(-100))); } @Test public void testConvertPositiveFloat() { - Assert.assertEquals("100.0", NumberConverters.NumberConverter.INSTANCE.convert(100f)); + Assert.assertEquals("100.0", NumberConverters.NumberConverter.INSTANCE.convert(Float.valueOf(100))); } @Test public void testConvertNegativeFloat() { - Assert.assertEquals("\\-100.0", NumberConverters.NumberConverter.INSTANCE.convert((float) -100)); + Assert.assertEquals("\\-100.0", NumberConverters.NumberConverter.INSTANCE.convert(Float.valueOf(-100))); } @Test @@ -70,12 +70,12 @@ public void testConvertNegativeInfiniteFloat() { @Test public void testConvertPositiveDouble() { - Assert.assertEquals("100.0", NumberConverters.NumberConverter.INSTANCE.convert(100d)); + Assert.assertEquals("100.0", NumberConverters.NumberConverter.INSTANCE.convert(Double.valueOf(100))); } @Test public void testConvertNegativeDouble() { - Assert.assertEquals("\\-100.0", NumberConverters.NumberConverter.INSTANCE.convert((double) -100)); + Assert.assertEquals("\\-100.0", NumberConverters.NumberConverter.INSTANCE.convert(Double.valueOf(-100))); } @Test diff --git a/src/test/java/org/springframework/data/solr/core/convert/SolrJConverterTests.java b/src/test/java/org/springframework/data/solr/core/convert/SolrJConverterTests.java index 492ca5d..21c5ac5 100644 --- a/src/test/java/org/springframework/data/solr/core/convert/SolrJConverterTests.java +++ b/src/test/java/org/springframework/data/solr/core/convert/SolrJConverterTests.java @@ -68,7 +68,7 @@ public void testRead() { document.addField("stringProperty", "christoph"); document.addField("intProperty", 32); - ConvertableBean convertable = converter.read(ConvertableBean.class, document); + ConvertableBean convertable = converter.read(ConvertableBean.class, (Map) document); Assert.assertEquals(document.getFieldValue("stringProperty"), convertable.getStringProperty()); Assert.assertEquals(document.getFieldValue("intProperty"), convertable.getIntProperty()); diff --git a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntityTests.java b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntityTests.java index 6eea4bc..c41b6eb 100644 --- a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntityTests.java +++ b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentEntityTests.java @@ -18,6 +18,7 @@ import static org.hamcrest.core.Is.*; import static org.hamcrest.core.IsNull.*; import static org.junit.Assert.*; +import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import org.junit.Rule; @@ -25,8 +26,10 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.data.mapping.MappingException; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.annotation.Reference; +import org.springframework.data.mapping.PersistentEntity; +import org.springframework.data.mapping.model.MappingException; import org.springframework.data.solr.core.mapping.SimpleSolrPersistentPropertyTest.BeanWithScore; import org.springframework.data.solr.repository.Score; import org.springframework.data.util.TypeInformation; @@ -34,16 +37,15 @@ /** * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ -@RunWith(MockitoJUnitRunner.Silent.class) +@RunWith(MockitoJUnitRunner.class) public class SimpleSolrPersistentEntityTests { private static final String CORE_NAME = "core1"; public @Rule ExpectedException expectedException = ExpectedException.none(); - @SuppressWarnings("rawtypes") // + @SuppressWarnings("rawtypes")// @Mock TypeInformation typeInfo; @Mock SolrPersistentProperty property; @@ -54,9 +56,9 @@ public void testPersistentEntityWithSolrDocumentAnnotation() { when(typeInfo.getType()).thenReturn(SearchableBeanWithSolrDocumentAnnotation.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>( + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity( typeInfo); - assertEquals(CORE_NAME, pe.getCollectionName()); + assertEquals(CORE_NAME, pe.getSolrCoreName()); } @SuppressWarnings("unchecked") @@ -65,8 +67,8 @@ public void testPersistentEntityShouldReadSolrCoreNameFromParentClass() { when(typeInfo.getType()).thenReturn(InheritingClass.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>(typeInfo); - assertEquals(CORE_NAME, pe.getCollectionName()); + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity(typeInfo); + assertEquals(CORE_NAME, pe.getSolrCoreName()); } @SuppressWarnings("unchecked") @@ -75,9 +77,9 @@ public void testPersistentEntityWithoutSolrDocumentAnnotation() { when(typeInfo.getType()).thenReturn(SearchableBeanWithoutSolrDocumentAnnotation.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>( + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity( typeInfo); - assertEquals("searchablebeanwithoutsolrdocumentannotation", pe.getCollectionName()); + assertEquals("searchablebeanwithoutsolrdocumentannotation", pe.getSolrCoreName()); } @SuppressWarnings("unchecked") @@ -86,9 +88,9 @@ public void testPersistentEntityWithEmptySolrDocumentAnnotation() { when(typeInfo.getType()).thenReturn(SearchableBeanWithEmptySolrDocumentAnnotation.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>( + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity( typeInfo); - assertEquals("searchablebeanwithemptysolrdocumentannotation", pe.getCollectionName()); + assertEquals("searchablebeanwithemptysolrdocumentannotation", pe.getSolrCoreName()); } @SuppressWarnings("unchecked") @@ -97,7 +99,7 @@ public void testPersistentEntityShouldReadDocumentBoostFromSolrDocumentAnnotatio when(typeInfo.getType()).thenReturn(DocumentWithBoost.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>(typeInfo); + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity(typeInfo); assertThat(pe.isBoosted(), is(true)); assertThat(pe.getBoost(), is(100f)); } @@ -108,7 +110,7 @@ public void testPersistentEntityShouldNotBeBoostenWhenSolrDocumentAnnotationHasD when(typeInfo.getType()).thenReturn(SearchableBeanWithEmptySolrDocumentAnnotation.class); - SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity<>( + SimpleSolrPersistentEntity pe = new SimpleSolrPersistentEntity( typeInfo); assertThat(pe.isBoosted(), is(false)); assertThat(pe.getBoost(), nullValue()); @@ -123,7 +125,7 @@ public void testPersistentEntityWithScoreProperty() { when(property.isAnnotationPresent(eq(Score.class))).thenReturn(true); when(property.getFieldName()).thenReturn("myScoreProperty"); - SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity<>(typeInfo); + SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity(typeInfo); entity.addPersistentProperty(property); @@ -140,7 +142,7 @@ public void verifyShouldThrowExceptionWhenMoreThanOneScorePropertyDefined() { expectedException.expectMessage("Ambiguous score field mapping detected!"); when(typeInfo.getType()).thenReturn(DocumentWithScore.class); - SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity<>(typeInfo); + SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity(typeInfo); SolrPersistentProperty score = mock(SolrPersistentProperty.class); SolrPersistentProperty anotherScore = mock(SolrPersistentProperty.class); @@ -168,7 +170,7 @@ public void verifyShouldThrowExceptionWhenDynamicDefinedForNonMapPropety() { expectedException.expectMessage("Map"); when(typeInfo.getType()).thenReturn(SearchableBeanWithoutSolrDocumentAnnotation.class); - SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity<>(typeInfo); + SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity(typeInfo); SolrPersistentProperty property = mock(SolrPersistentProperty.class); @@ -193,7 +195,7 @@ public void verifyShouldThrowExceptionWhenDynamicDefinedForNonWildcardPropety() expectedException.expectMessage("wildcard"); when(typeInfo.getType()).thenReturn(SearchableBeanWithoutSolrDocumentAnnotation.class); - SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity<>(typeInfo); + SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity(typeInfo); SolrPersistentProperty property = mock(SolrPersistentProperty.class); @@ -209,6 +211,24 @@ public void verifyShouldThrowExceptionWhenDynamicDefinedForNonWildcardPropety() entity.verify(); } + @Test // DATASOLR-341 + public void verifyShouldNotFailOnAssociations() { + + when(typeInfo.getType()).thenReturn(DocumentWithAssociation.class); + SimpleSolrPersistentEntity entity = new SimpleSolrPersistentEntity(typeInfo); + + SolrPersistentProperty property = mock(SolrPersistentProperty.class); + + when(property.isDynamicProperty()).thenReturn(false); + when(property.isAnnotationPresent(eq(Reference.class))).thenReturn(true); + when(property.getName()).thenReturn("refDoc"); + when(property.getOwner()).thenReturn((PersistentEntity) entity); + + entity.addPersistentProperty(property); + + entity.verify(); + } + @SolrDocument(solrCoreName = CORE_NAME) static class SearchableBeanWithSolrDocumentAnnotation {} @@ -227,4 +247,9 @@ static class DocumentWithBoost {} static class DocumentWithScore {} + static class DocumentWithAssociation { + + @Reference DocumentWithScore refDoc; + } + } diff --git a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyBoostTests.java b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyBoostTests.java index 347ab4c..d4ba442 100644 --- a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyBoostTests.java +++ b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyBoostTests.java @@ -28,19 +28,17 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; -import org.springframework.data.mapping.model.Property; +import org.mockito.Mockito; import org.springframework.data.mapping.model.SimpleTypeHolder; -import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(Parameterized.class) public class SimpleSolrPersistentPropertyBoostTests { - @SuppressWarnings("rawtypes") // + @SuppressWarnings("rawtypes")// private TypeInformation typeInfoMock; private SimpleSolrPersistentEntity persistentEntity; @@ -51,9 +49,10 @@ public class SimpleSolrPersistentPropertyBoostTests { @SuppressWarnings("unchecked") @Before public void setUp() { + typeInfoMock = Mockito.mock(TypeInformation.class); - typeInfoMock = ClassTypeInformation.from(BeanWithSolrFieldAnnotation.class); - persistentEntity = new SimpleSolrPersistentEntity<>(typeInfoMock); + Mockito.when(typeInfoMock.getType()).thenReturn(BeanWithSolrFieldAnnotation.class); + persistentEntity = new SimpleSolrPersistentEntity(typeInfoMock); } @Parameters(name = "{index}: {0} should be boosted by {1}") @@ -71,23 +70,21 @@ public void testGetBoostShouldReflectAnnotatedValues() throws IntrospectionExcep private SimpleSolrPersistentProperty getPersistentProperty(Class clazz, String propertyName) throws IntrospectionException { - PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, clazz); java.lang.reflect.Field field = org.springframework.util.ReflectionUtils.findField(clazz, propertyName); - return new SimpleSolrPersistentProperty(Property.of(ClassTypeInformation.from(clazz), field, descriptor), - persistentEntity, SimpleTypeHolder.DEFAULT); + return new SimpleSolrPersistentProperty(field, descriptor, persistentEntity, new SimpleTypeHolder()); } static class BeanWithSolrFieldAnnotation { - @Indexed // + @Indexed// private String fieldWithEmptyBoostAnnotation; - @Indexed(boost = 100) // + @Indexed(boost = 100)// private String fieldWithBoostViaIndexedAnnotation; - @Indexed(boost = Float.NaN) // + @Indexed(boost = Float.NaN)// private String fieldWithInvalidBoostViaIndexedAnnotation; public String getFieldWithEmptyBoostAnnotation() { diff --git a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyTest.java b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyTest.java index 15e55b8..4f351d9 100644 --- a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyTest.java +++ b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersistentPropertyTest.java @@ -25,18 +25,16 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.annotation.Reference; import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.solr.repository.Score; -import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; /** * @author Francisco Spaeth * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) public class SimpleSolrPersistentPropertyTest { @@ -47,8 +45,8 @@ public class SimpleSolrPersistentPropertyTest { @Test // DATASOLR-210 @SuppressWarnings({ "unchecked", "rawtypes" }) - public void scoredPropertyShouldBeReadOnlyAndNotWritable() - throws NoSuchFieldException, SecurityException, IntrospectionException { + public void scoredPropertyShouldBeReadOnlyAndNotWritable() throws NoSuchFieldException, SecurityException, + IntrospectionException { Field field = BeanWithScore.class.getDeclaredField("myScoreProperty"); PropertyDescriptor propertyDescriptor = new PropertyDescriptor("myScoreProperty", BeanWithScore.class, null, null); @@ -57,21 +55,42 @@ public void scoredPropertyShouldBeReadOnlyAndNotWritable() when(owner.getTypeInformation()).thenReturn(typeInformation); when(typeInformation.getProperty("myScoreProperty")).thenReturn((TypeInformation) typeInformation); - SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty( - Property.of(ClassTypeInformation.from(BeanWithScore.class), field, propertyDescriptor), owner, + SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty(field, propertyDescriptor, owner, simpleTypeHolder); assertTrue(property.isScoreProperty()); assertFalse(property.isWritable()); } + @Test // DATASOLR-341 + public void propertyWithReferenceAnnotationShouldNotBeTreatedAsAssociation() throws NoSuchFieldException, IntrospectionException { + + Field field = BeanWithScore.class.getDeclaredField("reference"); + PropertyDescriptor propertyDescriptor = new PropertyDescriptor("reference", BeanWithScore.class, null, null); + + when(owner.getType()).thenReturn((Class) BeanWithScore.class); + when(owner.getTypeInformation()).thenReturn(typeInformation); + when(typeInformation.getProperty("reference")).thenReturn((TypeInformation) typeInformation); + + SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty(field, propertyDescriptor, owner, + simpleTypeHolder); + + assertFalse(property.isAssociation()); + } + static class BeanWithScore { @Score Float myScoreProperty; + @Reference BeanWithScore reference; public Float getMyScoreProperty() { return myScoreProperty; } + + public BeanWithScore getReference() { + return reference; + } + } } diff --git a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersitentPropertyFieldNameTests.java b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersitentPropertyFieldNameTests.java index 1e9ddf7..542b3cc 100644 --- a/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersitentPropertyFieldNameTests.java +++ b/src/test/java/org/springframework/data/solr/core/mapping/SimpleSolrPersitentPropertyFieldNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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. @@ -27,20 +27,18 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import org.springframework.data.mapping.model.Property; +import org.mockito.Mockito; import org.springframework.data.mapping.model.SimpleTypeHolder; -import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(Parameterized.class) public class SimpleSolrPersitentPropertyFieldNameTests { - @SuppressWarnings("rawtypes") // - private TypeInformation typeInformation; + @SuppressWarnings("rawtypes")// + private TypeInformation typeInfoMock; private SimpleSolrPersistentEntity persistentEntity; @@ -55,9 +53,10 @@ public SimpleSolrPersitentPropertyFieldNameTests(String propertyName, String exp @SuppressWarnings("unchecked") @Before public void setUp() { + typeInfoMock = Mockito.mock(TypeInformation.class); - typeInformation = ClassTypeInformation.from(BeanWithSolrFieldAnnotation.class); - persistentEntity = new SimpleSolrPersistentEntity<>(typeInformation); + Mockito.when(typeInfoMock.getType()).thenReturn(BeanWithSolrFieldAnnotation.class); + persistentEntity = new SimpleSolrPersistentEntity(typeInfoMock); } @Parameters @@ -80,26 +79,25 @@ private SimpleSolrPersistentProperty getPersistentProperty(Class clazz, Strin PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, clazz); java.lang.reflect.Field field = org.springframework.util.ReflectionUtils.findField(clazz, propertyName); - return new SimpleSolrPersistentProperty(Property.of(ClassTypeInformation.from(clazz), field, descriptor), - persistentEntity, SimpleTypeHolder.DEFAULT); + return new SimpleSolrPersistentProperty(field, descriptor, persistentEntity, new SimpleTypeHolder()); } static class BeanWithSolrFieldAnnotation { - @Field // + @Field// private String fieldWithSolrjFieldAnnotation; - @Field("solrj") // + @Field("solrj")// private String fieldWithSolrjFieldAnnotationAndValue; - @Indexed // + @Indexed// private String fieldWithIndexedAnnotation; - @Indexed("indexed") // + @Indexed("indexed")// private String fieldWithIndexedAnnotationAndValue; - @Field("solrj") // - @Indexed("indexed") // + @Field("solrj")// + @Indexed("indexed")// private String fieldWithBothAnnotations; public String getFieldWithSolrjFieldAnnotation() { diff --git a/src/test/java/org/springframework/data/solr/core/query/CriteriaTests.java b/src/test/java/org/springframework/data/solr/core/query/CriteriaTests.java index 56b8a07..e6bc0a2 100644 --- a/src/test/java/org/springframework/data/solr/core/query/CriteriaTests.java +++ b/src/test/java/org/springframework/data/solr/core/query/CriteriaTests.java @@ -18,7 +18,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -91,8 +90,8 @@ public void testIsWithNull() { Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -106,8 +105,8 @@ public void testIsNull() { Assert.assertTrue(criteria.isNegating()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -121,8 +120,8 @@ public void testIsNotNull() { Assert.assertFalse(criteria.isNegating()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test(expected = InvalidDataAccessApiUsageException.class) @@ -318,8 +317,8 @@ public void testBetween() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -329,8 +328,8 @@ public void testBetweenWithoutUpperBound() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -340,8 +339,8 @@ public void testBetweenWithoutLowerBound() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -351,8 +350,8 @@ public void testBetweenExcludingLowerBound() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertFalse((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertFalse(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -362,8 +361,8 @@ public void testBetweenExcludingUpperBound() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertFalse((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertFalse(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -373,8 +372,8 @@ public void testBetweenWithoutLowerAndUpperBound() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -384,8 +383,8 @@ public void testLessThan() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertFalse((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertFalse(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -395,8 +394,8 @@ public void testLessThanEqual() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertEquals(200, ((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -406,8 +405,8 @@ public void testLessThanEqualNull() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -417,8 +416,8 @@ public void testGreaterThan() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertFalse((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertFalse(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -428,8 +427,8 @@ public void testGreaterThanEqual() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertEquals(100, ((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @Test @@ -439,8 +438,8 @@ public void testGreaterThanEqualNull() { Assert.assertEquals(OperationKey.BETWEEN.getKey(), entry.getKey()); Assert.assertNull(((Object[]) entry.getValue())[0]); Assert.assertNull(((Object[]) entry.getValue())[1]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[2]); - Assert.assertTrue((Boolean) ((Object[]) entry.getValue())[3]); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[2]).booleanValue()); + Assert.assertTrue(((Boolean) ((Object[]) entry.getValue())[3]).booleanValue()); } @@ -459,9 +458,9 @@ public void testIn() { @Test public void testInWithNestedCollection() { - List> enclosingList = new ArrayList<>(); + List> enclosingList = new ArrayList>(); enclosingList.add(Arrays.asList("spring", "data")); - enclosingList.add(Collections.singletonList("solr")); + enclosingList.add(Arrays.asList("solr")); Criteria criteria = new Criteria("field_1").in(enclosingList); assertPredicate(criteria.getPredicates(), 0, OperationKey.EQUALS, "spring"); diff --git a/src/test/java/org/springframework/data/solr/core/query/FieldWithQueryParametersTests.java b/src/test/java/org/springframework/data/solr/core/query/FieldWithQueryParametersTests.java index da72f9a..be8acd9 100644 --- a/src/test/java/org/springframework/data/solr/core/query/FieldWithQueryParametersTests.java +++ b/src/test/java/org/springframework/data/solr/core/query/FieldWithQueryParametersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -41,7 +41,7 @@ public class FieldWithQueryParametersTests { @Before public void setUp() { - field = new FieldWithQueryParameters<>(FIELDNAME); + field = new FieldWithQueryParameters(FIELDNAME); } @Test(expected = IllegalArgumentException.class) @@ -94,8 +94,8 @@ public void testAddingMultipleQueryParameters() { field.addQueryParameter(OPTION_WITH_INT); field.addQueryParameter(OPTION_WITH_DATE); - Assert.assertThat(field.getQueryParameters(), - Matchers.contains(OPTION_WITH_STRING, OPTION_WITH_INT, OPTION_WITH_DATE)); + Assert + .assertThat(field.getQueryParameters(), Matchers.contains(OPTION_WITH_STRING, OPTION_WITH_INT, OPTION_WITH_DATE)); } @Test diff --git a/src/test/java/org/springframework/data/solr/core/query/ITestCriteriaExecution.java b/src/test/java/org/springframework/data/solr/core/query/ITestCriteriaExecution.java index f0ec166..51000a9 100644 --- a/src/test/java/org/springframework/data/solr/core/query/ITestCriteriaExecution.java +++ b/src/test/java/org/springframework/data/solr/core/query/ITestCriteriaExecution.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -15,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import static org.junit.Assert.*; - import java.io.IOException; import java.util.Arrays; import java.util.Calendar; @@ -27,6 +25,7 @@ import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -47,15 +46,14 @@ public class ITestCriteriaExecution extends AbstractITestWithEmbeddedSolrServer @Before public void setUp() throws IOException, ParserConfigurationException, SAXException { - solrTemplate = new SolrTemplate(server); + solrTemplate = new SolrTemplate(server, "collection1"); solrTemplate.afterPropertiesSet(); } @After public void tearDown() { - solrTemplate.delete(COLLECTION_NAME, - new SimpleQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD))); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.delete(new SimpleQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD))); + solrTemplate.commit(); } @Test @@ -66,13 +64,13 @@ public void testNegativeNumberCriteria() { ExampleSolrBean negativePopularity = createExampleBeanWithId("2"); negativePopularity.setPopularity(-200); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(positivePopularity, negativePopularity)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(positivePopularity, negativePopularity)); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, - new SimpleQuery(new Criteria("popularity").is(-200)), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); - assertEquals(negativePopularity.getId(), result.getContent().get(0).getId()); + Page result = solrTemplate.queryForPage(new SimpleQuery(new Criteria("popularity").is(-200)), + ExampleSolrBean.class); + Assert.assertEquals(1, result.getContent().size()); + Assert.assertEquals(negativePopularity.getId(), result.getContent().get(0).getId()); } @Test @@ -83,13 +81,13 @@ public void testNegativeNumberInRange() { ExampleSolrBean negative200 = createExampleBeanWithId("2"); negative200.setPopularity(-200); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(negative100, negative200)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(negative100, negative200)); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, - new SimpleQuery(new Criteria("popularity").between(-150, -50)), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); - assertEquals(negative100.getId(), result.getContent().get(0).getId()); + Page result = solrTemplate + .queryForPage(new SimpleQuery(new Criteria("popularity").between(-150, -50)), ExampleSolrBean.class); + Assert.assertEquals(1, result.getContent().size()); + Assert.assertEquals(negative100.getId(), result.getContent().get(0).getId()); } @Test @@ -99,12 +97,12 @@ public void testDateValue() { calendar.set(2012, 7, 23, 6, 10, 0); searchableBean.setLastModified(calendar.getTime()); - solrTemplate.saveBean(COLLECTION_NAME, searchableBean); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBean(searchableBean); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, - new SimpleQuery(new Criteria("last_modified").is(calendar.getTime())), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); + Page result = solrTemplate + .queryForPage(new SimpleQuery(new Criteria("last_modified").is(calendar.getTime())), ExampleSolrBean.class); + Assert.assertEquals(1, result.getContent().size()); } @Test @@ -119,14 +117,14 @@ public void testDateValueInRangeQuery() { calendar2011.set(2011, 7, 23, 6, 10, 0); searchableBeanIn2011.setLastModified(calendar2011.getTime()); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(searchableBeanIn2012, searchableBeanIn2011)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(searchableBeanIn2012, searchableBeanIn2011)); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, + Page result = solrTemplate.queryForPage( new SimpleQuery(new Criteria("last_modified").between(new DateTime(2012, 1, 1, 0, 0, 0, DateTimeZone.UTC), new DateTime(2012, 12, 31, 23, 59, 59, DateTimeZone.UTC))), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); + Assert.assertEquals(1, result.getContent().size()); } @@ -138,13 +136,13 @@ public void testPoint() { ExampleSolrBean searchableBeanInNYC = createExampleBeanWithId("2"); searchableBeanInNYC.setStore("40.7143,-74.006"); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(searchableBeanInBuffalow, searchableBeanInNYC)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(searchableBeanInBuffalow, searchableBeanInNYC)); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, + Page result = solrTemplate.queryForPage( new SimpleQuery(new Criteria("store").near(new Point(45.15, -93.85), new Distance(5))), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); + Assert.assertEquals(1, result.getContent().size()); } @Test @@ -155,13 +153,13 @@ public void testPointWithDistanceInMiles() { ExampleSolrBean searchableBeanInNYC = createExampleBeanWithId("2"); searchableBeanInNYC.setStore("40.7143,-74.006"); - solrTemplate.saveBeans(COLLECTION_NAME, Arrays.asList(searchableBeanInBuffalow, searchableBeanInNYC)); - solrTemplate.commit(COLLECTION_NAME); + solrTemplate.saveBeans(Arrays.asList(searchableBeanInBuffalow, searchableBeanInNYC)); + solrTemplate.commit(); - Page result = solrTemplate.queryForPage(COLLECTION_NAME, + Page result = solrTemplate.queryForPage( new SimpleQuery(new Criteria("store").near(new Point(45.15, -93.85), new Distance(3.106856, Metrics.MILES))), ExampleSolrBean.class); - assertEquals(1, result.getContent().size()); + Assert.assertEquals(1, result.getContent().size()); } } diff --git a/src/test/java/org/springframework/data/solr/core/query/SimpleQueryTests.java b/src/test/java/org/springframework/data/solr/core/query/SimpleQueryTests.java index 9b2097f..ce3f488 100644 --- a/src/test/java/org/springframework/data/solr/core/query/SimpleQueryTests.java +++ b/src/test/java/org/springframework/data/solr/core/query/SimpleQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,8 +15,6 @@ */ package org.springframework.data.solr.core.query; -import static org.hamcrest.CoreMatchers.*; - import java.util.List; import org.apache.commons.lang3.StringUtils; @@ -69,15 +67,15 @@ public void testAddProjectionNullFieldName() { @SuppressWarnings("rawtypes") @Test public void testAddProjection() { - Query query = new SimpleQuery().addProjectionOnField(new SimpleField("field_1")) - .addProjectionOnField(new SimpleField("field_2")); + Query query = new SimpleQuery().addProjectionOnField(new SimpleField("field_1")).addProjectionOnField( + new SimpleField("field_2")); Assert.assertEquals(2, ((List) query.getProjectionOnFields()).size()); } @Test public void testSetPageRequest() { SimpleQuery query = new SimpleQuery(); - Assert.assertThat(query.getPageRequest().isUnpaged(), is(true)); + Assert.assertNull(query.getPageRequest()); Assert.assertNull(query.getOffset()); Assert.assertNull(query.getRows()); @@ -85,7 +83,7 @@ public void testSetPageRequest() { query.setPageRequest(alteredPage); Assert.assertThat(query.getPageRequest(), IsEqual.equalTo(alteredPage)); - Assert.assertThat(query.getSort(), IsEqual.equalTo(Sort.unsorted())); + Assert.assertNull(query.getSort()); } @Test @@ -107,8 +105,8 @@ public void testSetPageRequestWithSort() { @Test public void testCreateQueryWithSortedPageRequest() { - SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("*:*"), - new PageRequest(0, 20, Sort.Direction.DESC, "value_1", "value_2")); + SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("*:*"), new PageRequest(0, 20, Sort.Direction.DESC, + "value_1", "value_2")); Assert.assertNotNull(query.getPageRequest()); Assert.assertNotNull(query.getSort()); @@ -156,8 +154,8 @@ public void testAddGroupByNullFieldName() { @SuppressWarnings("rawtypes") @Test public void testAddGroupBy() { - Query query = new SimpleQuery().addGroupByField(new SimpleField("field_1")) - .addGroupByField(new SimpleField("field_2")); + Query query = new SimpleQuery().addGroupByField(new SimpleField("field_1")).addGroupByField( + new SimpleField("field_2")); Assert.assertEquals(2, ((List) query.getGroupByFields()).size()); } @@ -237,7 +235,7 @@ public void testCloneWithDefaultOperator() { @Test public void testCloneWithTimeAllowed() { Query source = new SimpleQuery(new Criteria("field_1").is("value_1")); - source.setTimeAllowed(10); + source.setTimeAllowed(Integer.valueOf(10)); Query destination = SimpleQuery.fromQuery(source); Assert.assertEquals(source.getTimeAllowed(), destination.getTimeAllowed()); @@ -266,7 +264,7 @@ public void testAddNullSort() { Query query = new SimpleQuery(new Criteria("field_1").is("value_1")); query.addSort(null); - Assert.assertEquals(query.getSort(), Sort.unsorted()); + Assert.assertNull(query.getSort()); } @Test @@ -306,10 +304,10 @@ public void testTimeAllowed() { @Test public void shouldOverridePagableArgsByUsingExplicitSetters() { SimpleQuery query = new SimpleQuery("*:*").setPageRequest(new PageRequest(1, 10)); - query.setOffset(2L); + query.setOffset(2); query.setRows(20); - Assert.assertThat(query.getOffset(), Is.is(2L)); + Assert.assertThat(query.getOffset(), Is.is(2)); Assert.assertThat(query.getRows(), Is.is(20)); } } diff --git a/src/test/java/org/springframework/data/solr/core/query/result/DelegatingCursorUnitTests.java b/src/test/java/org/springframework/data/solr/core/query/result/DelegatingCursorUnitTests.java index c042109..10a2266 100644 --- a/src/test/java/org/springframework/data/solr/core/query/result/DelegatingCursorUnitTests.java +++ b/src/test/java/org/springframework/data/solr/core/query/result/DelegatingCursorUnitTests.java @@ -42,24 +42,24 @@ public class DelegatingCursorUnitTests { @Test(expected = InvalidDataAccessApiUsageException.class) // DATASOLR-162 public void shouldThrowExceptionWhenOpeningMultipleTimes() { - new DelegatingCursorFake<>(null).open().open(); + new DelegatingCursorFake(null).open().open(); } @Test // DATASOLR-162 public void shouldNotHaveNextWhenNoElementsAvailable() { - assertThat(new DelegatingCursorFake<>(null).open().hasNext(), is(false)); + assertThat(new DelegatingCursorFake(null).open().hasNext(), is(false)); } @Test(expected = NoSuchElementException.class) // DATASOLR-162 public void nextShouldThrowExceptionWhenNoMoreElementsAvailable() { - new DelegatingCursorFake<>(null).open().next(); + new DelegatingCursorFake(null).open().next(); } @Test // DATASOLR-162 public void shouldReturnElementsInValidOrder() { - PartialResult result = new PartialResult<>("*", Arrays.asList("spring", "data", "solr")); - DelegatingCursor cursor = new DelegatingCursorFake<>(Collections.singleton(result)).open(); + PartialResult result = new PartialResult("*", Arrays.asList("spring", "data", "solr")); + DelegatingCursor cursor = new DelegatingCursorFake(Collections.singleton(result)).open(); assertThat(cursor.next(), equalTo("spring")); assertThat(cursor.next(), equalTo("data")); @@ -69,8 +69,8 @@ public void shouldReturnElementsInValidOrder() { @Test // DATASOLR-162 public void shouldStopWhenNoMoreElementsAvailableAndAlreadyFinished() { - PartialResult result = new PartialResult<>("*", Arrays.asList("spring", "data", "solr")); - DelegatingCursor cursor = new DelegatingCursorFake<>(Collections.singleton(result)).open(); + PartialResult result = new PartialResult("*", Arrays.asList("spring", "data", "solr")); + DelegatingCursor cursor = new DelegatingCursorFake(Collections.singleton(result)).open(); cursor.next(); cursor.next(); @@ -81,11 +81,11 @@ public void shouldStopWhenNoMoreElementsAvailableAndAlreadyFinished() { @Test // DATASOLR-162 public void shouldFetchNextSetOfElementsWhenNotFinishedAndCurrentResultsEndReached() { - PartialResult result1 = new PartialResult<>("foo", Arrays.asList("spring", "data")); - PartialResult result2 = new PartialResult<>("foo", Collections.singletonList("solr")); + PartialResult result1 = new PartialResult("foo", Arrays.asList("spring", "data")); + PartialResult result2 = new PartialResult("foo", Arrays.asList("solr")); @SuppressWarnings("unchecked") - DelegatingCursor cursor = new DelegatingCursorFake<>(Arrays.asList(result1, result2)).open(); + DelegatingCursor cursor = new DelegatingCursorFake(Arrays.asList(result1, result2)).open(); assertThat(cursor.next(), equalTo("spring")); assertThat(cursor.next(), equalTo("data")); @@ -95,11 +95,11 @@ public void shouldFetchNextSetOfElementsWhenNotFinishedAndCurrentResultsEndReach @Test // DATASOLR-162 public void shouldDetermineEndOfResultsCorrectly() { - PartialResult result1 = new PartialResult<>("foo", Arrays.asList("spring", "data")); - PartialResult result2 = new PartialResult<>("foo", Collections.singletonList("solr")); + PartialResult result1 = new PartialResult("foo", Arrays.asList("spring", "data")); + PartialResult result2 = new PartialResult("foo", Arrays.asList("solr")); @SuppressWarnings("unchecked") - DelegatingCursor cursor = new DelegatingCursorFake<>(Arrays.asList(result1, result2)).open(); + DelegatingCursor cursor = new DelegatingCursorFake(Arrays.asList(result1, result2)).open(); cursor.next(); cursor.next(); @@ -110,12 +110,12 @@ public void shouldDetermineEndOfResultsCorrectly() { @Test // DATASOLR-162 public void shouldFinishLoopingWhenCursorMarkEqualsPreviousOne() { - PartialResult result1 = new PartialResult<>("foo", Collections.singletonList("spring")); - PartialResult result2 = new PartialResult<>("bar", Collections.singletonList("data")); - PartialResult result3 = new PartialResult<>("bar", Collections.singletonList("solr")); + PartialResult result1 = new PartialResult("foo", Arrays.asList("spring")); + PartialResult result2 = new PartialResult("bar", Arrays.asList("data")); + PartialResult result3 = new PartialResult("bar", Arrays.asList("solr")); @SuppressWarnings("unchecked") - DelegatingCursor cursor = new DelegatingCursorFake<>(Arrays.asList(result1, result2, result3)).open(); + DelegatingCursor cursor = new DelegatingCursorFake(Arrays.asList(result1, result2, result3)).open(); assertThat(cursor.hasNext(), is(true)); assertThat(cursor.isFinished(), is(false)); @@ -134,7 +134,7 @@ public void shouldFinishLoopingWhenCursorMarkEqualsPreviousOne() { public void shouldNotModifyInitialQueryWhenRequestingResults() { SolrQuery initialQuery = new SolrQuery("*:*"); - DelegatingCursorFake cursor = new DelegatingCursorFake<>(initialQuery, null); + DelegatingCursorFake cursor = new DelegatingCursorFake(initialQuery, null); cursor.open(); SolrQuery executedQuey = cursor.getLastUsedQuery(); @@ -148,7 +148,7 @@ public void shouldNotModifyInitialQueryWhenRequestingResults() { class DelegatingCursorFake extends DelegatingCursor { - List> values = new ArrayList<>(); + List> values = new ArrayList>(); private int requestCounter; private SolrQuery lastUsedQuery; diff --git a/src/test/java/org/springframework/data/solr/core/query/result/SimpleStatsResultTests.java b/src/test/java/org/springframework/data/solr/core/query/result/SimpleStatsResultTests.java index c623c80..d1bd655 100644 --- a/src/test/java/org/springframework/data/solr/core/query/result/SimpleStatsResultTests.java +++ b/src/test/java/org/springframework/data/solr/core/query/result/SimpleStatsResultTests.java @@ -72,32 +72,4 @@ public void testGetMaxDate() { Assert.assertEquals(date, stats.getMaxAsDate()); } - @Test // DATASOLR-404 - public void testMeanDate() { - - SimpleStatsResult stats = new SimpleStatsResult(); - Date date = new Date(); - stats.setMean(date); - - Assert.assertEquals(date, stats.getMeanAsDate()); - } - - @Test // DATASOLR-404 - public void testMeanNumber() { - - SimpleStatsResult stats = new SimpleStatsResult(); - Date date = new Date(); - stats.setMean(1L); - - Assert.assertEquals(1D, stats.getMeanAsDouble(), 0D); - } - - @Test // DATASOLR-404 - public void testMeanDateWhenNoDate() { - - SimpleStatsResult stats = new SimpleStatsResult(); - stats.setMean("o_O"); - - Assert.assertNull(stats.getMeanAsDate()); - } } diff --git a/src/test/java/org/springframework/data/solr/core/query/result/SolrGroupResultPageTest.java b/src/test/java/org/springframework/data/solr/core/query/result/SolrGroupResultPageTest.java index 8be94a6..790b88d 100644 --- a/src/test/java/org/springframework/data/solr/core/query/result/SolrGroupResultPageTest.java +++ b/src/test/java/org/springframework/data/solr/core/query/result/SolrGroupResultPageTest.java @@ -35,15 +35,15 @@ public class SolrGroupResultPageTest { @Test // DATASOLR-121 public void testGetGroupResultField() { @SuppressWarnings("unchecked") - GroupResult gr = new SimpleGroupResult<>(1, null, "name", Mockito.mock(Page.class)); + GroupResult gr = new SimpleGroupResult(1, null, "name", Mockito.mock(Page.class)); Field field = Mockito.mock(Field.class); Mockito.when(field.getName()).thenReturn("name"); - Map> groupResultMap = new HashMap<>(); + Map> groupResultMap = new HashMap>(); groupResultMap.put("name", gr); - SolrResultPage result = new SolrResultPage<>(Collections.emptyList()); + SolrResultPage result = new SolrResultPage(Collections.emptyList()); result.setGroupResults(groupResultMap); Assert.assertEquals(gr, result.getGroupResult(field)); @@ -52,14 +52,14 @@ public void testGetGroupResultField() { @Test // DATASOLR-121 public void testGetGroupResultFunction() { @SuppressWarnings("unchecked") - GroupResult gr = new SimpleGroupResult<>(1, null, "name", Mockito.mock(Page.class)); + GroupResult gr = new SimpleGroupResult(1, null, "name", Mockito.mock(Page.class)); Function func = Mockito.mock(Function.class); - Map> groupResultMap = new HashMap<>(); + Map> groupResultMap = new HashMap>(); groupResultMap.put(func, gr); - SolrResultPage result = new SolrResultPage<>(Collections.emptyList()); + SolrResultPage result = new SolrResultPage(Collections.emptyList()); result.setGroupResults(groupResultMap); Assert.assertEquals(gr, result.getGroupResult(func)); @@ -68,14 +68,14 @@ public void testGetGroupResultFunction() { @Test // DATASOLR-121 public void testGetGroupResultQuery() { @SuppressWarnings("unchecked") - GroupResult gr = new SimpleGroupResult<>(1, null, "name", Mockito.mock(Page.class)); + GroupResult gr = new SimpleGroupResult(1, null, "name", Mockito.mock(Page.class)); Query query = Mockito.mock(Query.class); - Map> groupResultMap = new HashMap<>(); + Map> groupResultMap = new HashMap>(); groupResultMap.put(query, gr); - SolrResultPage result = new SolrResultPage<>(Collections.emptyList()); + SolrResultPage result = new SolrResultPage(Collections.emptyList()); result.setGroupResults(groupResultMap); Assert.assertEquals(gr, result.getGroupResult(query)); @@ -84,12 +84,12 @@ public void testGetGroupResultQuery() { @Test // DATASOLR-121 public void testGetGroupResultString() { @SuppressWarnings("unchecked") - GroupResult gr = new SimpleGroupResult<>(1, null, "name", Mockito.mock(Page.class)); + GroupResult gr = new SimpleGroupResult(1, null, "name", Mockito.mock(Page.class)); - Map> groupResultMap = new HashMap<>(); + Map> groupResultMap = new HashMap>(); groupResultMap.put("name", gr); - SolrResultPage result = new SolrResultPage<>(Collections.emptyList()); + SolrResultPage result = new SolrResultPage(Collections.emptyList()); result.setGroupResults(groupResultMap); Assert.assertEquals(gr, result.getGroupResult("name")); @@ -97,7 +97,7 @@ public void testGetGroupResultString() { @Test // DATASOLR-121 public void testInexistentGroupResult() { - SolrResultPage result = new SolrResultPage<>(Collections.emptyList()); + SolrResultPage result = new SolrResultPage(Collections.emptyList()); Assert.assertNull(result.getGroupResult("name")); Assert.assertNull(result.getGroupResult(Mockito.mock(Query.class))); diff --git a/src/test/java/org/springframework/data/solr/core/schema/DefaultSchemaOperationsTests.java b/src/test/java/org/springframework/data/solr/core/schema/DefaultSchemaOperationsTests.java index 2585ab4..754c152 100644 --- a/src/test/java/org/springframework/data/solr/core/schema/DefaultSchemaOperationsTests.java +++ b/src/test/java/org/springframework/data/solr/core/schema/DefaultSchemaOperationsTests.java @@ -119,7 +119,7 @@ public void removesFieldCorrectly() { @Test // DATASOLR-313 public void readsSchemaVersionCorrectly() { - assertThat(schemaOps.getSchemaVersion(), is(closeTo(1.6D, 0.1D))); + assertThat(schemaOps.getSchemaVersion(), is(closeTo(1.5D, 0.0D))); } @Test(expected = SchemaModificationException.class) // DATASOLR-313 diff --git a/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaCreation.java b/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaCreation.java index c2e0d8e..3d6f6b4 100644 --- a/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaCreation.java +++ b/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaCreation.java @@ -61,11 +61,12 @@ public class ITestSolrSchemaCreation { public void setUp() { this.template = new SolrTemplate(resource); + this.template.setSolrCore(COLLECTION_NAME); template.setSchemaCreationFeatures(Collections.singletonList(Feature.CREATE_MISSING_FIELDS)); template.afterPropertiesSet(); - template.delete(COLLECTION_NAME, new SimpleQuery("*:*")); - template.commit(COLLECTION_NAME); + template.delete(new SimpleQuery("*:*")); + template.commit(); } @Test // DATASOLR-72, DATASOLR-313 @@ -73,46 +74,46 @@ public void beanShouldBeSavedCorrectly() throws SolrServerException, IOException Foo foo = new Foo(); foo.id = "1"; - template.saveBean(COLLECTION_NAME, foo); + template.saveBean(foo); Map> fields = requestSchemaFields(); // @Indexed String indexedStringWithoutType; - assertThat(fields.get("indexedStringWithoutType").get("type"), is(equalTo("string"))); - assertThat(fields.get("indexedStringWithoutType").get("multiValued"), is(false)); - assertThat(fields.get("indexedStringWithoutType").get("indexed"), is(true)); - assertThat(fields.get("indexedStringWithoutType").get("stored"), is(true)); - assertThat(fields.get("indexedStringWithoutType").get("required"), is(false)); + assertThat((String) fields.get("indexedStringWithoutType").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("indexed"), is(true)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("stored"), is(true)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("required"), is(false)); // @Indexed(name = "namedField", type = "string", searchable = false) - assertThat(fields.get("namedField").get("type"), is(equalTo("string"))); - assertThat(fields.get("namedField").get("multiValued"), is(false)); - assertThat(fields.get("namedField").get("indexed"), is(false)); - assertThat(fields.get("namedField").get("stored"), is(true)); - assertThat(fields.get("namedField").get("required"), is(false)); + assertThat((String) fields.get("namedField").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("namedField").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("namedField").get("indexed"), is(false)); + assertThat((Boolean) fields.get("namedField").get("stored"), is(true)); + assertThat((Boolean) fields.get("namedField").get("required"), is(false)); // @Indexed List listField; - assertThat(fields.get("listField").get("type"), is(equalTo("string"))); - assertThat(fields.get("listField").get("multiValued"), is(true)); - assertThat(fields.get("listField").get("indexed"), is(true)); - assertThat(fields.get("listField").get("stored"), is(true)); - assertThat(fields.get("listField").get("required"), is(false)); + assertThat((String) fields.get("listField").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("listField").get("multiValued"), is(true)); + assertThat((Boolean) fields.get("listField").get("indexed"), is(true)); + assertThat((Boolean) fields.get("listField").get("stored"), is(true)); + assertThat((Boolean) fields.get("listField").get("required"), is(false)); // @Indexed(type = "tdouble") Double someDoubleValue; - assertThat(fields.get("someDoubleValue").get("type"), is(equalTo("tdouble"))); - assertThat(fields.get("someDoubleValue").get("multiValued"), is(false)); - assertThat(fields.get("someDoubleValue").get("indexed"), is(true)); - assertThat(fields.get("someDoubleValue").get("stored"), is(true)); - assertThat(fields.get("someDoubleValue").get("required"), is(false)); + assertThat((String) fields.get("someDoubleValue").get("type"), is(equalTo("tdouble"))); + assertThat((Boolean) fields.get("someDoubleValue").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("someDoubleValue").get("indexed"), is(true)); + assertThat((Boolean) fields.get("someDoubleValue").get("stored"), is(true)); + assertThat((Boolean) fields.get("someDoubleValue").get("required"), is(false)); // @Indexed(name = "copySource", type = "string", copyTo = { "_text_" }) String aCopyFiled; - assertThat(fields.get("copySource").get("type"), is(equalTo("string"))); - assertThat(fields.get("copySource").get("multiValued"), is(false)); - assertThat(fields.get("copySource").get("indexed"), is(true)); - assertThat(fields.get("copySource").get("stored"), is(true)); - assertThat(fields.get("copySource").get("required"), is(false)); + assertThat((String) fields.get("copySource").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("copySource").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("copySource").get("indexed"), is(true)); + assertThat((Boolean) fields.get("copySource").get("stored"), is(true)); + assertThat((Boolean) fields.get("copySource").get("required"), is(false)); - Map hm = new HashMap<>(); + Map hm = new HashMap(); hm.put("source", "copySource"); hm.put("dest", "_text_"); @@ -122,7 +123,7 @@ public void beanShouldBeSavedCorrectly() throws SolrServerException, IOException @Test // DATASOLR-313 public void existingFieldsShouldNotBeTouched() throws SolrServerException, IOException, InterruptedException { - Map field = new LinkedHashMap<>(); + Map field = new LinkedHashMap(); field.put("name", "indexedStringWithoutType"); field.put("type", "string"); field.put("multiValued", true); @@ -133,37 +134,37 @@ public void existingFieldsShouldNotBeTouched() throws SolrServerException, IOExc Foo foo = new Foo(); foo.id = "1"; - template.saveBean(COLLECTION_NAME, foo); + template.saveBean(foo); Map> fields = requestSchemaFields(); // @Indexed String indexedStringWithoutType; - assertThat(fields.get("indexedStringWithoutType").get("type"), is(equalTo("string"))); - assertThat(fields.get("indexedStringWithoutType").get("multiValued"), is(true)); - assertThat(fields.get("indexedStringWithoutType").get("indexed"), is(false)); - assertThat(fields.get("indexedStringWithoutType").get("stored"), is(true)); - assertThat(fields.get("indexedStringWithoutType").get("required"), is(nullValue())); + assertThat((String) fields.get("indexedStringWithoutType").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("multiValued"), is(true)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("indexed"), is(false)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("stored"), is(true)); + assertThat((Boolean) fields.get("indexedStringWithoutType").get("required"), is(nullValue())); // @Indexed(name = "namedField", type = "string", searchable = false) - assertThat(fields.get("namedField").get("type"), is(equalTo("string"))); - assertThat(fields.get("namedField").get("multiValued"), is(false)); - assertThat(fields.get("namedField").get("indexed"), is(false)); - assertThat(fields.get("namedField").get("stored"), is(true)); - assertThat(fields.get("namedField").get("required"), is(false)); + assertThat((String) fields.get("namedField").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("namedField").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("namedField").get("indexed"), is(false)); + assertThat((Boolean) fields.get("namedField").get("stored"), is(true)); + assertThat((Boolean) fields.get("namedField").get("required"), is(false)); // @Indexed List listField; - assertThat(fields.get("listField").get("type"), is(equalTo("string"))); - assertThat(fields.get("listField").get("multiValued"), is(true)); - assertThat(fields.get("listField").get("indexed"), is(true)); - assertThat(fields.get("listField").get("stored"), is(true)); - assertThat(fields.get("listField").get("required"), is(false)); + assertThat((String) fields.get("listField").get("type"), is(equalTo("string"))); + assertThat((Boolean) fields.get("listField").get("multiValued"), is(true)); + assertThat((Boolean) fields.get("listField").get("indexed"), is(true)); + assertThat((Boolean) fields.get("listField").get("stored"), is(true)); + assertThat((Boolean) fields.get("listField").get("required"), is(false)); // @Indexed(type = "tdouble") Double someDoubleValue; - assertThat(fields.get("someDoubleValue").get("type"), is(equalTo("tdouble"))); - assertThat(fields.get("someDoubleValue").get("multiValued"), is(false)); - assertThat(fields.get("someDoubleValue").get("indexed"), is(true)); - assertThat(fields.get("someDoubleValue").get("stored"), is(true)); - assertThat(fields.get("someDoubleValue").get("required"), is(false)); + assertThat((String) fields.get("someDoubleValue").get("type"), is(equalTo("tdouble"))); + assertThat((Boolean) fields.get("someDoubleValue").get("multiValued"), is(false)); + assertThat((Boolean) fields.get("someDoubleValue").get("indexed"), is(true)); + assertThat((Boolean) fields.get("someDoubleValue").get("stored"), is(true)); + assertThat((Boolean) fields.get("someDoubleValue").get("required"), is(false)); } private Map> requestSchemaFields() throws SolrServerException, IOException { @@ -171,7 +172,7 @@ private Map> requestSchemaFields() throws SolrServer SchemaRepresentation schema = new SchemaRequest().process(resource.getSolrClient(COLLECTION_NAME), COLLECTION_NAME) .getSchemaRepresentation(); - Map> fields = new LinkedHashMap<>(); + Map> fields = new LinkedHashMap>(); for (Map field : schema.getFields()) { fields.put(field.get("name").toString(), field); diff --git a/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaWriter.java b/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaWriter.java index 71477eb..3fc64a8 100644 --- a/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaWriter.java +++ b/src/test/java/org/springframework/data/solr/core/schema/ITestSolrSchemaWriter.java @@ -15,13 +15,14 @@ */ package org.springframework.data.solr.core.schema; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.IsEqual.*; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.*; import java.util.Collections; import org.apache.solr.client.solrj.SolrClient; +import org.hamcrest.core.IsNull; import org.junit.Before; import org.junit.ClassRule; import org.junit.Ignore; @@ -31,6 +32,7 @@ import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.data.solr.server.support.HttpSolrClientFactory; import org.springframework.data.solr.test.util.EmbeddedSolrServer; +import org.springframework.util.Assert; /** * @author Christoph Strobl @@ -55,7 +57,7 @@ public void setUp() { public void getSchemaVersionShouldReturnVersionNumberCorrectly() { Double version = schemaWriter.retrieveSchemaVersion("collection1"); - assertThat(version, is(closeTo(1.6D, 0.1D))); + assertThat(version, equalTo(1.5D)); } @Test // DATASOLR-72 diff --git a/src/test/java/org/springframework/data/solr/core/schema/SolrSchmemaResolverUnitTests.java b/src/test/java/org/springframework/data/solr/core/schema/SolrSchmeaResolverUnitTests.java similarity index 99% rename from src/test/java/org/springframework/data/solr/core/schema/SolrSchmemaResolverUnitTests.java rename to src/test/java/org/springframework/data/solr/core/schema/SolrSchmeaResolverUnitTests.java index 9d4f233..0d3bb04 100644 --- a/src/test/java/org/springframework/data/solr/core/schema/SolrSchmemaResolverUnitTests.java +++ b/src/test/java/org/springframework/data/solr/core/schema/SolrSchmeaResolverUnitTests.java @@ -41,9 +41,8 @@ /** * @author Christoph Strobl - * @author Mark Paluch */ -public class SolrSchmemaResolverUnitTests { +public class SolrSchmeaResolverUnitTests { private SolrSchemaResolver schemaResolver; private MappingContext, SolrPersistentProperty> context; diff --git a/src/test/java/org/springframework/data/solr/repository/ExampleSolrBeanRepository.java b/src/test/java/org/springframework/data/solr/repository/ExampleSolrBeanRepository.java index c5a0e9b..038974b 100644 --- a/src/test/java/org/springframework/data/solr/repository/ExampleSolrBeanRepository.java +++ b/src/test/java/org/springframework/data/solr/repository/ExampleSolrBeanRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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. @@ -16,7 +16,6 @@ package org.springframework.data.solr.repository; import org.springframework.data.solr.ExampleSolrBean; -import org.springframework.data.solr.core.SolrOperations; import org.springframework.data.solr.repository.support.SimpleSolrRepository; /** @@ -24,7 +23,4 @@ */ public class ExampleSolrBeanRepository extends SimpleSolrRepository { - public ExampleSolrBeanRepository(SolrOperations solrOperations, Class entityClass) { - super(solrOperations, entityClass); - } } diff --git a/src/test/java/org/springframework/data/solr/repository/ITestSimpleSolrRepository.java b/src/test/java/org/springframework/data/solr/repository/ITestSimpleSolrRepository.java index 710ec5c..3d5281a 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestSimpleSolrRepository.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestSimpleSolrRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-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. @@ -35,11 +35,10 @@ public class ITestSimpleSolrRepository extends AbstractITestWithEmbeddedSolrServ @Before public void setUp() { - - SolrTemplate template = new SolrTemplate(server); + repository = new ExampleSolrBeanRepository(); + SolrTemplate template = new SolrTemplate(server, "collection1"); template.afterPropertiesSet(); - - repository = new ExampleSolrBeanRepository(template, ExampleSolrBean.class); + repository.setSolrOperations(template); } @Test @@ -49,31 +48,32 @@ public void testBeanLifecyle() { Assert.assertSame(toInsert, savedBean); - Assert.assertTrue(repository.existsById(savedBean.getId())); + Assert.assertTrue(repository.exists(savedBean.getId())); - ExampleSolrBean retrieved = repository.findById(savedBean.getId()).get(); + ExampleSolrBean retrieved = repository.findOne(savedBean.getId()); Assert.assertNotNull(retrieved); Assert.assertTrue(EqualsBuilder.reflectionEquals(savedBean, retrieved, new String[] { "version" })); Assert.assertEquals(1, repository.count()); - Assert.assertTrue(repository.existsById(savedBean.getId())); + Assert.assertTrue(repository.exists(savedBean.getId())); repository.delete(savedBean); Assert.assertEquals(0, repository.count()); - Assert.assertFalse(repository.findById(savedBean.getId()).isPresent()); + retrieved = repository.findOne(savedBean.getId()); + Assert.assertNull(retrieved); } @Test public void testListFunctions() { int objectCount = 100; - List toInsert = new ArrayList<>(objectCount); + List toInsert = new ArrayList(objectCount); for (int i = 0; i < 100; i++) { toInsert.add(createExampleBeanWithId(Integer.toString(i))); } - repository.saveAll(toInsert); + repository.save(toInsert); Assert.assertEquals(objectCount, repository.count()); diff --git a/src/test/java/org/springframework/data/solr/repository/ITestSolrRepositoryOperations.java b/src/test/java/org/springframework/data/solr/repository/ITestSolrRepositoryOperations.java index 82a0e01..18e3fc0 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestSolrRepositoryOperations.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestSolrRepositoryOperations.java @@ -15,18 +15,19 @@ */ package org.springframework.data.solr.repository; -import static org.hamcrest.collection.IsCollectionWithSize.*; -import static org.hamcrest.collection.IsIterableContainingInOrder.*; -import static org.junit.Assert.*; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Date; import java.util.List; import org.hamcrest.Matchers; +import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.collection.IsEmptyCollection; +import org.hamcrest.collection.IsIterableContainingInOrder; import org.hamcrest.core.Is; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; @@ -85,7 +86,7 @@ public class ITestSolrRepositoryOperations { @Before public void setUp() { repo.deleteAll(); - repo.saveAll( + repo.save( Arrays.asList(POPULAR_AVAILABLE_PRODUCT, UNPOPULAR_AVAILABLE_PRODUCT, UNAVAILABLE_PRODUCT, NAMED_PRODUCT)); } @@ -96,23 +97,23 @@ public void tearDown() { @Test public void testFindOne() { - ProductBean found = repo.findById(POPULAR_AVAILABLE_PRODUCT.getId()).get(); + ProductBean found = repo.findOne(POPULAR_AVAILABLE_PRODUCT.getId()); Assert.assertEquals(POPULAR_AVAILABLE_PRODUCT.getId(), found.getId()); } @Test public void testFindOneThatDoesNotExist() { - Assert.assertFalse(repo.findById(POPULAR_AVAILABLE_PRODUCT.getId().concat("XX-XX-XX")).isPresent()); + Assert.assertNull(repo.findOne(POPULAR_AVAILABLE_PRODUCT.getId().concat("XX-XX-XX"))); } @Test public void testExists() { - Assert.assertTrue(repo.existsById(POPULAR_AVAILABLE_PRODUCT.getId())); + Assert.assertTrue(repo.exists(POPULAR_AVAILABLE_PRODUCT.getId())); } @Test public void testExistsOneThatDoesNotExist() { - Assert.assertFalse(repo.existsById(POPULAR_AVAILABLE_PRODUCT.getId().concat("XX-XX-XX"))); + Assert.assertFalse(repo.exists(POPULAR_AVAILABLE_PRODUCT.getId().concat("XX-XX-XX"))); } @Test @@ -172,7 +173,7 @@ public void testFindByIsNotNull() { @Test public void testFindSingleElementByIs() { - ProductBean product = repo.findProductBeanById(POPULAR_AVAILABLE_PRODUCT.getId()); + ProductBean product = repo.findById(POPULAR_AVAILABLE_PRODUCT.getId()); Assert.assertNotNull(product); Assert.assertEquals(POPULAR_AVAILABLE_PRODUCT.getId(), product.getId()); } @@ -204,7 +205,7 @@ public void testFindByBefore() { ProductBean modifiedMid2011 = createProductBean("2011", 5, true); modifiedMid2011.setLastModified(new DateTime(2011, 6, 1, 0, 0, 0, DateTimeZone.UTC).toDate()); - repo.saveAll(Arrays.asList(modifiedMid2012, modifiedMid2011)); + repo.save(Arrays.asList(modifiedMid2012, modifiedMid2011)); List found = repo .findByLastModifiedBefore(new DateTime(2011, 12, 31, 23, 59, 59, DateTimeZone.UTC).toDate()); Assert.assertEquals(1, found.size()); @@ -233,7 +234,7 @@ public void testFindByAfter() { ProductBean modifiedMid2011 = createProductBean("2011", 5, true); modifiedMid2011.setLastModified(new DateTime(2011, 6, 1, 0, 0, 0, DateTimeZone.UTC).toDate()); - repo.saveAll(Arrays.asList(modifiedMid2012, modifiedMid2011)); + repo.save(Arrays.asList(modifiedMid2012, modifiedMid2011)); List found = repo .findByLastModifiedAfter(new DateTime(2012, 1, 1, 0, 0, 0, DateTimeZone.UTC).toDate()); Assert.assertEquals(1, found.size()); @@ -300,7 +301,7 @@ public void testFindByWithin() { ProductBean locatedInNYC = createProductBean("200", 5, true); locatedInNYC.setLocation("40.7143,-74.006"); - repo.saveAll(Arrays.asList(locatedInBuffalow, locatedInNYC)); + repo.save(Arrays.asList(locatedInBuffalow, locatedInNYC)); List found = repo.findByLocationWithin(new Point(45.15, -93.85), new Distance(5)); Assert.assertEquals(1, found.size()); @@ -315,7 +316,7 @@ public void testFindByNear() { ProductBean locatedInNYC = createProductBean("200", 5, true); locatedInNYC.setLocation("40.7143,-74.006"); - repo.saveAll(Arrays.asList(locatedInBuffalow, locatedInNYC)); + repo.save(Arrays.asList(locatedInBuffalow, locatedInNYC)); List found = repo.findByLocationNear(new Point(45.15, -93.85), new Distance(5)); Assert.assertEquals(1, found.size()); @@ -330,7 +331,7 @@ public void testFindByNearWithBox() { ProductBean locatedInNYC = createProductBean("200", 5, true); locatedInNYC.setLocation("40.7143,-74.006"); - repo.saveAll(Arrays.asList(locatedInBuffalow, locatedInNYC)); + repo.save(Arrays.asList(locatedInBuffalow, locatedInNYC)); List found = repo.findByLocationNear(new Box(new Point(45, -94), new Point(46, -93))); Assert.assertEquals(1, found.size()); @@ -341,11 +342,11 @@ public void testFindByNearWithBox() { public void testFindWithSortAsc() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); List found = repo.findByAvailableTrueOrderByPopularityAsc(); @@ -361,11 +362,11 @@ public void testFindWithSortAsc() { public void testFindWithSortDesc() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); List found = repo.findByAvailableTrueOrderByPopularityDesc(); @@ -381,11 +382,11 @@ public void testFindWithSortDesc() { public void testFindWithSortDescForAnnotatedQuery() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); List found = repo.findByAvailableWithAnnotatedQueryUsingSort(true, new Sort(Direction.DESC, "popularity")); @@ -402,11 +403,11 @@ public void testFindWithSortDescForAnnotatedQuery() { public void testFindWithSortDescInPageableForAnnotatedQuery() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); Page found = repo.findByAvailableWithAnnotatedQueryUsingSortInPageable(true, new PageRequest(0, 50, new Sort(Direction.DESC, "popularity"))); @@ -423,11 +424,11 @@ public void testFindWithSortDescInPageableForAnnotatedQuery() { public void testFindWithSortDescForNamedQuery() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); List found = repo.findByAvailableWithSort(true, new Sort(Direction.DESC, "popularity")); @@ -443,11 +444,11 @@ public void testFindWithSortDescForNamedQuery() { public void testFindWithSortDescInPageableForNamedQuery() { repo.deleteAll(); - List values = new ArrayList<>(); + List values = new ArrayList(); for (int i = 0; i < 10; i++) { values.add(createProductBean(Integer.toString(i), i, true)); } - repo.saveAll(values); + repo.save(values); Page found = repo.findByAvailableWithSort(true, new PageRequest(0, 30, new Sort(Direction.DESC, "popularity"))); @@ -753,7 +754,7 @@ public void testMultipleFilters() { @Test public void testDefaultAndOperator() { - List found = repo.findByAvailableIn(Collections.singletonList(Boolean.TRUE)); + List found = repo.findByAvailableIn(Arrays.asList(Boolean.TRUE)); Assert.assertEquals(3, found.size()); found = repo.findByAvailableIn(Arrays.asList(Boolean.TRUE, Boolean.FALSE)); @@ -762,7 +763,7 @@ public void testDefaultAndOperator() { @Test public void testDefaultOrOperator() { - List found = repo.findByAvailableInWithOrOperator(Collections.singletonList(Boolean.TRUE)); + List found = repo.findByAvailableInWithOrOperator(Arrays.asList(Boolean.TRUE)); Assert.assertEquals(3, found.size()); found = repo.findByAvailableInWithOrOperator(Arrays.asList(Boolean.TRUE, Boolean.FALSE)); @@ -779,12 +780,12 @@ public void testTimeAllowed() { public void testWithBoost() { repo.deleteAll(); ProductBean beanWithName = createProductBean("1", 5, true, "stackoverflow"); - beanWithName.setTitle(Collections.singletonList("indexoutofbounds")); + beanWithName.setTitle(Arrays.asList("indexoutofbounds")); ProductBean beanWithTitle = createProductBean("2", 5, true, "indexoutofbounds"); - beanWithTitle.setTitle(Collections.singletonList("stackoverflow")); + beanWithTitle.setTitle(Arrays.asList("stackoverflow")); - repo.saveAll(Arrays.asList(beanWithName, beanWithTitle)); + repo.save(Arrays.asList(beanWithName, beanWithTitle)); List found = repo.findByNameStartsWithOrTitleStartsWith("indexoutofbounds", "indexoutofbounds"); Assert.assertEquals(2, found.size()); @@ -913,7 +914,7 @@ public void testDereivedDeleteQueryRemovesDocumentsCorrectly() { long referenceCount = repo.count(); repo.deleteByName(NAMED_PRODUCT.getName()); - assertThat(repo.existsById(NAMED_PRODUCT.getId()), Is.is(false)); + assertThat(repo.exists(NAMED_PRODUCT.getId()), Is.is(false)); assertThat(repo.count(), Is.is(referenceCount - 1)); } @@ -922,7 +923,7 @@ public void testDerivedDeleteByQueryRemovesDocumentAndReturnsNumberDeletedCorrec long referenceCount = repo.count(); long nrDeleted = repo.deleteProductBeanByName(NAMED_PRODUCT.getName()); - assertThat(repo.existsById(NAMED_PRODUCT.getId()), Is.is(false)); + assertThat(repo.exists(NAMED_PRODUCT.getId()), Is.is(false)); assertThat(repo.count(), Is.is(referenceCount - nrDeleted)); } @@ -930,7 +931,7 @@ public void testDerivedDeleteByQueryRemovesDocumentAndReturnsNumberDeletedCorrec public void testDerivedDeleteByQueryRemovesDocumentAndReturnsListOfDeletedDocumentsCorrectly() { List result = repo.removeByName(NAMED_PRODUCT.getName()); - assertThat(repo.existsById(NAMED_PRODUCT.getId()), Is.is(false)); + assertThat(repo.exists(NAMED_PRODUCT.getId()), Is.is(false)); assertThat(result, hasSize(1)); assertThat(result.get(0).getId(), IsEqual.equalTo(NAMED_PRODUCT.getId())); } @@ -940,7 +941,7 @@ public void testAnnotatedDeleteByQueryRemovesDocumensCorrectly() { long referenceCount = repo.count(); repo.removeUsingAnnotatedQuery(NAMED_PRODUCT.getName()); - assertThat(repo.existsById(NAMED_PRODUCT.getId()), Is.is(false)); + assertThat(repo.exists(NAMED_PRODUCT.getId()), Is.is(false)); assertThat(repo.count(), Is.is(referenceCount - 1)); } @@ -955,7 +956,7 @@ public void findTopNResultAppliesLimitationCorrectly() { public void findTopNResultAppliesLimitationForPageableCorrectly() { List beans = createProductBeans(10, "top"); - repo.saveAll(beans); + repo.save(beans); Page result = repo.findTop3ByNameStartsWith("to", new PageRequest(0, 2)); assertThat(result.getNumberOfElements(), IsEqual.equalTo(2)); @@ -966,7 +967,7 @@ public void findTopNResultAppliesLimitationForPageableCorrectly() { public void findTopNResultAppliesLimitationForPageableCorrectlyForPage1() { List beans = createProductBeans(10, "top"); - repo.saveAll(beans); + repo.save(beans); Page result = repo.findTop3ByNameStartsWith("to", new PageRequest(1, 2)); assertThat(result.getNumberOfElements(), IsEqual.equalTo(1)); @@ -976,7 +977,7 @@ public void findTopNResultAppliesLimitationForPageableCorrectlyForPage1() { @Test // DATASOLR-170 public void findTopNResultReturnsEmptyListIfOusideOfRange() { - repo.saveAll(createProductBeans(10, "top")); + repo.save(createProductBeans(10, "top")); Page result = repo.findTop3ByNameStartsWith("to", new PageRequest(1, 5)); assertThat(result.getNumberOfElements(), IsEqual.equalTo(0)); @@ -986,7 +987,7 @@ public void findTopNResultReturnsEmptyListIfOusideOfRange() { @Test // DATASOLR-186 public void sliceShouldReturnCorrectly() { - repo.saveAll(createProductBeans(10, "slice")); + repo.save(createProductBeans(10, "slice")); Slice slice = repo.findProductBeanByName("slice", new PageRequest(0, 2)); assertThat(slice.getNumberOfElements(), Is.is(2)); @@ -995,7 +996,7 @@ public void sliceShouldReturnCorrectly() { @Test // DATASOLR-186 public void sliceShouldReturnAllElementsWhenPageableIsBigEnoughCorrectly() { - repo.saveAll(createProductBeans(10, "slice")); + repo.save(createProductBeans(10, "slice")); Slice slice = repo.findProductBeanByName("slice", new PageRequest(0, 20)); assertThat(slice.getNumberOfElements(), Is.is(10)); @@ -1004,7 +1005,7 @@ public void sliceShouldReturnAllElementsWhenPageableIsBigEnoughCorrectly() { @Test // DATASOLR-186 public void sliceShouldBeEmptyWhenPageableOutOfRange() { - repo.saveAll(createProductBeans(10, "slice")); + repo.save(createProductBeans(10, "slice")); Slice slice = repo.findProductBeanByName("slice", new PageRequest(1, 20)); assertThat(slice.hasContent(), Is.is(false)); @@ -1063,7 +1064,7 @@ public void derivedFinderUsingEnum() { ProductBean json = createProductBean("6", 3, true, "json"); json.setContentType(ContentType.JSON); - repo.saveAll(Arrays.asList(html, json)); + repo.save(Arrays.asList(html, json)); List result = repo.findByContentType(ContentType.HTML); assertThat(result, hasSize(1)); @@ -1072,7 +1073,7 @@ public void derivedFinderUsingEnum() { private static List createProductBeans(int nrToCreate, String prefix) { - List beans = new ArrayList<>(nrToCreate); + List beans = new ArrayList(nrToCreate); for (int i = 0; i < nrToCreate; i++) { String id = StringUtils.hasText(prefix) ? (prefix + "-" + i) : Integer.toString(i); beans.add(createProductBean(id, 0, true, id)); diff --git a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackFalse.java b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackFalse.java index 687ad83..380cf11 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackFalse.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackFalse.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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,10 +15,8 @@ */ package org.springframework.data.solr.repository; -import static org.mockito.ArgumentMatchers.eq; - import java.io.IOException; -import java.util.Collections; +import java.util.Arrays; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; @@ -26,21 +24,20 @@ import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("TransactionalSolrRepositoryTest-context.xml") -@Transactional(transactionManager = "transactionManager") -@Rollback(false) +@Transactional +@TransactionConfiguration(defaultRollback = false, transactionManager = "transactionManager") public class ITestTransactionalSolrRepositoryDeleteOperationRollbackFalse extends TransactionalIntegrationTestsBase { private static final String ID = "id-tansaction-committed"; @@ -56,13 +53,13 @@ public void resetMock() { @AfterTransaction public void checkIfDeleted() throws SolrServerException, IOException { - Mockito.verify(solrClientMock, Mockito.times(1)).commit(eq("collection1")); + Mockito.verify(solrClientMock, Mockito.times(1)).commit(); Mockito.verify(solrClientMock, Mockito.never()).rollback(); } @Test public void testDeleteById() { - repo.deleteById(ID); + repo.delete(ID); } @Test @@ -76,7 +73,7 @@ public void testDelete() { public void testDeleteMultipleObjects() { ProductBean bean = new ProductBean(); bean.setId(ID); - repo.deleteAll(Collections.singletonList(bean)); + repo.delete(Arrays.asList(bean)); } @Test diff --git a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackTrue.java b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackTrue.java index 0242146..a746d0c 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackTrue.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositoryDeleteOperationRollbackTrue.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -16,7 +16,7 @@ package org.springframework.data.solr.repository; import java.io.IOException; -import java.util.Collections; +import java.util.Arrays; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; @@ -28,15 +28,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("TransactionalSolrRepositoryTest-context.xml") -@Transactional(transactionManager = "transactionManager") +@Transactional +@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager") public class ITestTransactionalSolrRepositoryDeleteOperationRollbackTrue extends TransactionalIntegrationTestsBase { private static final String ID = "id-tansaction-rolled-back"; @@ -58,7 +59,7 @@ public void checkIfDeleted() throws SolrServerException, IOException { @Test public void testDeleteById() { - repo.deleteById(ID); + repo.delete(ID); } @Test @@ -72,7 +73,7 @@ public void testDelete() { public void testDeleteMultipleObjects() { ProductBean bean = new ProductBean(); bean.setId(ID); - repo.deleteAll(Collections.singletonList(bean)); + repo.delete(Arrays.asList(bean)); } @Test diff --git a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackFalse.java b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackFalse.java index 826931c..c5f308e 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackFalse.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackFalse.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -16,7 +16,7 @@ package org.springframework.data.solr.repository; import java.io.IOException; -import java.util.Collections; +import java.util.Arrays; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; @@ -24,21 +24,20 @@ import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("TransactionalSolrRepositoryTest-context.xml") -@Transactional(transactionManager = "transactionManager") -@Rollback(false) +@Transactional +@TransactionConfiguration(defaultRollback = false, transactionManager = "transactionManager") public class ITestTransactionalSolrRepositorySaveOperationRollbackFalse extends TransactionalIntegrationTestsBase { private static final String ID = "id-tansaction-committed"; @@ -54,7 +53,7 @@ public void resetMock() { @AfterTransaction public void checkIfSaved() throws SolrServerException, IOException { - Mockito.verify(solrClientMock, Mockito.times(1)).commit(Mockito.any()); + Mockito.verify(solrClientMock, Mockito.times(1)).commit(); Mockito.verify(solrClientMock, Mockito.never()).rollback(); } @@ -69,7 +68,7 @@ public void testSave() { public void testSaveMultipleObjects() { ProductBean bean = new ProductBean(); bean.setId(ID); - repo.saveAll(Collections.singletonList(bean)); + repo.save(Arrays.asList(bean)); } } diff --git a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackTrue.java b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackTrue.java index 8e8a240..824ece1 100644 --- a/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackTrue.java +++ b/src/test/java/org/springframework/data/solr/repository/ITestTransactionalSolrRepositorySaveOperationRollbackTrue.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2015 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. @@ -16,7 +16,7 @@ package org.springframework.data.solr.repository; import java.io.IOException; -import java.util.Collections; +import java.util.Arrays; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; @@ -28,15 +28,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author Christoph Strobl - * @author Mark Paluch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("TransactionalSolrRepositoryTest-context.xml") -@Transactional(transactionManager = "transactionManager") +@Transactional +@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionManager") public class ITestTransactionalSolrRepositorySaveOperationRollbackTrue extends TransactionalIntegrationTestsBase { private static final String ID = "id-tansaction-rolled-back"; @@ -67,7 +68,7 @@ public void testSave() { public void testSaveMultipleObjects() { ProductBean bean = new ProductBean(); bean.setId(ID); - repo.saveAll(Collections.singletonList(bean)); + repo.save(Arrays.asList(bean)); } } diff --git a/src/test/java/org/springframework/data/solr/repository/ProductBean.java b/src/test/java/org/springframework/data/solr/repository/ProductBean.java index 5967d45..63a1090 100644 --- a/src/test/java/org/springframework/data/solr/repository/ProductBean.java +++ b/src/test/java/org/springframework/data/solr/repository/ProductBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -20,37 +20,47 @@ import org.apache.solr.client.solrj.beans.Field; import org.springframework.data.annotation.Id; -import org.springframework.data.solr.core.mapping.SolrDocument; /** * @author Christoph Strobl */ -@SolrDocument(collection = "collection1") public class ProductBean { - @Id @Field("id") private String id; + @Id + @Field("id") + private String id; - @Field("title") private List title; + @Field("title") + private List title; - @Field("name") private String name; + @Field("name") + private String name; - @Field("description") private String description; + @Field("description") + private String description; private String text; - @Field private List categories; + @Field + private List categories; - @Field private Float weight; + @Field + private Float weight; - @Field private Float price; + @Field + private Float price; - @Field private Integer popularity; + @Field + private Integer popularity; - @Field("inStock") private boolean available; + @Field("inStock") + private boolean available; - @Field("store") private String location; + @Field("store") + private String location; - @Field("last_modified") private Date lastModified; + @Field("last_modified") + private Date lastModified; @Field("content_type_s") private ContentType contentType; diff --git a/src/test/java/org/springframework/data/solr/repository/ProductRepository.java b/src/test/java/org/springframework/data/solr/repository/ProductRepository.java index cc3eb01..2ff657d 100644 --- a/src/test/java/org/springframework/data/solr/repository/ProductRepository.java +++ b/src/test/java/org/springframework/data/solr/repository/ProductRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -57,7 +57,7 @@ public interface ProductRepository extends SolrCrudRepository findByNameIsNotNull(); - ProductBean findProductBeanById(String id); + ProductBean findById(String id); List findByAvailableTrue(); diff --git a/src/test/java/org/springframework/data/solr/repository/SimpleSolrRepositoryTests.java b/src/test/java/org/springframework/data/solr/repository/SimpleSolrRepositoryTests.java index 9cea8ca..c2f5b90 100644 --- a/src/test/java/org/springframework/data/solr/repository/SimpleSolrRepositoryTests.java +++ b/src/test/java/org/springframework/data/solr/repository/SimpleSolrRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 2014 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,8 +15,6 @@ */ package org.springframework.data.solr.repository; -import static org.hamcrest.CoreMatchers.*; - import java.util.Arrays; import org.apache.solr.client.solrj.beans.Field; @@ -28,7 +26,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.annotation.Id; import org.springframework.data.solr.ExampleSolrBean; import org.springframework.data.solr.core.SolrOperations; @@ -49,56 +47,56 @@ public class SimpleSolrRepositoryTests { @Before public void setUp() { - repository = new SimpleSolrRepository<>(solrOperationsMock, ExampleSolrBean.class); + repository = new SimpleSolrRepository(solrOperationsMock, ExampleSolrBean.class); } @Test(expected = IllegalArgumentException.class) public void testInitRepositoryWithNullSolrOperations() { - new SimpleSolrRepository(null, (Class) null); + new SimpleSolrRepository(null); } @Test(expected = IllegalArgumentException.class) public void testInitRepositoryWithNullEntityClass() { - new SimpleSolrRepository( - new SolrTemplate(new HttpSolrClient("http://localhost:8080/solr"), null), (Class) null); + new SimpleSolrRepository(new SolrTemplate( + new HttpSolrClient("http://localhost:8080/solr"), null), null); } @Test public void testInitRepository() { - repository = new SimpleSolrRepository<>(new SolrTemplate(new HttpSolrClient("http://localhost:8080/solr"), null), - ExampleSolrBean.class); + repository = new SimpleSolrRepository(new SolrTemplate(new HttpSolrClient( + "http://localhost:8080/solr"), null), ExampleSolrBean.class); Assert.assertEquals(ExampleSolrBean.class, repository.getEntityClass()); } @Test public void testFindAllByIdQuery() { - Mockito.when(solrOperationsMock.count(Mockito.any(), Mockito.any(SolrDataQuery.class))).thenReturn(12345l); + Mockito.when(solrOperationsMock.count(Mockito.any(SolrDataQuery.class))).thenReturn(12345l); - repository.findAllById(Arrays.asList("id-1", "id-2", "id-3")); + repository.findAll(Arrays.asList("id-1", "id-2", "id-3")); ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - Mockito.verify(solrOperationsMock, Mockito.times(1)).count(Mockito.any(), captor.capture()); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.any(), captor.capture(), + Mockito.verify(solrOperationsMock, Mockito.times(1)).count(captor.capture()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), Mockito.eq(ExampleSolrBean.class)); - Assert.assertThat(captor.getAllValues().get(0).getPageRequest().isUnpaged(), is(true)); + Assert.assertNull(captor.getAllValues().get(0).getPageRequest()); Assert.assertEquals(12345, captor.getAllValues().get(1).getPageRequest().getPageSize()); } @Test public void testFindAllByIdQueryForBeanWithLongIdType() { - Mockito.when(solrOperationsMock.count(Mockito.any(), Mockito.any(SolrDataQuery.class))).thenReturn(12345l); - SimpleSolrRepository repoWithNonStringIdType = new SimpleSolrRepository<>( + Mockito.when(solrOperationsMock.count(Mockito.any(SolrDataQuery.class))).thenReturn(12345l); + SimpleSolrRepository repoWithNonStringIdType = new SimpleSolrRepository( solrOperationsMock, BeanWithLongIdType.class); - repoWithNonStringIdType.findAllById(Arrays.asList(1L, 2L, 3L)); + repoWithNonStringIdType.findAll(Arrays.asList(1L, 2L, 3L)); ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - Mockito.verify(solrOperationsMock, Mockito.times(1)).count(Mockito.any(), captor.capture()); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.any(), captor.capture(), + Mockito.verify(solrOperationsMock, Mockito.times(1)).count(captor.capture()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), Mockito.eq(BeanWithLongIdType.class)); - Assert.assertThat(captor.getAllValues().get(0).getPageRequest().isUnpaged(), is(true)); + Assert.assertNull(captor.getAllValues().get(0).getPageRequest()); Assert.assertEquals(12345, captor.getAllValues().get(1).getPageRequest().getPageSize()); } diff --git a/src/test/java/org/springframework/data/solr/repository/cdi/CdiProductRepository.java b/src/test/java/org/springframework/data/solr/repository/cdi/CdiProductRepository.java index ada3a1e..58e36ed 100644 --- a/src/test/java/org/springframework/data/solr/repository/cdi/CdiProductRepository.java +++ b/src/test/java/org/springframework/data/solr/repository/cdi/CdiProductRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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,8 +15,6 @@ */ package org.springframework.data.solr.repository.cdi; -import java.util.Optional; - import org.springframework.data.solr.repository.ProductBean; import org.springframework.data.solr.repository.SolrCrudRepository; @@ -25,6 +23,6 @@ */ public interface CdiProductRepository extends SolrCrudRepository { - Optional findById(String id); + ProductBean findOne(String id); } diff --git a/src/test/java/org/springframework/data/solr/repository/cdi/ITestCdiRepository.java b/src/test/java/org/springframework/data/solr/repository/cdi/ITestCdiRepository.java index 2a2b9e1..2c8688e 100644 --- a/src/test/java/org/springframework/data/solr/repository/cdi/ITestCdiRepository.java +++ b/src/test/java/org/springframework/data/solr/repository/cdi/ITestCdiRepository.java @@ -18,17 +18,13 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; -import java.util.Optional; - -import javax.enterprise.inject.se.SeContainer; -import javax.enterprise.inject.se.SeContainerInitializer; - +import org.apache.webbeans.cditest.CdiTestContainer; +import org.apache.webbeans.cditest.CdiTestContainerLoader; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; - import org.springframework.data.solr.repository.ProductBean; /** @@ -37,35 +33,32 @@ */ public class ITestCdiRepository { - private static SeContainer cdiContainer; + private static CdiTestContainer cdiContainer; private CdiProductRepository repository; private SamplePersonRepository samplePersonRepository; @BeforeClass - public static void init() { - - cdiContainer = SeContainerInitializer.newInstance() // - .disableDiscovery() // - .addPackages(CdiRepositoryClient.class) // - .initialize(); + public static void init() throws Exception { + cdiContainer = CdiTestContainerLoader.getCdiContainer(); + cdiContainer.startApplicationScope(); + cdiContainer.bootContainer(); } @AfterClass - public static void shutdown() { - cdiContainer.close(); + public static void shutdown() throws Exception { + cdiContainer.stopContexts(); + cdiContainer.shutdownContainer(); } @Before public void setUp() { - - CdiRepositoryClient client = cdiContainer.select(CdiRepositoryClient.class).get(); + CdiRepositoryClient client = cdiContainer.getInstance(CdiRepositoryClient.class); repository = client.getRepository(); samplePersonRepository = client.getSamplePersonRepository(); } - @Test // DATASOLR-106 + @Test public void testCdiRepository() { - Assert.assertNotNull(repository); ProductBean bean = new ProductBean(); @@ -74,26 +67,28 @@ public void testCdiRepository() { repository.save(bean); - Assert.assertTrue(repository.existsById(bean.getId())); + Assert.assertTrue(repository.exists(bean.getId())); - Optional retrieved = repository.findById(bean.getId()); - Assert.assertTrue(retrieved.isPresent()); - Assert.assertEquals(bean.getId(), retrieved.get().getId()); - Assert.assertEquals(bean.getName(), retrieved.get().getName()); + ProductBean retrieved = repository.findOne(bean.getId()); + Assert.assertNotNull(retrieved); + Assert.assertEquals(bean.getId(), retrieved.getId()); + Assert.assertEquals(bean.getName(), retrieved.getName()); Assert.assertEquals(1, repository.count()); - Assert.assertTrue(repository.existsById(bean.getId())); + Assert.assertTrue(repository.exists(bean.getId())); repository.delete(bean); Assert.assertEquals(0, repository.count()); - retrieved = repository.findById(bean.getId()); - Assert.assertFalse(retrieved.isPresent()); + retrieved = repository.findOne(bean.getId()); + Assert.assertNull(retrieved); } @Test // DATASOLR-187 public void returnOneFromCustomImpl() { + assertThat(samplePersonRepository.returnOne(), is(1)); } + } diff --git a/src/test/java/org/springframework/data/solr/repository/cdi/SolrTemplateProducer.java b/src/test/java/org/springframework/data/solr/repository/cdi/SolrTemplateProducer.java index 6362475..fc4df61 100644 --- a/src/test/java/org/springframework/data/solr/repository/cdi/SolrTemplateProducer.java +++ b/src/test/java/org/springframework/data/solr/repository/cdi/SolrTemplateProducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-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. @@ -43,6 +43,7 @@ public SolrOperations createSolrTemplate() throws IOException, ParserConfigurati ResourceUtils.getURL("classpath:static-schema").getPath()); SolrTemplate template = new SolrTemplate(factory); + template.setSolrCore("collection1"); template.afterPropertiesSet(); return template; } @@ -57,11 +58,16 @@ private void deleteAll() { SolrOperations template; try { template = createSolrTemplate(); - template.delete("collection1", new SimpleQuery(new SimpleStringCriteria("*:*"))); - template.commit("collection1"); - } catch (IOException | SAXException | ParserConfigurationException e) { + template.delete(new SimpleQuery(new SimpleStringCriteria("*:*"))); + template.commit(); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (ParserConfigurationException e) { + throw new RuntimeException(e); + } catch (SAXException e) { throw new RuntimeException(e); } + } } diff --git a/src/test/java/org/springframework/data/solr/repository/config/EnableSolrRepositoriesWithPredefinedConvertersUnitTests.java b/src/test/java/org/springframework/data/solr/repository/config/EnableSolrRepositoriesWithPredefinedConvertersUnitTests.java index f89f59c..98c3746 100644 --- a/src/test/java/org/springframework/data/solr/repository/config/EnableSolrRepositoriesWithPredefinedConvertersUnitTests.java +++ b/src/test/java/org/springframework/data/solr/repository/config/EnableSolrRepositoriesWithPredefinedConvertersUnitTests.java @@ -19,8 +19,8 @@ import static org.junit.Assert.*; import java.lang.reflect.Proxy; -import java.util.Collections; +import org.apache.solr.client.solrj.SolrClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; @@ -28,15 +28,13 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.data.convert.CustomConversions; import org.springframework.data.repository.CrudRepository; import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer; import org.springframework.data.solr.core.SolrTemplate; +import org.springframework.data.solr.core.convert.CustomConversions; import org.springframework.data.solr.core.convert.MappingSolrConverter; -import org.springframework.data.solr.core.convert.SolrCustomConversions; import org.springframework.data.solr.repository.ProductBean; import org.springframework.data.solr.repository.support.SimpleSolrRepository; -import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -47,19 +45,19 @@ @ContextConfiguration public class EnableSolrRepositoriesWithPredefinedConvertersUnitTests extends AbstractITestWithEmbeddedSolrServer { - private static final CustomConversions CUSTOM_CONVERSIONS = new SolrCustomConversions(Collections.emptyList()); + private static final CustomConversions CUSTOM_CONVERSIONS = new CustomConversions(); @Configuration - @EnableSolrRepositories(considerNestedRepositories = true) - static class Config extends AbstractSolrConfiguration { + @EnableSolrRepositories(multicoreSupport = true, considerNestedRepositories = true) + static class Config { - @Override - public SolrClientFactory solrClientFactory() { - return server; + @Bean + public SolrClient solrClient() { + return server.getSolrClient("collection1"); } @Bean - public CustomConversions customConversions() { + CustomConversions customConversions() { CustomConversions conversions = CUSTOM_CONVERSIONS; return conversions; } @@ -81,7 +79,7 @@ public void shouldUseExistingMappingContextWhenPresent() throws BeansException, sameInstance(CUSTOM_CONVERSIONS)); } - interface ProductRepository extends CrudRepository { + static interface ProductRepository extends CrudRepository { } } diff --git a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesJustDeclaringSolrClient.java b/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesJustDeclaringSolrClient.java deleted file mode 100644 index 30f0ed6..0000000 --- a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesJustDeclaringSolrClient.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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.solr.repository.config; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import org.apache.solr.client.solrj.SolrClient; -import org.junit.Test; -import org.junit.runner.RunWith; -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.data.solr.AbstractITestWithEmbeddedSolrServer; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * Integration test for {@link EnableSolrRepositories} just declaring a {@link SolrClient} {@link Bean} but no - * {@link org.springframework.data.solr.core.SolrTemplate}. - * - * @author Christoph Strobl - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class ITestEnableSolrRepositoriesJustDeclaringSolrClient extends AbstractITestWithEmbeddedSolrServer { - - @Configuration - @EnableSolrRepositories - static class Config { - - @Bean - public SolrClient solrClient() { - return server.getSolrClient("collection1"); - } - - } - - @Autowired PersonRepository repository; - - @Autowired ApplicationContext context; - - @Test - public void bootstrapsRepository() { - assertThat(repository, is(notNullValue())); - } - - @Test // DATASOLR-163 - public void shouldRegisterMappingContextWhenNotPresent() { - assertThat(context.containsBean("solrMappingContext"), is(true)); - } - - @Test // DATASOLR-372 - public void shouldRegisterSolrTemplateWhenNotPresent() { - assertThat(context.containsBean("solrTemplate"), is(true)); - } -} diff --git a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithMulticoreSupport.java b/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithMulticoreSupport.java index 8492cd3..e5d137f 100644 --- a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithMulticoreSupport.java +++ b/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithMulticoreSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 - 2017 the original author or authors. + * Copyright 2014 - 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. @@ -25,7 +25,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer; -import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -39,12 +38,12 @@ public class ITestEnableSolrRepositoriesWithMulticoreSupport extends AbstractITestWithEmbeddedSolrServer { @Configuration - @EnableSolrRepositories - static class Config extends AbstractSolrConfiguration { + @EnableSolrRepositories(multicoreSupport = true) + static class Config { - @Override - public SolrClientFactory solrClientFactory() { - return server; + @Bean + public SolrClient solrClient() { + return server.getSolrClient("collection1"); } } diff --git a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithSchemaCreationSupport.java b/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithSchemaCreationSupport.java index 48b1dfc..bdf46cc 100644 --- a/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithSchemaCreationSupport.java +++ b/src/test/java/org/springframework/data/solr/repository/config/ITestEnableSolrRepositoriesWithSchemaCreationSupport.java @@ -31,7 +31,6 @@ import org.springframework.data.solr.core.SolrTemplate; import org.springframework.data.solr.core.schema.SolrPersistentEntitySchemaCreator.Feature; import org.springframework.data.solr.repository.support.SimpleSolrRepository; -import org.springframework.data.solr.server.SolrClientFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -45,12 +44,12 @@ public class ITestEnableSolrRepositoriesWithSchemaCreationSupport extends Abstra @Autowired ApplicationContext context; @Configuration - @EnableSolrRepositories(schemaCreationSupport = true) - static class Config extends AbstractSolrConfiguration { + @EnableSolrRepositories(schemaCreationSupport = true, multicoreSupport = true) + static class Config { - @Override - public SolrClientFactory solrClientFactory() { - return server; + @Bean + public SolrClient solrClient() { + return server.getSolrClient("collection1"); } } diff --git a/src/test/java/org/springframework/data/solr/repository/config/ITestXmlNamespaceMulticore.java b/src/test/java/org/springframework/data/solr/repository/config/ITestXmlNamespaceMulticore.java new file mode 100644 index 0000000..b2b148f --- /dev/null +++ b/src/test/java/org/springframework/data/solr/repository/config/ITestXmlNamespaceMulticore.java @@ -0,0 +1,46 @@ +/* + * Copyright 2012 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.solr.repository.config; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * Integration test for XML namespace configuration. + * + * @author Oliver Gierke + * @author Christoph Strobl + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("namespace-multicore.xml") +public class ITestXmlNamespaceMulticore { + + @Autowired ApplicationContext context; + + @Test + public void createsRepositoryAndEmbeddedServerCorrectly() { + assertThat(context.getBean(PersonRepository.class), is(notNullValue())); + assertThat(context.getBean("solrClient", HttpSolrClient.class), is(notNullValue())); + } +} diff --git a/src/test/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessorTests.java b/src/test/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessorTests.java index f0f85e4..c7d63cb 100644 --- a/src/test/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessorTests.java +++ b/src/test/java/org/springframework/data/solr/repository/query/SolrParametersParameterAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2015 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. @@ -23,7 +23,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.RepositoryMetadata; @@ -61,7 +61,7 @@ public void testGetBoostMultipleObjects() throws Exception { Assert.assertEquals("value1", accessor.getBindableValue(0)); Assert.assertEquals(2.0f, accessor.getBoost(0), 0.0f); - Assert.assertEquals(1000, accessor.getBindableValue(1)); + Assert.assertEquals(Integer.valueOf(1000), accessor.getBindableValue(1)); Assert.assertEquals(10.0f, accessor.getBoost(1), 0.0f); } @@ -74,7 +74,7 @@ public void testGetBoostNotAllArgsHavingBoostValues() throws Exception { Assert.assertEquals("value1", accessor.getBindableValue(0)); Assert.assertEquals(Float.NaN, accessor.getBoost(0), 0.0f); - Assert.assertEquals(1000, accessor.getBindableValue(1)); + Assert.assertEquals(Integer.valueOf(1000), accessor.getBindableValue(1)); Assert.assertEquals(10.0f, accessor.getBoost(1), 0.0f); } diff --git a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryCreatorTests.java b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryCreatorTests.java index 0768d0c..5b5da02 100644 --- a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryCreatorTests.java +++ b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryCreatorTests.java @@ -27,7 +27,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.domain.Sort; import org.springframework.data.geo.Box; import org.springframework.data.geo.Distance; diff --git a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryMethodTests.java b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryMethodTests.java index b8adec4..206d9db 100644 --- a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryMethodTests.java +++ b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryMethodTests.java @@ -22,7 +22,6 @@ import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -374,7 +373,7 @@ public void testQueryWithEmptyHighlight() throws Exception { @Test public void testQueryWithHighlightSingleField() throws Exception { SolrQueryMethod method = getQueryMethodByName("findByTextHighlightSingleField", String.class); - assertThat(Collections.singletonList("field_1"), equalTo(method.getHighlightFieldNames())); + assertThat(Arrays.asList("field_1"), equalTo(method.getHighlightFieldNames())); } @Test @@ -449,15 +448,15 @@ public void testDeleteAttrbiteOfAnnotatedQueryIsFalseByDefault() throws Exceptio public void testStatsForField() throws Exception { SolrQueryMethod method = getQueryMethodByName("findByNameWithFieldStats", String.class); - assertEquals(Collections.singletonList("field1"), method.getFieldStats()); + assertEquals(Arrays.asList("field1"), method.getFieldStats()); } @Test // DATASOLR-160 public void testStatsForFieldAndFacets() throws Exception { SolrQueryMethod method = getQueryMethodByName("findByNameWithFieldAndFacetStats", String.class); - assertEquals(Collections.singletonList("field1"), method.getFieldStats()); - assertEquals(Collections.singletonList("field2"), method.getStatsFacets()); + assertEquals(Arrays.asList("field1"), method.getFieldStats()); + assertEquals(Arrays.asList("field2"), method.getStatsFacets()); } @Test // DATASOLR-160 @@ -475,7 +474,7 @@ public void testStatsForFieldAndFacetsAndSelectiveFacets() throws Exception { SolrQueryMethod method = getQueryMethodByName("findByNameWithFieldStatsAndFacetsStatsAndSelectiveFacetStats", String.class); - assertEquals(Collections.singletonList("field1"), method.getFieldStats()); + assertEquals(Arrays.asList("field1"), method.getFieldStats()); assertEquals(Arrays.asList("field2", "field3"), method.getStatsFacets()); Map statsSelectiveFacets = method.getStatsSelectiveFacets(); assertEquals(1, statsSelectiveFacets.size()); diff --git a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryTests.java b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryTests.java index 6bbe03c..64e81f0 100644 --- a/src/test/java/org/springframework/data/solr/repository/query/SolrQueryTests.java +++ b/src/test/java/org/springframework/data/solr/repository/query/SolrQueryTests.java @@ -15,12 +15,12 @@ */ package org.springframework.data.solr.repository.query; +import java.io.Serializable; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Optional; import org.apache.solr.common.params.HighlightParams; import org.hamcrest.collection.IsEmptyIterable; @@ -30,9 +30,10 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; @@ -69,7 +70,7 @@ * @author Francisco Spaeth * @author Oliver Gierke */ -@RunWith(MockitoJUnitRunner.Silent.class) +@RunWith(MockitoJUnitRunner.class) public class SolrQueryTests { private @Mock SolrOperations solrOperationsMock; @@ -88,8 +89,8 @@ public void setUp() { solrConverter = new MappingSolrConverter(mappingContext); entityInformationCreator = new SolrEntityInformationCreatorImpl(); Mockito.when(persitentEntityMock.getType()).thenReturn(ProductBean.class); - Mockito.when(solrOperationsMock.execute(Mockito.any(SolrCallback.class))) - .thenReturn(new PageImpl<>(Collections. emptyList())); + Mockito.when(solrOperationsMock.execute(Matchers.any(SolrCallback.class))) + .thenReturn(new PageImpl(Collections. emptyList())); Mockito.when(solrOperationsMock.getConverter()).thenReturn(solrConverter); } @@ -106,8 +107,8 @@ public void testQueryWithHighlight() { createQueryForMethod("findAndApplyHighlighting", Pageable.class).execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(Mockito.eq("collection-1"), - captor.capture(), (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(captor.capture(), + (Class) Matchers.any()); HighlightOptions capturedOptions = captor.getValue().getHighlightOptions(); Assert.assertNotNull(capturedOptions); @@ -121,8 +122,8 @@ public void testQueryWithHighlightParameters() { createQueryForMethod("findAndApplyHighlightingAllParameters", Pageable.class) .execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(Mockito.eq("collection-1"), - captor.capture(), (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(captor.capture(), + (Class) Matchers.any()); HighlightOptions capturedOptions = captor.getValue().getHighlightOptions(); Assert.assertNotNull(capturedOptions); @@ -145,8 +146,8 @@ public void testQueryWithParametrizedHighlightQuery() { createQueryForMethod("findAndApplyHighlightingWithParametrizedHighlightQuery", String.class, Pageable.class) .execute(new Object[] { "spring", new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(Mockito.eq("collection-1"), - captor.capture(), (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(captor.capture(), + (Class) Matchers.any()); HighlightOptions capturedOptions = captor.getValue().getHighlightOptions(); Assert.assertEquals("name:*spring*", @@ -161,8 +162,8 @@ public void testQueryWithNonDefaultHighlightFormatter() { createQueryForMethod("findAndApplyHighlightingWithNonDefaultFormatter", Pageable.class) .execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(Mockito.eq("collection-1"), - captor.capture(), (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForHighlightPage(captor.capture(), + (Class) Matchers.any()); HighlightOptions capturedOptions = captor.getValue().getHighlightOptions(); Assert.assertNotNull(capturedOptions); @@ -180,14 +181,13 @@ public void shouldApplyLimitCorrectlyWhenPageSizeToBig() throws NoSuchMethodExce Method method = Repo1.class.getMethod("findTop5ByName", String.class, Pageable.class); SolrQueryMethod sqm = createSolrQueryMethodFrom(method); - PartTreeSolrQuery ptsq = new PartTreeSolrQuery("collection-1", sqm, this.solrOperationsMock); + PartTreeSolrQuery ptsq = new PartTreeSolrQuery(sqm, this.solrOperationsMock); ptsq.execute(new Object[] { "foo", new PageRequest(0, 10) }); ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), captor.capture(), - (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), (Class) Matchers.any()); Assert.assertThat(captor.getValue().getPageRequest().getPageNumber(), IsEqual.equalTo(0)); Assert.assertThat(captor.getValue().getPageRequest().getPageSize(), IsEqual.equalTo(5)); @@ -199,14 +199,13 @@ public void shouldApplyLimitCorrectlyToPageWhenPageInsideLimit() throws NoSuchMe Method method = Repo1.class.getMethod("findTop5ByName", String.class, Pageable.class); SolrQueryMethod sqm = createSolrQueryMethodFrom(method); - PartTreeSolrQuery ptsq = new PartTreeSolrQuery("collection-1", sqm, this.solrOperationsMock); + PartTreeSolrQuery ptsq = new PartTreeSolrQuery(sqm, this.solrOperationsMock); ptsq.execute(new Object[] { "foo", new PageRequest(1, 2) }); ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), captor.capture(), - (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), (Class) Matchers.any()); Assert.assertThat(captor.getValue().getPageRequest().getPageNumber(), IsEqual.equalTo(1)); Assert.assertThat(captor.getValue().getPageRequest().getPageSize(), IsEqual.equalTo(2)); @@ -222,8 +221,8 @@ public void shouldNotCallServerIfPageOutsideLimit() throws NoSuchMethodException ptsq.execute(new Object[] { "foo", new PageRequest(2, 5) }); - Mockito.verify(solrOperationsMock, Mockito.never()).queryForPage(Mockito.eq("collection-1"), - Mockito.any(Query.class), (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.never()).queryForPage(Matchers.any(Query.class), + (Class) Matchers.any()); } @Test // DATASOLR-186 @@ -232,8 +231,8 @@ public void sliceShouldTriggerPagedExecution() { createQueryForMethod("findByName", String.class, Pageable.class) .execute(new Object[] { "sliceme", new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), - Mockito.any(Query.class), Mockito.> any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Matchers.any(Query.class), + Matchers.> any()); } @SuppressWarnings("unchecked") @@ -243,8 +242,8 @@ public void testQueryWithStats() { createQueryForMethod("findAndApplyStats", Pageable.class).execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), captor.capture(), - (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), + (Class) Matchers.any()); StatsOptions capturedOptions = captor.getValue().getStatsOptions(); @@ -270,13 +269,13 @@ public void testQueryWithStatsNonSelective() { createQueryForMethod("findAndApplyStatsNonSelective", Pageable.class) .execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), captor.capture(), - (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), + (Class) Matchers.any()); StatsOptions capturedOptions = captor.getValue().getStatsOptions(); Assert.assertEquals(1, capturedOptions.getFields().size()); - Assert.assertTrue(capturedOptions.getFields().containsAll(Collections.singletonList(new SimpleField("field1")))); + Assert.assertTrue(capturedOptions.getFields().containsAll(Arrays.asList(new SimpleField("field1")))); Assert.assertEquals(2, capturedOptions.getFacets().size()); Assert.assertTrue( @@ -292,30 +291,24 @@ public void testQueryWithStatsNoFacets() { createQueryForMethod("findAndApplyStatsNoFacets", Pageable.class).execute(new Object[] { new PageRequest(0, 10) }); - Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(Mockito.eq("collection-1"), captor.capture(), - (Class) Mockito.any()); + Mockito.verify(solrOperationsMock, Mockito.times(1)).queryForPage(captor.capture(), + (Class) Matchers.any()); StatsOptions capturedOptions = captor.getValue().getStatsOptions(); Assert.assertEquals(1, capturedOptions.getFields().size()); - Assert.assertTrue(capturedOptions.getFields().containsAll(Collections.singletonList(new SimpleField("field1")))); + Assert.assertTrue(capturedOptions.getFields().containsAll(Arrays.asList(new SimpleField("field1")))); Assert.assertThat(capturedOptions.getFacets(), IsEmptyIterable.emptyIterable()); Assert.assertThat(capturedOptions.getSelectiveFacets().entrySet(), IsEmptyIterable.emptyIterable()); } - @Test // DATASOLR-402 - public void singleEntityExecutionShouldUseCollectionNameWhenReturningOptional() { - - createQueryForMethod("findAndReturnNotOptional").execute(new Object[] {}); - - Mockito.verify(solrOperationsMock).queryForObject(Mockito.eq("collection-1"), Mockito.any(), Mockito.any()); - } - private RepositoryQuery createQueryForMethod(String methodName, Class... paramTypes) { try { return this.createQueryForMethod(Repo1.class.getMethod(methodName, paramTypes)); - } catch (NoSuchMethodException | SecurityException e) { + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } catch (SecurityException e) { throw new IllegalArgumentException(e.getMessage(), e); } } @@ -352,7 +345,7 @@ private interface Repo1 extends SolrCrudRepository { Slice findByName(String name, Pageable page); @Stats(value = "field1", facets = { "field2", "field3" }, // - selective = @SelectiveStats(field = "field4", facets = { "field4_1", "field4_2" })) + selective = @SelectiveStats(field = "field4", facets = { "field4_1", "field4_2" }) ) Page findAndApplyStats(Pageable page); @Stats(value = "field1", facets = { "field2", "field3" }) @@ -361,14 +354,13 @@ private interface Repo1 extends SolrCrudRepository { @Stats(value = "field1") Page findAndApplyStatsNoFacets(Pageable page); - ProductBean findAndReturnNotOptional(); } private class SolrEntityInformationCreatorImpl implements SolrEntityInformationCreator { @SuppressWarnings("unchecked") @Override - public SolrEntityInformation getEntityInformation(Class domainClass) { + public SolrEntityInformation getEntityInformation(Class domainClass) { return (SolrEntityInformation) new SolrEntityInformationImpl(persitentEntityMock); } } @@ -394,7 +386,7 @@ public Class getJavaType() { private class SolrQueryImpl extends AbstractSolrQuery { public SolrQueryImpl(SolrOperations solrOperations, SolrQueryMethod solrQueryMethod) { - super("collection-1", solrOperations, solrQueryMethod); + super(solrOperations, solrQueryMethod); } @Override diff --git a/src/test/java/org/springframework/data/solr/repository/query/StringBasedSolrQueryTests.java b/src/test/java/org/springframework/data/solr/repository/query/StringBasedSolrQueryTests.java index e54f231..8968129 100644 --- a/src/test/java/org/springframework/data/solr/repository/query/StringBasedSolrQueryTests.java +++ b/src/test/java/org/springframework/data/solr/repository/query/StringBasedSolrQueryTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; diff --git a/src/test/java/org/springframework/data/solr/repository/support/ITestSolrRepositoryFactory.java b/src/test/java/org/springframework/data/solr/repository/support/ITestSolrRepositoryFactory.java index 87e6433..26543d3 100644 --- a/src/test/java/org/springframework/data/solr/repository/support/ITestSolrRepositoryFactory.java +++ b/src/test/java/org/springframework/data/solr/repository/support/ITestSolrRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 - 2017 the original author or authors. + * Copyright 2012 - 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. @@ -44,7 +44,7 @@ public class ITestSolrRepositoryFactory extends AbstractITestWithEmbeddedSolrSer @Before public void setUp() { - SolrTemplate template = new SolrTemplate(server); + SolrTemplate template = new SolrTemplate(server, "collection1"); template.afterPropertiesSet(); factory = new SolrRepositoryFactory(template); } @@ -70,19 +70,19 @@ public void testCRUDOperations() throws InterruptedException { repository.save(initial); Assert.assertEquals(1, repository.count()); - ProductBean loaded = repository.findById(initial.getId()).get(); + ProductBean loaded = repository.findOne(initial.getId()); Assert.assertEquals(initial.getName(), loaded.getName()); loaded.setName("name changed"); repository.save(loaded); Assert.assertEquals(1, repository.count()); - loaded = repository.findById(initial.getId()).get(); + loaded = repository.findOne(initial.getId()); Assert.assertEquals("name changed", loaded.getName()); repository.delete(loaded); - Thread.sleep(200); + Thread.sleep(100); Assert.assertEquals(0, repository.count()); } @@ -117,7 +117,7 @@ public void testPartTreeQuery() { ProductBeanRepository repository = factory.getRepository(ProductBeanRepository.class); - repository.saveAll(Arrays.asList(availableProduct, unavailableProduct)); + repository.save(Arrays.asList(availableProduct, unavailableProduct)); Assert.assertEquals(2, repository.count()); Page result = repository.findByAvailableTrue(new PageRequest(0, 10)); @@ -133,7 +133,7 @@ public void testCollectionResultQuery() { ProductBeanRepository repository = factory.getRepository(ProductBeanRepository.class); - repository.saveAll(Arrays.asList(availableProduct, unavailableProduct)); + repository.save(Arrays.asList(availableProduct, unavailableProduct)); Assert.assertEquals(2, repository.count()); List result = repository.findByAvailableTrue(); diff --git a/src/test/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformationTests.java b/src/test/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformationTests.java index 96584b4..f4d59be 100644 --- a/src/test/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformationTests.java +++ b/src/test/java/org/springframework/data/solr/repository/support/MappingSolrEntityInformationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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,17 +15,15 @@ */ package org.springframework.data.solr.repository.support; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - import org.apache.solr.client.solrj.beans.Field; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.annotation.Id; -import org.springframework.data.mapping.model.Property; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.solr.core.mapping.SimpleSolrPersistentProperty; import org.springframework.data.solr.core.mapping.SolrPersistentEntity; @@ -35,96 +33,108 @@ /** * @author Christoph Strobl - * @author Mark Paluch */ -@RunWith(MockitoJUnitRunner.Silent.class) +@RunWith(MockitoJUnitRunner.class) public class MappingSolrEntityInformationTests { private static final String PRODUCT_BEAN_SIMPLE_NAME = "productbean"; - @Mock SolrPersistentEntity persistentEntity; - @Mock SolrPersistentEntity persistentEntityWithAlternateFieldNameForId; - @Mock SolrPersistentEntity persistentEntityWithLongIdFieldType; + @Mock + private SolrPersistentEntity persistentEntity; + + @Mock + private SolrPersistentEntity persistentEntityWithAlternateFieldNameForId; + + @Mock + private SolrPersistentEntity persistentEntityWithLongIdFieldType; @Before public void setUp() { - when(persistentEntity.getType()).thenReturn(ProductBean.class); - when(persistentEntity.getCollectionName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); + Mockito.when(persistentEntity.getType()).thenReturn(ProductBean.class); + Mockito.when(persistentEntity.getSolrCoreName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); - when(persistentEntityWithAlternateFieldNameForId.getType()) - .thenReturn(ProductBeanWithAlternateFieldNameForId.class); - when(persistentEntityWithAlternateFieldNameForId.getCollectionName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); + Mockito.when(persistentEntityWithAlternateFieldNameForId.getType()).thenReturn( + ProductBeanWithAlternateFieldNameForId.class); + Mockito.when(persistentEntityWithAlternateFieldNameForId.getSolrCoreName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); - when(persistentEntityWithLongIdFieldType.getType()).thenReturn(ProductBeanWithLongIdFieldType.class); - when(persistentEntityWithLongIdFieldType.getCollectionName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); + Mockito.when(persistentEntityWithLongIdFieldType.getType()).thenReturn(ProductBeanWithLongIdFieldType.class); + Mockito.when(persistentEntityWithLongIdFieldType.getSolrCoreName()).thenReturn(PRODUCT_BEAN_SIMPLE_NAME); } @Test public void testSolrCoreRetrievalWhenNotExplicitlySet() { - SolrEntityInformation entityInformation = new MappingSolrEntityInformation<>(persistentEntity); - assertEquals(PRODUCT_BEAN_SIMPLE_NAME, entityInformation.getCollectionName()); + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( + persistentEntity); + Assert.assertEquals(PRODUCT_BEAN_SIMPLE_NAME, entityInformation.getSolrCoreName()); } @Test - public void testIdType() throws NoSuchFieldException, SecurityException { - when(persistentEntity.getTypeInformation()).thenReturn(ClassTypeInformation.from(ProductBean.class)); - - SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty( - Property.of(ClassTypeInformation.from(ProductBean.class), ProductBean.class.getDeclaredField("id")), - persistentEntity, SimpleTypeHolder.DEFAULT); - when(persistentEntity.getRequiredIdProperty()).thenReturn(property); + public void testSolrCoreRetrievalWhenSet() { + final String coreName = "core1"; + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( + persistentEntity, coreName); + Assert.assertEquals(coreName, entityInformation.getSolrCoreName()); + } - SolrEntityInformation entityInformation = new MappingSolrEntityInformation<>(persistentEntity); - assertEquals(String.class, entityInformation.getIdType()); + @Test + public void testIdType() throws NoSuchFieldException, SecurityException { + Mockito.when(persistentEntity.getTypeInformation()).thenReturn(ClassTypeInformation.from(ProductBean.class)); + SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty(ProductBean.class.getDeclaredField("id"), + null, persistentEntity, new SimpleTypeHolder()); + Mockito.when(persistentEntity.getIdProperty()).thenReturn(property); + + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( + persistentEntity); + Assert.assertEquals(String.class, entityInformation.getIdType()); } @Test public void testIdTypeWithLongIdFieldType() throws NoSuchFieldException, SecurityException { - when(persistentEntityWithLongIdFieldType.getTypeInformation()) - .thenReturn(ClassTypeInformation.from(ProductBeanWithLongIdFieldType.class)); + Mockito.when(persistentEntityWithLongIdFieldType.getTypeInformation()).thenReturn( + ClassTypeInformation.from(ProductBeanWithLongIdFieldType.class)); SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty( - Property.of(ClassTypeInformation.from(ProductBeanWithLongIdFieldType.class), - ProductBeanWithLongIdFieldType.class.getDeclaredField("id")), - persistentEntityWithLongIdFieldType, SimpleTypeHolder.DEFAULT); - when(persistentEntityWithLongIdFieldType.getRequiredIdProperty()).thenReturn(property); + ProductBeanWithLongIdFieldType.class.getDeclaredField("id"), null, persistentEntityWithLongIdFieldType, + new SimpleTypeHolder()); + Mockito.when(persistentEntityWithLongIdFieldType.getIdProperty()).thenReturn(property); - SolrEntityInformation entityInformation = new MappingSolrEntityInformation<>( + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( persistentEntityWithLongIdFieldType); - assertEquals(Long.class, entityInformation.getIdType()); + Assert.assertEquals(Long.class, entityInformation.getIdType()); } @Test public void testGetIdAttribute() throws NoSuchFieldException, SecurityException { - when(persistentEntity.getTypeInformation()).thenReturn(ClassTypeInformation.from(ProductBean.class)); - SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty( - Property.of(ClassTypeInformation.from(ProductBean.class), ProductBean.class.getDeclaredField("id")), - persistentEntity, SimpleTypeHolder.DEFAULT); - when(persistentEntity.getRequiredIdProperty()).thenReturn(property); - - SolrEntityInformation entityInformation = new MappingSolrEntityInformation<>(persistentEntity); - assertEquals("id", entityInformation.getIdAttribute()); + Mockito.when(persistentEntity.getTypeInformation()).thenReturn(ClassTypeInformation.from(ProductBean.class)); + SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty(ProductBean.class.getDeclaredField("id"), + null, persistentEntity, new SimpleTypeHolder()); + Mockito.when(persistentEntity.getIdProperty()).thenReturn(property); + + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( + persistentEntity); + Assert.assertEquals("id", entityInformation.getIdAttribute()); } @Test public void testGetIdAttributeForAlternateFieldName() throws NoSuchFieldException, SecurityException { - when(persistentEntityWithAlternateFieldNameForId.getTypeInformation()) - .thenReturn(ClassTypeInformation.from(ProductBeanWithAlternateFieldNameForId.class)); + Mockito.when(persistentEntityWithAlternateFieldNameForId.getTypeInformation()).thenReturn( + ClassTypeInformation.from(ProductBeanWithAlternateFieldNameForId.class)); SimpleSolrPersistentProperty property = new SimpleSolrPersistentProperty( - Property.of(ClassTypeInformation.from(ProductBeanWithAlternateFieldNameForId.class), - ProductBeanWithAlternateFieldNameForId.class.getDeclaredField("productId")), - persistentEntityWithAlternateFieldNameForId, SimpleTypeHolder.DEFAULT); - when(persistentEntityWithAlternateFieldNameForId.getRequiredIdProperty()).thenReturn(property); + ProductBeanWithAlternateFieldNameForId.class.getDeclaredField("productId"), null, + persistentEntityWithAlternateFieldNameForId, new SimpleTypeHolder()); + Mockito.when(persistentEntityWithAlternateFieldNameForId.getIdProperty()).thenReturn(property); - SolrEntityInformation entityInformation = new MappingSolrEntityInformation<>( + SolrEntityInformation entityInformation = new MappingSolrEntityInformation( persistentEntityWithAlternateFieldNameForId); - assertEquals("product_id", entityInformation.getIdAttribute()); + Assert.assertEquals("product_id", entityInformation.getIdAttribute()); } class ProductBeanWithAlternateFieldNameForId { - @Id @Field("product_id") private String productId; + @Id + @Field("product_id") + private String productId; public String getProductId() { return productId; @@ -138,7 +148,8 @@ public void setProductId(String productId) { class ProductBeanWithLongIdFieldType { - @Id private Long id; + @Id + private Long id; public Long getId() { return id; diff --git a/src/test/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryTests.java b/src/test/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryTests.java index a57290f..ff251fe 100644 --- a/src/test/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryTests.java +++ b/src/test/java/org/springframework/data/solr/repository/support/SolrRepositoryFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012 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,8 +22,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.data.mapping.MappingException; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.Repository; import org.springframework.data.solr.core.SolrOperations; @@ -38,7 +37,6 @@ /** * @author Christoph Strobl * @author Francisco Spaeth - * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) public class SolrRepositoryFactoryTests { @@ -56,7 +54,7 @@ public class SolrRepositoryFactoryTests { @Before @SuppressWarnings("unchecked") public void setUp() { - Mockito.when(solrEntityMock.getRequiredIdProperty()).thenReturn(solrPersistentPropertyMock); + Mockito.when(solrEntityMock.getIdProperty()).thenReturn(solrPersistentPropertyMock); Mockito.when(solrPersistentPropertyMock.getFieldName()).thenReturn("id"); Mockito.when(solrOperationsMock.getConverter()).thenReturn(solrConverterMock); Mockito.when(solrConverterMock.getMappingContext()).thenReturn(mappingContextMock); @@ -80,7 +78,7 @@ public void testGetRepository() { Assert.assertNotNull(repository); } - @Test(expected = MappingException.class) + @Test(expected = IllegalArgumentException.class) public void testGetRepositoryOfUnmanageableType() { SolrTemplate template = new SolrTemplate(new HttpSolrClient("http://solrserver:8983/solr"), null); @@ -90,7 +88,7 @@ public void testGetRepositoryOfUnmanageableType() { @SuppressWarnings("unchecked") private void initMappingContext() { - Mockito.when(mappingContextMock.getRequiredPersistentEntity(ProductBean.class)).thenReturn(solrEntityMock); + Mockito.when(mappingContextMock.getPersistentEntity(ProductBean.class)).thenReturn(solrEntityMock); Mockito.when(solrEntityMock.getType()).thenReturn(ProductBean.class); } diff --git a/src/test/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactoryTests.java b/src/test/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactoryTests.java new file mode 100644 index 0000000..97ea94e --- /dev/null +++ b/src/test/java/org/springframework/data/solr/server/support/MulticoreSolrClientFactoryTests.java @@ -0,0 +1,184 @@ +/* + * Copyright 2012 - 2015 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.solr.server.support; + +import java.net.MalformedURLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.impl.CloudSolrClient; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.impl.LBHttpSolrClient; +import org.hamcrest.core.IsEqual; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.Mockito; +import org.springframework.data.solr.core.mapping.SolrDocument; + +/** + * @author Christoph Strobl + */ +@RunWith(Parameterized.class) +public class MulticoreSolrClientFactoryTests { + + private SolrClient solrClient; + private MulticoreSolrClientFactory factory; + private static final List CORES = Arrays.asList("spring", "data", "solr"); + + public MulticoreSolrClientFactoryTests(SolrClient solrClient) { + this.solrClient = solrClient; + } + + @Parameters + public static Collection data() throws MalformedURLException { + Object[][] data = new Object[][] { { new HttpSolrClient("http://127.0.0.1:8983") }, + { new LBHttpSolrClient("http://127.0.0.1:8983", "http://127.0.0.1:6666") }, + { new CloudSolrClient("http://127.0.0.1:8080") } }; + return Arrays.asList(data); + } + + @Before + public void setUp() throws MalformedURLException { + this.factory = new MulticoreSolrClientFactory(this.solrClient, CORES); + } + + @Test + public void testGetCores() { + Assert.assertThat(factory.getCores(), IsEqual.equalTo(CORES)); + } + + @Test + public void testGetSolrClientForDefinedCore() { + SolrClient solrClient = factory.getSolrClient("spring"); + Assert.assertNotNull(solrClient); + Assert.assertNotSame(this.solrClient, solrClient); + } + + @Test + public void testGetSolrClientForUndefinedCore() { + SolrClient solrClient = factory.getSolrClient("gini"); + Assert.assertNotNull(solrClient); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "gini"))); + } + + @Test + public void testGetSolrClientForNullCoreReturnsDefaultInstance() { + SolrClient solrClient = factory.getSolrClient((String) null); + Assert.assertSame(this.solrClient, solrClient); + } + + @Test + public void testGetSolrClientForEmptyCoreReturnsDefaultInstance() { + SolrClient solrClient = factory.getSolrClient(" "); + Assert.assertSame(this.solrClient, solrClient); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetSolrClientForNullClassThrowsIllegalArgumentException() { + factory.getSolrClient((Class) null); + } + + @Test + public void testGetSolrServerForClassWithoutSolrDocumentAnnotationReturnedCorrectly() { + SolrClient solrClient = factory.getSolrClient(ClassWithoutSolrDocumentAnnotation.class); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertThat(factory.getCores(), + IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "ClassWithoutSolrDocumentAnnotation"))); + } + + @Test + public void testGetSolrServerForClassWithEmptySolrDocumentAnnotationReturnedCorrectly() { + SolrClient solrClient = factory.getSolrClient(ClassWithEmptySolrDocumentAnnotation.class); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertThat(factory.getCores(), + IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "ClassWithEmptySolrDocumentAnnotation"))); + } + + @Test + public void testGetSolrServerForClassWithSolrDocumentAnnotationReturnedCorrectly() { + SolrClient solrClient = factory.getSolrClient(ClassWithSolrDocumentAnnotation.class); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "core1"))); + } + + @Test + public void testGetDefaultSolrClient() { + SolrClient solrClient = factory.getSolrClient(); + Assert.assertSame(this.solrClient, solrClient); + } + + @Test + public void testGetSolrClientReturnsNullWhenCoreDoesNotExistAndCreateMissingIsFalse() { + factory.setCreateMissingSolrClient(false); + Assert.assertNull(factory.getSolrClient("NoSuchCore")); + } + + @Test + public void testAddSolrClientForCoreNotConfigured() { + HttpSolrClient ref = new HttpSolrClient("http://some.server.added/manually"); + factory.addSolrClientForCore(ref, "core1"); + + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "core1"))); + + SolrClient solrClient = factory.getSolrClient("core1"); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertSame(ref, solrClient); + } + + @Test + public void testAddSolrClientOverwritesExistingWhenCoreAlreayConfigured() { + HttpSolrClient ref = new HttpSolrClient("http://some.server.added/manually"); + factory.addSolrClientForCore(ref, "solr"); + + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr"))); + + SolrClient solrClient = factory.getSolrClient("solr"); + Assert.assertNotSame(this.solrClient, solrClient); + Assert.assertSame(ref, solrClient); + } + + @Test + public void testRemoveSolrClientCallsShutownOnRemovedInstance() { + SolrClient solrClientMock = Mockito.mock(this.solrClient.getClass()); + factory.addSolrClientForCore(solrClientMock, "mock"); + + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr", "mock"))); + factory.removeSolrClient("mock"); + Assert.assertThat(factory.getCores(), IsEqual.equalTo(Arrays.asList("spring", "data", "solr"))); + } + + private static class ClassWithoutSolrDocumentAnnotation { + + } + + @SolrDocument + private static class ClassWithEmptySolrDocumentAnnotation { + + } + + @SolrDocument(solrCoreName = "core1") + private static class ClassWithSolrDocumentAnnotation { + + } + +} diff --git a/src/test/java/org/springframework/data/solr/server/support/SolrClientUtilTests.java b/src/test/java/org/springframework/data/solr/server/support/SolrClientUtilTests.java new file mode 100644 index 0000000..5697b21 --- /dev/null +++ b/src/test/java/org/springframework/data/solr/server/support/SolrClientUtilTests.java @@ -0,0 +1,315 @@ +/* + * 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.solr.server.support; + +import static org.hamcrest.core.IsCollectionContaining.*; +import static org.hamcrest.core.IsEqual.*; +import static org.hamcrest.text.IsEmptyString.*; + +import java.net.MalformedURLException; +import java.util.Map; + +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.AbstractHttpClient; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.SingleClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; +import org.apache.solr.client.solrj.impl.CloudSolrClient; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.impl.LBHttpSolrClient; +import org.apache.solr.core.CoreContainer; +import org.hamcrest.core.IsEqual; +import org.hamcrest.core.IsSame; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.data.solr.core.mapping.SolrDocument; +import org.springframework.test.util.ReflectionTestUtils; + +/** + * @author Christoph Strobl + */ +public class SolrClientUtilTests { + + private static final String FIELD_ZOO_KEEPER = "zkHost"; + private static final String FIELD_ALIVE_SERVERS = "aliveServers"; + + private static final String CORE_NAME = "core1"; + private static final String ZOO_KEEPER_URL = "http://127.0.0.1/zk"; + private static final String BASE_URL = "http://127.0.0.1:8983/solr"; + private static final String ALTERNATE_BASE_URL = "http://localhost:8983/solr"; + + private static final String CORE_URL = BASE_URL + "/" + CORE_NAME; + private static final String ALTERNATE_CORE_URL = ALTERNATE_BASE_URL + "/" + CORE_NAME; + + @Test(expected = IllegalArgumentException.class) + public void testCloneNullThrowsIllegalArgumentException() { + SolrClientUtils.clone(null); + } + + @Test + public void testClonesHttpSolrClientCorrectly() { + HttpSolrClient httpSolrClient = new HttpSolrClient(BASE_URL); + httpSolrClient.setDefaultMaxConnectionsPerHost(10); + httpSolrClient.setFollowRedirects(true); + httpSolrClient.setUseMultiPartPost(true); + + HttpSolrClient clone = SolrClientUtils.clone(httpSolrClient); + Assert.assertEquals(httpSolrClient.getBaseURL(), clone.getBaseURL()); + assertHttpSolrClientProperties(httpSolrClient, clone); + } + + @Test + public void testClonesHttpSolrClientForCoreCorrectly() { + HttpSolrClient httpSolrClient = new HttpSolrClient(BASE_URL); + httpSolrClient.setDefaultMaxConnectionsPerHost(10); + httpSolrClient.setFollowRedirects(true); + httpSolrClient.setUseMultiPartPost(true); + + HttpSolrClient clone = SolrClientUtils.clone(httpSolrClient, CORE_NAME); + + Assert.assertEquals(CORE_URL, clone.getBaseURL()); + + assertHttpSolrClientProperties(httpSolrClient, clone); + } + + @Test + public void testClonesLBHttpSolrClientCorrectly() throws MalformedURLException { + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(BASE_URL, ALTERNATE_BASE_URL); + lbSolrClient.setAliveCheckInterval(10); + + LBHttpSolrClient clone = SolrClientUtils.clone(lbSolrClient); + + Assert.assertEquals(ReflectionTestUtils.getField(lbSolrClient, FIELD_ALIVE_SERVERS), + ReflectionTestUtils.getField(clone, FIELD_ALIVE_SERVERS)); + assertLBHttpSolrClientProperties(lbSolrClient, clone); + } + + @Test + @SuppressWarnings("unchecked") + public void testClonesLBHttpSolrClientForCoreCorrectly() throws MalformedURLException { + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(BASE_URL, ALTERNATE_BASE_URL); + lbSolrClient.setAliveCheckInterval(10); + + LBHttpSolrClient clone = SolrClientUtils.clone(lbSolrClient, CORE_NAME); + + Map aliveServers = (Map) ReflectionTestUtils.getField(clone, FIELD_ALIVE_SERVERS); + Assert.assertThat(aliveServers.keySet(), hasItems(CORE_URL, ALTERNATE_CORE_URL)); + + assertLBHttpSolrClientProperties(lbSolrClient, clone); + } + + @Test + public void testClonesCloudSolrClientCorrectly() throws MalformedURLException { + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(BASE_URL, ALTERNATE_BASE_URL); + CloudSolrClient cloudClient = new CloudSolrClient(ZOO_KEEPER_URL, lbSolrClient); + + CloudSolrClient clone = SolrClientUtils.clone(cloudClient); + Assert.assertEquals(ZOO_KEEPER_URL, ReflectionTestUtils.getField(clone, FIELD_ZOO_KEEPER)); + + LBHttpSolrClient lbClone = clone.getLbClient(); + Assert.assertEquals(ReflectionTestUtils.getField(lbSolrClient, FIELD_ALIVE_SERVERS), + ReflectionTestUtils.getField(lbClone, FIELD_ALIVE_SERVERS)); + + assertLBHttpSolrClientProperties(lbSolrClient, lbClone); + } + + @Test + @SuppressWarnings("unchecked") + public void testClonesCloudSolrClientForCoreCorrectlyWhenCoreNameIsNotEmpty() throws MalformedURLException { + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(BASE_URL, ALTERNATE_BASE_URL); + CloudSolrClient cloudClient = new CloudSolrClient(ZOO_KEEPER_URL, lbSolrClient); + + CloudSolrClient clone = SolrClientUtils.clone(cloudClient, CORE_NAME); + Assert.assertEquals(ZOO_KEEPER_URL, ReflectionTestUtils.getField(clone, FIELD_ZOO_KEEPER)); + + LBHttpSolrClient lbClone = clone.getLbClient(); + Map aliveServers = (Map) ReflectionTestUtils.getField(lbClone, FIELD_ALIVE_SERVERS); + Assert.assertThat(aliveServers.keySet(), hasItems(CORE_URL, ALTERNATE_CORE_URL)); + + assertLBHttpSolrClientProperties(lbSolrClient, lbClone); + Assert.assertThat(clone.getDefaultCollection(), equalTo(CORE_NAME)); + } + + @Test + public void testClonesCloudSolrClientForCoreCorrectlyWhenNoLBHttpServerPresent() throws MalformedURLException { + CloudSolrClient cloudClient = new CloudSolrClient(ZOO_KEEPER_URL); + + CloudSolrClient clone = SolrClientUtils.clone(cloudClient, CORE_NAME); + Assert.assertEquals(ZOO_KEEPER_URL, ReflectionTestUtils.getField(clone, FIELD_ZOO_KEEPER)); + + LBHttpSolrClient lbClone = clone.getLbClient(); + + assertLBHttpSolrClientProperties(cloudClient.getLbClient(), lbClone); + Assert.assertThat(clone.getDefaultCollection(), equalTo(CORE_NAME)); + } + + @Test + public void testCreateUrlForCoreAppendsCoreCorrectly() { + Assert.assertEquals(CORE_URL, SolrClientUtils.appendCoreToBaseUrl(BASE_URL, CORE_NAME)); + } + + @Test + public void testCreateUrlForCoreAppendsCoreCorrectlyWhenBaseUrlHasTrailingSlash() { + Assert.assertEquals(CORE_URL, SolrClientUtils.appendCoreToBaseUrl(BASE_URL + "/", CORE_NAME)); + } + + @Test + public void testCreateUrlForCoreAppendsCoreCorrectlyWhenCoreIsEmpty() { + Assert.assertEquals(BASE_URL, SolrClientUtils.appendCoreToBaseUrl(BASE_URL, " ")); + } + + @Test + public void testCreateUrlForCoreAppendsCoreCorrectlyWhenCoreIsNull() { + Assert.assertEquals(BASE_URL, SolrClientUtils.appendCoreToBaseUrl(BASE_URL, null)); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateUrlForCoreThrowsIllegalArgumentExceptionWhenBaseUrlIsNull() { + Assert.assertEquals(BASE_URL, SolrClientUtils.appendCoreToBaseUrl(null, null)); + } + + @Test + public void testResolveSolrCoreNameShouldReturnEmptyStringWhenNoAnnotationPresent() { + Assert.assertThat(SolrClientUtils.resolveSolrCoreName(ClassWithoutSolrDocumentAnnotation.class), isEmptyString()); + } + + @Test + public void testResolveSolrCoreNameShouldReturnEmptyStringWhenAnnotationHasNoValue() { + Assert.assertThat(SolrClientUtils.resolveSolrCoreName(ClassWithEmptySolrDocumentAnnotation.class), isEmptyString()); + } + + @Test + public void testResolveSolrCoreNameShouldReturnAnnotationValueWhenPresent() { + Assert.assertThat(SolrClientUtils.resolveSolrCoreName(ClassWithSolrDocumentAnnotation.class), equalTo("core1")); + } + + @Test // DATASOLR-189 + public void cloningLBHttpSolrClientShouldCopyHttpParamsCorrectly() throws MalformedURLException { + + HttpParams params = new BasicHttpParams(); + params.setParameter("foo", "bar"); + DefaultHttpClient client = new DefaultHttpClient(params); + + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(client, BASE_URL, ALTERNATE_BASE_URL); + + LBHttpSolrClient cloned = SolrClientUtils.clone(lbSolrClient, CORE_NAME); + Assert.assertThat(cloned.getHttpClient().getParams(), IsEqual.equalTo(params)); + + } + + @Test // DATASOLR-189 + public void cloningLBHttpSolrClientShouldCopyCredentialsProviderCorrectly() { + + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar")); + + DefaultHttpClient client = new DefaultHttpClient(); + client.setCredentialsProvider(credentialsProvider); + + LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(client, BASE_URL, ALTERNATE_BASE_URL); + + LBHttpSolrClient cloned = SolrClientUtils.clone(lbSolrClient, CORE_NAME); + Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(), + IsEqual. equalTo(credentialsProvider)); + } + + @Test // DATASOLR-189 + public void cloningHttpSolrClientShouldCopyHttpParamsCorrectly() { + + HttpParams params = new BasicHttpParams(); + params.setParameter("foo", "bar"); + DefaultHttpClient client = new DefaultHttpClient(params); + + HttpSolrClient solrClient = new HttpSolrClient(BASE_URL, client); + HttpSolrClient cloned = SolrClientUtils.clone(solrClient); + + Assert.assertThat(cloned.getHttpClient().getParams(), IsEqual.equalTo(params)); + } + + @Test // DATASOLR-189 + public void cloningHttpSolrClientShouldCopyCredentialsProviderCorrectly() { + + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar")); + + DefaultHttpClient client = new DefaultHttpClient(); + client.setCredentialsProvider(credentialsProvider); + + HttpSolrClient solrClient = new HttpSolrClient(BASE_URL, client); + HttpSolrClient cloned = SolrClientUtils.clone(solrClient); + + Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(), + IsEqual. equalTo(credentialsProvider)); + } + + @Test // DATASOLR-227 + public void cloningHttpSolrClientShouldCopyConnectionManager() { + + ClientConnectionManager conncetionManager = new SingleClientConnManager(); + + DefaultHttpClient client = new DefaultHttpClient(conncetionManager); + + HttpSolrClient solrClient = new HttpSolrClient(BASE_URL, client); + HttpSolrClient cloned = SolrClientUtils.clone(solrClient); + + Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getConnectionManager(), + IsEqual. equalTo(conncetionManager)); + } + + @Test // DATASOLR-203 + public void cloningEmbeddedSolrServerShouldReuseCoreContainer() { + + CoreContainer coreContainer = Mockito.mock(CoreContainer.class); + EmbeddedSolrServer solrServer = new EmbeddedSolrServer(coreContainer, "core1"); + + EmbeddedSolrServer clone = SolrClientUtils.clone(solrServer, "core1"); + Assert.assertThat(clone.getCoreContainer(), IsSame.sameInstance(coreContainer)); + } + + private void assertHttpSolrClientProperties(HttpSolrClient httpSolrServer, HttpSolrClient clone) { + Assert.assertEquals(ReflectionTestUtils.getField(httpSolrServer, "followRedirects"), + ReflectionTestUtils.getField(clone, "followRedirects")); + Assert.assertEquals(ReflectionTestUtils.getField(httpSolrServer, "useMultiPartPost"), + ReflectionTestUtils.getField(clone, "useMultiPartPost")); + } + + private void assertLBHttpSolrClientProperties(LBHttpSolrClient lbSolrServer, LBHttpSolrClient clone) { + Assert.assertEquals(ReflectionTestUtils.getField(lbSolrServer, "interval"), + ReflectionTestUtils.getField(clone, "interval")); + } + + private static class ClassWithoutSolrDocumentAnnotation { + + } + + @SolrDocument + private static class ClassWithEmptySolrDocumentAnnotation { + + } + + @SolrDocument(solrCoreName = "core1") + private static class ClassWithSolrDocumentAnnotation { + + } + +} diff --git a/src/test/java/org/springframework/data/solr/test/util/EmbeddedSolrServer.java b/src/test/java/org/springframework/data/solr/test/util/EmbeddedSolrServer.java index 108a0c3..e1a578a 100644 --- a/src/test/java/org/springframework/data/solr/test/util/EmbeddedSolrServer.java +++ b/src/test/java/org/springframework/data/solr/test/util/EmbeddedSolrServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * 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. @@ -66,7 +66,7 @@ public class EmbeddedSolrServer extends ExternalResource implements SolrClientFa TemporaryFolder folder; CoreContainer coreContainer; private ClientCache clientCache = ClientCache.DISABLED; - ConcurrentHashMap cachedClients = new ConcurrentHashMap<>(); + ConcurrentHashMap cachedClients = new ConcurrentHashMap(); private EmbeddedSolrServer() {} @@ -108,6 +108,7 @@ public SolrClient getSolrClient() { * (non-Javadoc) * @see org.springframework.data.solr.server.SolrClientFactory#getSolrClient(java.lang.String) */ + @Override @SuppressWarnings("serial") public SolrClient getSolrClient(String collectionName) { @@ -142,8 +143,9 @@ public void close() { * (non-Javadoc) * @see org.springframework.data.solr.server.SolrClientFactory#getCores() */ + @Override public List getCores() { - return new ArrayList<>(coreContainer.getAllCoreNames()); + return new ArrayList(coreContainer.getCoreNames()); } /* @@ -263,7 +265,7 @@ public SolrQueryRequest buildRequestFrom(SolrCore core, SolrParams params, Colle } } - public enum ClientCache { + public static enum ClientCache { ENABLED, DISABLED } diff --git a/src/test/resources/META-INF/beans.xml b/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000..9750d10 --- /dev/null +++ b/src/test/resources/META-INF/beans.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/test/resources/managed-schema/collection1/conf/elevate.xml b/src/test/resources/managed-schema/collection1/conf/elevate.xml index ff2c8ae..25d5ceb 100644 --- a/src/test/resources/managed-schema/collection1/conf/elevate.xml +++ b/src/test/resources/managed-schema/collection1/conf/elevate.xml @@ -24,19 +24,15 @@ --> - - + + + + + + + + + + + diff --git a/src/test/resources/managed-schema/collection1/conf/email_url_types.txt b/src/test/resources/managed-schema/collection1/conf/email_url_types.txt deleted file mode 100644 index 622b193..0000000 --- a/src/test/resources/managed-schema/collection1/conf/email_url_types.txt +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/src/test/resources/managed-schema/collection1/conf/managed-schema b/src/test/resources/managed-schema/collection1/conf/managed-schema index 1e3b17b..8d8031b 100644 --- a/src/test/resources/managed-schema/collection1/conf/managed-schema +++ b/src/test/resources/managed-schema/collection1/conf/managed-schema @@ -1,6 +1,6 @@ - + id @@ -12,28 +12,10 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + @@ -42,47 +24,37 @@ - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - + - - - - - - + + + + + + @@ -129,7 +101,7 @@ - + @@ -137,7 +109,7 @@ - + @@ -161,7 +133,7 @@ - + @@ -169,43 +141,31 @@ - + - + - - + - + - - - - - - - - - - - - - + + - + - + @@ -216,7 +176,7 @@ - + @@ -242,7 +202,7 @@ - + @@ -251,7 +211,7 @@ - + @@ -265,7 +225,7 @@ - + @@ -274,7 +234,7 @@ - + @@ -283,11 +243,11 @@ - + - + @@ -314,7 +274,7 @@ - + @@ -339,11 +299,11 @@ - + - + @@ -366,7 +326,7 @@ - + @@ -375,7 +335,7 @@ - + @@ -383,7 +343,7 @@ - + @@ -399,7 +359,7 @@ - + @@ -407,7 +367,7 @@ - + @@ -431,21 +391,21 @@ - - - - - - - + + + + + + + - + - + @@ -484,24 +444,15 @@ - - - - - - - - - @@ -509,10 +460,6 @@ - - - - diff --git a/src/test/resources/managed-schema/collection1/conf/params.json b/src/test/resources/managed-schema/collection1/conf/params.json index 22aadcc..06114ef 100644 --- a/src/test/resources/managed-schema/collection1/conf/params.json +++ b/src/test/resources/managed-schema/collection1/conf/params.json @@ -4,31 +4,17 @@ "q.alt":"*:*", "rows":"10", "fl":"*,score", - "":{"v":0}}, + "":{"v":0} + }, "facets":{ "facet":"on", - "facet.mincount":"1", - "f.doc_type.facet.mincount":"0", - "facet.field":["text_shingles","{!ex=type}doc_type", "language"], - "f.text_shingles.facet.limit":10, - "facet.query":"{!ex=type key=all_types}*:*", - "f.doc_type.facet.missing":true, - "":{"v":0}}, - "browse":{ - "type_fq":"{!field f=doc_type v=$type}", - "hl":"on", - "hl.fl":"content", - "v.locale":"${locale}", - "debug":"true", - "hl.simple.pre":"HL_START", - "hl.simple.post":"HL_END", - "echoParams": "explicit", - "_appends_": { - "fq": "{!switch v=$type tag=type case='*:*' case.all='*:*' case.unknown='-doc_type:[* TO *]' default=$type_fq}" - }, - "":{"v":0}}, - "velocity":{ - "wt":"velocity", - "v.template":"browse", - "v.layout":"layout", - "":{"v":0}}}} + "facet.mincount": "1", + "":{"v":0} + }, + "velocity":{ + "wt": "velocity", + "v.template":"browse", + "v.layout": "layout", + "":{"v":0} + } +}} \ No newline at end of file diff --git a/src/test/resources/managed-schema/collection1/conf/solrconfig.xml b/src/test/resources/managed-schema/collection1/conf/solrconfig.xml index e9e4a95..f699c75 100644 --- a/src/test/resources/managed-schema/collection1/conf/solrconfig.xml +++ b/src/test/resources/managed-schema/collection1/conf/solrconfig.xml @@ -35,7 +35,7 @@ that you fully re-index after changing this setting as it can affect both how text is indexed and queried. --> - 6.6.1 + 5.5.0 - - + + + true + managed-schema + + - - @@ -161,18 +181,31 @@ - + 0.1 + + --> + + + - - - ${solr.lock.type:native} + ${solr.lock.type:none} - @@ -231,12 +264,12 @@ 30MINUTES 1DAY --> - @@ -273,7 +306,14 @@ uncommitted changes to the index, so use of a hard autoCommit is recommended (see below). "dir" - the target directory for transaction logs, defaults to the - solr data directory. --> + solr data directory. + "numVersionBuckets" - sets the number of buckets used to keep + track of max version values when checking for re-ordered + updates; increase this value to reduce the cost of + synchronizing access to version buckets during high-volume + indexing, this requires 8 bytes (long) * numVersionBuckets + of heap space per Solr core. + --> ${solr.ulog.dir:} ${solr.ulog.numVersionBuckets:65536} @@ -283,7 +323,7 @@ Perform a hard commit automatically under certain conditions. Instead of enabling autoCommit, consider using "commitWithin" - when adding documents. + when adding documents. http://wiki.apache.org/solr/UpdateXmlMessages @@ -292,7 +332,7 @@ maxTime - Maximum amount of time in ms that is allowed to pass since a document was added before automatically - triggering a new commit. + triggering a new commit. openSearcher - if false, the commit causes recent index changes to be flushed to stable storage, but does not cause a new searcher to be opened to make those changes visible. @@ -310,14 +350,13 @@ but does not ensure that data is synced to disk. This is faster and more near-realtime friendly than a hard commit. --> - - 1024 @@ -402,7 +441,7 @@ There are two implementations of cache available for Solr, LRUCache, based on a synchronized LinkedHashMap, and - FastLRUCache, based on a ConcurrentHashMap. + FastLRUCache, based on a ConcurrentHashMap. FastLRUCache has faster gets and slower puts in single threaded operation and thus is generally faster than LRUCache @@ -435,7 +474,7 @@ autowarmCount="0"/> 20 200 @@ -588,6 +627,17 @@ --> false + + 2 + @@ -600,7 +650,7 @@ such as /select?qt=XXX handleSelect="true" will cause the SolrDispatchFilter to process - the request and dispatch the query to a handler specified by the + the request and dispatch the query to a handler specified by the "qt" param, assuming "/select" isn't already registered. handleSelect="false" will cause the SolrDispatchFilter to @@ -622,19 +672,19 @@ multipartUploadLimitInKB - specifies the max size (in KiB) of Multipart File Uploads that Solr will allow in a Request. - + formdataUploadLimitInKB - specifies the max size (in KiB) of form data (application/x-www-form-urlencoded) sent via POST. You can use POST to pass request parameters not fitting into the URL. - + addHttpRequestToContext - if set to true, it will instruct the requestParsers to include the original HttpServletRequest - object in the context map of the SolrQueryRequest under the + object in the context map of the SolrQueryRequest under the key "httpRequest". It will not be used by any of the existing - Solr components, but may be useful when developing custom + Solr components, but may be useful when developing custom plugins. - + *** WARNING *** The settings below authorize Solr to fetch remote files, You should make sure your system has some authentication before @@ -657,21 +707,21 @@ - - + + + explicit + + @@ -814,13 +867,13 @@ - files-update-processor + add-unknown-fields-to-the-schema + + + + + {!xport} + xsort + false + + + + query + + + + + + + + + json + false + + + + + + + + + + + + + + + + explicit + true + + + @@ -894,7 +1043,7 @@ default - _text_ + text solr.DirectSolrSpellChecker internal @@ -911,12 +1060,11 @@ 0.01 - + + + + + + + + + - @@ -948,6 +1133,7 @@ collations (re-written queries) can include a combination of corrections from both spellcheckers --> default + wordbreak on true 10 @@ -973,8 +1159,8 @@ This is purely as an example. - In reality you will likely want to add the component to your - already specified request handlers. + In reality you will likely want to add the component to your + already specified request handlers. --> @@ -1048,8 +1234,8 @@ - @@ -1094,7 +1280,7 @@ - - - - + + + + [^\w-\.] @@ -1213,8 +1402,6 @@ tdoubles - - @@ -1224,8 +1411,8 @@ on the fly based on the hash code of some other fields. This example has overwriteDupes set to false since we are using the id field as the signatureField and Solr will maintain - uniqueness based on that anyway. - + uniqueness based on that anyway. + --> - text/plain; charset=UTF-8 + application/json; charset=UTF-8 ${velocity.template.base.dir:} - ${velocity.solr.resource.loader.enabled:true} - ${velocity.params.resource.loader.enabled:false} 5 @@ -1335,7 +1520,7 @@ @@ -1368,12 +1553,12 @@ jdbc://.... - + To add a constant value to all docs, use: 5 - + If you want the user to still be able to change it with _value:something_ use this: 5 @@ -1384,4 +1569,10 @@ --> + + + + *:* + + diff --git a/src/test/resources/org/springframework/data/solr/repository/ITestSolrRepositoryOperations-context.xml b/src/test/resources/org/springframework/data/solr/repository/ITestSolrRepositoryOperations-context.xml index 477308e..a18878b 100644 --- a/src/test/resources/org/springframework/data/solr/repository/ITestSolrRepositoryOperations-context.xml +++ b/src/test/resources/org/springframework/data/solr/repository/ITestSolrRepositoryOperations-context.xml @@ -11,6 +11,7 @@ + diff --git a/src/test/resources/org/springframework/data/solr/repository/config/namespace-multicore.xml b/src/test/resources/org/springframework/data/solr/repository/config/namespace-multicore.xml new file mode 100644 index 0000000..ea20671 --- /dev/null +++ b/src/test/resources/org/springframework/data/solr/repository/config/namespace-multicore.xml @@ -0,0 +1,11 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/static-schema/collection1/conf/managed-schema b/src/test/resources/static-schema/collection1/conf/managed-schema deleted file mode 100644 index 3a508bf..0000000 --- a/src/test/resources/static-schema/collection1/conf/managed-schema +++ /dev/null @@ -1,1189 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - id - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/resources/static-schema/collection1/conf/schema.xml b/src/test/resources/static-schema/collection1/conf/schema.xml index b7728f0..649d921 100644 --- a/src/test/resources/static-schema/collection1/conf/schema.xml +++ b/src/test/resources/static-schema/collection1/conf/schema.xml @@ -16,10 +16,10 @@ limitations under the License. --> - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - id - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> - - - - + Default numeric field types. For faster range queries, consider the tint/tfloat/tlong/tdouble types. - - - - - - - - - - + + + + - - - - + + + + - - - - + Note: For faster range queries, consider the tdate type + --> + - - + + @@ -430,11 +395,11 @@ - - - + + + - - - - - + + + + + + removes stop words from case-insensitive "stopwords.txt" + (empty by default), and down cases. At query time only, it + also applies synonyms. --> - - - - - - - - - - - - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + each token, to enable more efficient leading wildcard queries. --> - - - - - - - - - - - - + + + + + + + + + + + + @@ -631,99 +596,99 @@ that does not include some properties of the source text --> - - - - - - - - - - + + + + + + + + + + - + - - - - + + + + - - - - - + + + + + - - - - + + + + - - - - - - - + + + + + + - - - - - - - + + + + + + + any data added to them will be ignored outright. --> - - + + + geo="true" distErrPct="0.025" maxDistErr="0.001" distanceUnits="kilometers" /> - - - + + + + - - + - - - - - - - - - + + + + + + + + + - - - - - - + + + + + + - + - - - - - - - - + + + + + + + + - + - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - + + + + + + - + - - - - - - + + + + + + - + - - - - - - - - - + + + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - + + + + + + - + - - - - - - - - - + + + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - - - - + + + + + + + + + + - + - - - - - - - - - - + + + + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - - - - + + + + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - - - + + + + + + + + + - + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - - - + + + + + + + + + - + - - - - - - - - - + + + + + + + + + - + - - - - - - + + + + + + - + - - - - - - - + + + + + + + - + - - - - - - - + + + + + + + - + - - - - - + + + + + - + - - - - - - - - - - - - - - - + + + + + + + - - - + + + diff --git a/src/test/resources/static-schema/collection1/conf/solrconfig.xml b/src/test/resources/static-schema/collection1/conf/solrconfig.xml index 4633045..10b3524 100644 --- a/src/test/resources/static-schema/collection1/conf/solrconfig.xml +++ b/src/test/resources/static-schema/collection1/conf/solrconfig.xml @@ -35,7 +35,7 @@ that you fully re-index after changing this setting as it can affect both how text is indexed and queried. --> - 6.6.1 + 5.5.0 + + + + + + @@ -171,11 +196,22 @@ Even older versions of Lucene used LogDocMergePolicy. --> + + + ${solr.lock.type:none} + + + + solr data directory. --> ${solr.ulog.dir:} - ${solr.ulog.numVersionBuckets:65536} + + Caches results of searches - ordered lists of document ids + (DocList) based on a query, a sort, and the range of documents requested. + --> --> - - - false + + 2 + @@ -773,21 +805,6 @@ explicit 10 - - false + + + + {!xport} + xsort + false + + + + query + + + + + + + + + + + text + + + + _src_ + + true + + + + + + + + + + + + + + + + + + + + + explicit + true + + + 0.01 @@ -1169,16 +1346,13 @@ - - + mySuggester FuzzyLookupFactory @@ -1186,12 +1360,11 @@ cat price string - false + startup="lazy" enable="${solr.suggester.enabled:false}" > true 10 @@ -1200,6 +1373,7 @@ suggest + --> - + Currently available open source algorithms are: + * org.carrot2.clustering.lingo.LingoClusteringAlgorithm + * org.carrot2.clustering.stc.STCClusteringAlgorithm + * org.carrot2.clustering.kmeans.BisectingKMeansClusteringAlgorithm - - lingo3g - true - com.carrotsearch.lingo3g.Lingo3GClusteringAlgorithm - clustering/carrot2 - + See http://project.carrot2.org/algorithms.html for more information. - - lingo + A commercial algorithm Lingo3G (needs to be installed separately) is defined as: + * com.carrotsearch.lingo3g.Lingo3GClusteringAlgorithm + --> org.carrot2.clustering.lingo.LingoClusteringAlgorithm + + clustering/carrot2 + stc org.carrot2.clustering.stc.STCClusteringAlgorithm - clustering/carrot2 + kmeans org.carrot2.clustering.kmeans.BisectingKMeansClusteringAlgorithm - clustering/carrot2 - @@ -1305,14 +1489,14 @@ text^0.5 features^1.0 name^1.2 sku^1.5 id^10.0 manu^1.1 cat^1.4 *:* - 100 + 10 *,score clustering - + - - - - + + @@ -1648,22 +1821,11 @@ EditorialMarkerFactory will do exactly that: --> + - - - QUERY_DOC_FV - + + + *:* + diff --git a/src/test/resources/static-schema/core/schema/default_schema.json b/src/test/resources/static-schema/core/schema/default_schema.json index 8946f12..412b4f3 100644 --- a/src/test/resources/static-schema/core/schema/default_schema.json +++ b/src/test/resources/static-schema/core/schema/default_schema.json @@ -5,7 +5,7 @@ }, "schema": { "name": "example", - "version": 1.6, + "version": 1.5, "uniqueKey": "id", "fieldTypes": [ { diff --git a/template.mf b/template.mf new file mode 100644 index 0000000..99dbd62 --- /dev/null +++ b/template.mf @@ -0,0 +1,24 @@ +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: org.springframework.data.solr +Bundle-Name: ${project.name} +Bundle-Vendor: Pivotal Software, Inc. +Bundle-Version: ${project.version} +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Template: + org.springframework.data.solr.*;version="${project.version}" +Import-Template: + javax.enterprise.*;version="${cdi:[=.=.=,+1.0.0)}";resolution:=optional, + javax.xml.*;version="0.0.0", + javax.activation.*;version="0.0.0", + org.aopalliance.*;version="[1.0.0,2.0.0)", + org.apache.commons.collections.*;version="${commons.collections:[=.=.=,+1.0.0)}", + org.apache.commons.lang3.*;version="${commons.lang:[=.=.=,+1.0.0)}", + org.apache.http.*;version="${httpcomponents:[=.=.=,+1.0.0)}", + org.apache.solr.*;version="${solr:[=.=.=,+1.0.0)}", + org.joda.time.*;version="[1.5.0,2.0.0)";resolution:=optional, + org.slf4j.*;version="${slf4j:[=.=.=,+1.0.0)}", + org.springframework.*;version="${spring:[=.=.=.=,+1.0.0)}", + org.springframework.data.*;version="${springdata.commons:[=.=.=.=,+1.0.0)}", + org.w3c.*;version="0.0.0", + org.xml.sax.*;version="0.0.0", + com.fasterxml.jackson.*;version="${jackson}" From e4b0fc63244e691a06c9748c271eb4ba693e4c95 Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Wed, 29 Nov 2017 12:47:42 +0400 Subject: [PATCH 02/10] changes 2.1.8 for spring-solr-data branch From 62255d9aa11321d44caff81c536a1f1f039a16aa Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Wed, 29 Nov 2017 13:47:48 +0400 Subject: [PATCH 03/10] ReRank changes in Q Anotation --- .../data/solr/core/DefaultQueryParser.java | 18 +++++- .../core/query/AbstractQueryDecorator.java | 10 ++++ .../data/solr/core/query/Query.java | 16 ++++++ .../data/solr/core/query/SimpleQuery.java | 19 +++++++ .../data/solr/repository/Query.java | 2 + .../repository/query/AbstractSolrQuery.java | 15 +++++ .../repository/query/SolrQueryMethod.java | 55 +++++++++++++++++++ 7 files changed, 134 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java index e7b816f..ec49d0c 100644 --- a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java @@ -115,16 +115,32 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { appendTimeAllowed(solrQuery, query.getTimeAllowed()); appendDefType(solrQuery, query.getDefType()); appendRequestHandler(solrQuery, query.getRequestHandler()); - + appendReRankQueryHandler(solrQuery,query.getRqqValue()); + processGroupOptions(solrQuery, query); processStatsOptions(solrQuery, query); processSpellcheckOptions(solrQuery, query); + LOGGER.info("solrQuery.toQueryString() ================= "+ solrQuery.toQueryString()); + LOGGER.info("solrQuery.toString() == ========= " + solrQuery.toString()); + if (LOGGER.isDebugEnabled()) { LOGGER.debug("Constructed SolrQuery:\r\n %s", solrQuery); } } + /** + * @param solrQuery + * @param rqqValue + */ + private void appendReRankQueryHandler(SolrQuery solrQuery, String rqqValue) { + if(StringUtils.isNotBlank(rqqValue)) { + solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); + solrQuery.set("rqq", rqqValue); + } + } + + private void processFacetOptions(SolrQuery solrQuery, FacetQuery query) { if (enableFaceting(solrQuery, query)) { appendFacetingOnFields(solrQuery, (FacetQuery) query); diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java index 11c13a9..80ab502 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java @@ -58,6 +58,11 @@ public void setJoin(Join join) { public Join getJoin() { return this.query.getJoin(); } + + @Override + public String getRqqValue() { + return this.query.getRqqValue(); + } @Override public T addProjectionOnField(Field field) { @@ -154,6 +159,11 @@ public void setRequestHandler(String requestHandler) { public T setOffset(Integer offset) { return this.query.setOffset(offset); } + + @Override + public T setReRank(String rqqValue) { + return this.query.setReRank(rqqValue); + } @Override public T setRows(Integer rows) { diff --git a/src/main/java/org/springframework/data/solr/core/query/Query.java b/src/main/java/org/springframework/data/solr/core/query/Query.java index cfeb5b0..fed23ba 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Query.java +++ b/src/main/java/org/springframework/data/solr/core/query/Query.java @@ -177,6 +177,15 @@ public String toString() { * @return */ Integer getTimeAllowed(); + + /** + * Set the rerank value. + * + * @param offset + * @return + * @since 1.3 + */ + T setReRank(String rqqValue); /** * Set the default operator {@code q.op} for query expressions @@ -258,5 +267,12 @@ public String toString() { * @since 2.1 */ SpellcheckOptions getSpellcheckOptions(); + + /** + * Return the time (in milliseconds) allowed for a search to finish + * + * @return + */ + String getRqqValue(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java index abbc725..9b86e62 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java @@ -44,6 +44,7 @@ public class SimpleQuery extends AbstractQuery implements Query, FilterQuery { private Operator defaultOperator; private Integer timeAllowed; + private String rqqValue; private String defType; private GroupOptions groupOptions; @@ -385,4 +386,22 @@ public T setSpellcheckOptions(SpellcheckOptions spellcheckOpti public SpellcheckOptions getSpellcheckOptions() { return this.spellcheckOptions; } + + /* (non-Javadoc) + * @see org.springframework.data.solr.core.query.Query#setReRank(java.lang.String) + */ + @SuppressWarnings("unchecked") + @Override + public T setReRank(String rqqValue) { + this.rqqValue=rqqValue; + return (T) this; + } + + /* (non-Javadoc) + * @see org.springframework.data.solr.core.query.Query#getRqqValue() + */ + @Override + public String getRqqValue() { + return this.rqqValue; + } } diff --git a/src/main/java/org/springframework/data/solr/repository/Query.java b/src/main/java/org/springframework/data/solr/repository/Query.java index 9b8d80a..5d0327d 100644 --- a/src/main/java/org/springframework/data/solr/repository/Query.java +++ b/src/main/java/org/springframework/data/solr/repository/Query.java @@ -93,5 +93,7 @@ * @since 1.2 */ boolean delete() default false; + + String rqqValue() default ""; } diff --git a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java index 698dbe3..450d227 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java @@ -21,6 +21,8 @@ import java.util.regex.Pattern; import org.apache.solr.common.params.HighlightParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Page; @@ -73,6 +75,8 @@ public abstract class AbstractSolrQuery implements RepositoryQuery { private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); + + private static final Logger logger = LoggerFactory.getLogger(AbstractSolrQuery.class); private final SolrOperations solrOperations; private final SolrQueryMethod solrQueryMethod; @@ -126,6 +130,7 @@ public Object execute(Object[] parameters) { setDefTypeIfDefined(query); setRequestHandlerIfDefined(query); setSpellecheckOptionsWhenDefined(query); + setReRankIfDefined(query); if (solrQueryMethod.hasStatsDefinition()) { query.setStatsOptions(extractStatsOptions(solrQueryMethod, accessor)); @@ -168,6 +173,16 @@ public Object execute(Object[] parameters) { return new SingleEntityExecution().execute(query); } + /** + * @param query + */ + private void setReRankIfDefined(Query query) { + String rqqValue = query.getRqqValue(); + if(rqqValue!=null) { + query.setReRank(rqqValue); + } + } + @Override public SolrQueryMethod getQueryMethod() { return this.solrQueryMethod; diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java index 2be347e..c782f62 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java @@ -35,6 +35,7 @@ import org.springframework.data.solr.repository.Highlight; import org.springframework.data.solr.repository.Pivot; import org.springframework.data.solr.repository.Query; +import org.springframework.data.solr.repository.Rerank; import org.springframework.data.solr.repository.SelectiveStats; import org.springframework.data.solr.repository.Spellcheck; import org.springframework.data.solr.repository.Stats; @@ -125,6 +126,16 @@ public Integer getTimeAllowed() { } return null; } + + /** + * @return null if {@link Query#rqqValue()} is null or blank + */ + public String getRqqValue() { + if (hasQueryAnnotation()) { + return getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "rqqValue"); + } + return null; + } /** * @return true if {@link #hasFacetFields()} or {@link #hasFacetQueries()} @@ -217,6 +228,50 @@ public String getFacetPrefix() { return getAnnotationValueAsStringOrNullIfBlank(getFacetAnnotation(), "prefix"); } + + + // Rerank Anotation + + + /** + * @return the {@link Rerank} annotation, null if there is none + */ + private Rerank getRerankAnnotation() { + return this.method.getAnnotation(Rerank.class); + } + + private boolean hasRerankAnnotation() { + return getRerankAnnotation() != null; + } + + /** + * @return null if {@link Rerank#reRankDocs()} is null or negative + */ + public Integer getReRankDocs() { + if (hasRerankAnnotation()) { + return getAnnotationValueAsIntOrNullIfNegative(getRerankAnnotation(), "reRankDocs"); + } + return null; + } + + /** + * @return null if {@link Rerank#reRankWt()} is null or negative + */ + public Integer getReRankWt() { + if (hasRerankAnnotation()) { + return getAnnotationValueAsIntOrNullIfNegative(getRerankAnnotation(), "reRankWt"); + } + return null; + } + + /** + * @return null if {@link Rerank#value()} is null or blank + */ + public String getAnnotatedRerank() { + return getAnnotationValueAsStringOrNullIfBlank(getRerankAnnotation(), "value"); + } + + /** * @return the {@link Stats} annotation, null if there is none */ From f362c99b6d4e7cbe1e8d8cd8cb3beabaf56f662c Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Fri, 1 Dec 2017 13:31:56 +0400 Subject: [PATCH 04/10] Changes done with query ReRank taken care --- .../data/solr/core/DefaultQueryParser.java | 32 +++++++++++++++++++ .../core/query/AbstractQueryDecorator.java | 5 +-- .../data/solr/core/query/Query.java | 2 +- .../data/solr/core/query/SimpleQuery.java | 8 +++-- .../data/solr/core/query/SolrDataQuery.java | 2 +- .../repository/query/AbstractSolrQuery.java | 5 +-- 6 files changed, 46 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java index ec49d0c..8839429 100644 --- a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java @@ -92,8 +92,10 @@ public final SolrQuery doConstructSolrQuery(SolrDataQuery query) { Assert.notNull(query.getCriteria(), "Query has to have a criteria."); SolrQuery solrQuery = new SolrQuery(); + LOGGER.info("doConstructSolrQuery solrQuery.toString() == ========= " + solrQuery.toString()); solrQuery.setParam(CommonParams.Q, getQueryString(query)); if (query instanceof Query) { + //processQueryRqqOption(solrQuery,query); processQueryOptions(solrQuery, (Query) query); } if (query instanceof FacetQuery) { @@ -106,16 +108,31 @@ public final SolrQuery doConstructSolrQuery(SolrDataQuery query) { return solrQuery; } + private void processQueryRqqOption(SolrQuery solrQuery, SolrDataQuery query) { + appendReRankQueryHandler2(solrQuery,query); + } + private void processQueryOptions(SolrQuery solrQuery, Query query) { + LOGGER.info("query.toString() == ========= " + query.toString()); + LOGGER.info("solrQuery.toString() == ========= " + solrQuery.toString()); appendPagination(solrQuery, query.getOffset(), query.getRows()); + LOGGER.info("appendPagination solrQuery.toString() == ========= " + solrQuery.toString()); appendProjectionOnFields(solrQuery, query.getProjectionOnFields()); + LOGGER.info("appendProjectionOnFields solrQuery.toString() == ========= " + solrQuery.toString()); appendFilterQuery(solrQuery, query.getFilterQueries()); + LOGGER.info("appendFilterQuery solrQuery.toString() == ========= " + solrQuery.toString()); appendSort(solrQuery, query.getSort()); + LOGGER.info("appendSort solrQuery.toString() == ========= " + solrQuery.toString()); appendDefaultOperator(solrQuery, query.getDefaultOperator()); + LOGGER.info("appendDefaultOperator solrQuery.toString() == ========= " + solrQuery.toString()); appendTimeAllowed(solrQuery, query.getTimeAllowed()); + LOGGER.info("appendTimeAllowed solrQuery.toString() == ========= " + solrQuery.toString()); appendDefType(solrQuery, query.getDefType()); + LOGGER.info("appendDefType solrQuery.toString() == ========= " + solrQuery.toString()); appendRequestHandler(solrQuery, query.getRequestHandler()); + LOGGER.info("appendRequestHandler solrQuery.toString() == ========= " + solrQuery.toString()); appendReRankQueryHandler(solrQuery,query.getRqqValue()); + LOGGER.info("appendReRankQueryHandler solrQuery.toString() == ========= " + solrQuery.toString()); processGroupOptions(solrQuery, query); processStatsOptions(solrQuery, query); @@ -134,9 +151,24 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { * @param rqqValue */ private void appendReRankQueryHandler(SolrQuery solrQuery, String rqqValue) { + LOGGER.info("Inside appendReRankQueryHandler ==== " + rqqValue); if(StringUtils.isNotBlank(rqqValue)) { + LOGGER.info("Inside appendReRankQueryHandler and rqqValue is not blank with value : " + rqqValue); solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); solrQuery.set("rqq", rqqValue); + LOGGER.info("--------------------- solrQuery.toQueryString() =------------------"+solrQuery.toQueryString()); + } + } + + private void appendReRankQueryHandler2(SolrQuery solrQuery, SolrDataQuery query) { + String rqqValue = ((Query)query).getRqqValue(); + LOGGER.info("Inside appendReRankQueryHandler2 ==== " + rqqValue); + if(StringUtils.isNotBlank(rqqValue)) { + String realRqqValueFromQuery = getRqqValue(query); + LOGGER.info("Inside appendReRankQueryHandler2 and rqqValue is not blank with value : " + realRqqValueFromQuery); + solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); + solrQuery.set("rqq", realRqqValueFromQuery); + LOGGER.info("--------------------- solrQuery.toQueryString() =------------------"+solrQuery.toQueryString()); } } diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java index 80ab502..882ac82 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java @@ -161,8 +161,9 @@ public T setOffset(Integer offset) { } @Override - public T setReRank(String rqqValue) { - return this.query.setReRank(rqqValue); + public T setRqqValue(String rqqValue) { + logger.info("===================== T setRqqValue(String rqqValue)----------------" + rqqValue); + return this.query.setRqqValue(rqqValue); } @Override diff --git a/src/main/java/org/springframework/data/solr/core/query/Query.java b/src/main/java/org/springframework/data/solr/core/query/Query.java index fed23ba..5b02ae3 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Query.java +++ b/src/main/java/org/springframework/data/solr/core/query/Query.java @@ -185,7 +185,7 @@ public String toString() { * @return * @since 1.3 */ - T setReRank(String rqqValue); + T setRqqValue(String rqqValue); /** * Set the default operator {@code q.op} for query expressions diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java index 9b86e62..dba776c 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java @@ -133,7 +133,11 @@ public static T fromQuery(Query source, T destination) { if (source.getTimeAllowed() != null) { destination.setTimeAllowed(source.getTimeAllowed()); } - + + if (source.getRqqValue() != null) { + destination.setRqqValue(source.getRqqValue()); + } + if (source.getRequestHandler() != null) { destination.setRequestHandler(source.getRequestHandler()); } @@ -392,7 +396,7 @@ public SpellcheckOptions getSpellcheckOptions() { */ @SuppressWarnings("unchecked") @Override - public T setReRank(String rqqValue) { + public T setRqqValue(String rqqValue) { this.rqqValue=rqqValue; return (T) this; } diff --git a/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java b/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java index 9491685..25e2603 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SolrDataQuery.java @@ -26,7 +26,7 @@ public interface SolrDataQuery { * Append criteria to query. Criteria must not be null, nor point to a field with null value. * * @param criteria - * @return + * @return */ T addCriteria(Criteria criteria); diff --git a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java index 450d227..587b9c5 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java @@ -177,9 +177,10 @@ public Object execute(Object[] parameters) { * @param query */ private void setReRankIfDefined(Query query) { - String rqqValue = query.getRqqValue(); + logger.info(" void setReRankIfDefined(Query query)" + solrQueryMethod.toString()); + String rqqValue = solrQueryMethod.getRqqValue(); if(rqqValue!=null) { - query.setReRank(rqqValue); + query.setRqqValue(rqqValue); } } From 4d95098e306835474856eb1642a19c3db1bbdd9a Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Fri, 1 Dec 2017 13:33:24 +0400 Subject: [PATCH 05/10] done --- .../data/solr/core/DefaultQueryParser.java | 32 ------------------- .../data/solr/core/QueryParserBase.java | 24 +++++++++++++- .../core/query/AbstractQueryDecorator.java | 3 +- .../data/solr/core/query/SimpleQuery.java | 11 ++++++- .../repository/query/AbstractSolrQuery.java | 5 --- .../repository/query/SolrQueryMethod.java | 8 +++++ 6 files changed, 42 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java index 8839429..43dd2de 100644 --- a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java @@ -92,10 +92,8 @@ public final SolrQuery doConstructSolrQuery(SolrDataQuery query) { Assert.notNull(query.getCriteria(), "Query has to have a criteria."); SolrQuery solrQuery = new SolrQuery(); - LOGGER.info("doConstructSolrQuery solrQuery.toString() == ========= " + solrQuery.toString()); solrQuery.setParam(CommonParams.Q, getQueryString(query)); if (query instanceof Query) { - //processQueryRqqOption(solrQuery,query); processQueryOptions(solrQuery, (Query) query); } if (query instanceof FacetQuery) { @@ -108,31 +106,16 @@ public final SolrQuery doConstructSolrQuery(SolrDataQuery query) { return solrQuery; } - private void processQueryRqqOption(SolrQuery solrQuery, SolrDataQuery query) { - appendReRankQueryHandler2(solrQuery,query); - } - private void processQueryOptions(SolrQuery solrQuery, Query query) { - LOGGER.info("query.toString() == ========= " + query.toString()); - LOGGER.info("solrQuery.toString() == ========= " + solrQuery.toString()); appendPagination(solrQuery, query.getOffset(), query.getRows()); - LOGGER.info("appendPagination solrQuery.toString() == ========= " + solrQuery.toString()); appendProjectionOnFields(solrQuery, query.getProjectionOnFields()); - LOGGER.info("appendProjectionOnFields solrQuery.toString() == ========= " + solrQuery.toString()); appendFilterQuery(solrQuery, query.getFilterQueries()); - LOGGER.info("appendFilterQuery solrQuery.toString() == ========= " + solrQuery.toString()); appendSort(solrQuery, query.getSort()); - LOGGER.info("appendSort solrQuery.toString() == ========= " + solrQuery.toString()); appendDefaultOperator(solrQuery, query.getDefaultOperator()); - LOGGER.info("appendDefaultOperator solrQuery.toString() == ========= " + solrQuery.toString()); appendTimeAllowed(solrQuery, query.getTimeAllowed()); - LOGGER.info("appendTimeAllowed solrQuery.toString() == ========= " + solrQuery.toString()); appendDefType(solrQuery, query.getDefType()); - LOGGER.info("appendDefType solrQuery.toString() == ========= " + solrQuery.toString()); appendRequestHandler(solrQuery, query.getRequestHandler()); - LOGGER.info("appendRequestHandler solrQuery.toString() == ========= " + solrQuery.toString()); appendReRankQueryHandler(solrQuery,query.getRqqValue()); - LOGGER.info("appendReRankQueryHandler solrQuery.toString() == ========= " + solrQuery.toString()); processGroupOptions(solrQuery, query); processStatsOptions(solrQuery, query); @@ -151,28 +134,13 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { * @param rqqValue */ private void appendReRankQueryHandler(SolrQuery solrQuery, String rqqValue) { - LOGGER.info("Inside appendReRankQueryHandler ==== " + rqqValue); if(StringUtils.isNotBlank(rqqValue)) { LOGGER.info("Inside appendReRankQueryHandler and rqqValue is not blank with value : " + rqqValue); solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); solrQuery.set("rqq", rqqValue); - LOGGER.info("--------------------- solrQuery.toQueryString() =------------------"+solrQuery.toQueryString()); } } - private void appendReRankQueryHandler2(SolrQuery solrQuery, SolrDataQuery query) { - String rqqValue = ((Query)query).getRqqValue(); - LOGGER.info("Inside appendReRankQueryHandler2 ==== " + rqqValue); - if(StringUtils.isNotBlank(rqqValue)) { - String realRqqValueFromQuery = getRqqValue(query); - LOGGER.info("Inside appendReRankQueryHandler2 and rqqValue is not blank with value : " + realRqqValueFromQuery); - solrQuery.set("rq", "{!rerank reRankQuery=$rqq reRankDocs=1000 reRankWeight=3}"); - solrQuery.set("rqq", realRqqValueFromQuery); - LOGGER.info("--------------------- solrQuery.toQueryString() =------------------"+solrQuery.toQueryString()); - } - } - - private void processFacetOptions(SolrQuery solrQuery, FacetQuery query) { if (enableFaceting(solrQuery, query)) { appendFacetingOnFields(solrQuery, (FacetQuery) query); diff --git a/src/main/java/org/springframework/data/solr/core/QueryParserBase.java b/src/main/java/org/springframework/data/solr/core/QueryParserBase.java index cf1bbff..2e013d5 100644 --- a/src/main/java/org/springframework/data/solr/core/QueryParserBase.java +++ b/src/main/java/org/springframework/data/solr/core/QueryParserBase.java @@ -28,6 +28,8 @@ import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.SpatialParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.data.geo.Box; @@ -72,6 +74,8 @@ public abstract class QueryParserBase implement protected static final String DELIMINATOR = ":"; protected static final String NOT = "-"; protected static final String BOOST = "^"; + + private final Logger log = LoggerFactory.getLogger(QueryParserBase.class); protected final GenericConversionService conversionService = new GenericConversionService(); private final List critieraEntryProcessors = new ArrayList(); @@ -110,12 +114,30 @@ public abstract class QueryParserBase implement @Override public String getQueryString(SolrDataQuery query) { + log.info("query.toString()" + query.toString()); if (query.getCriteria() == null) { return null; } - + log.info("query.getCriteria() ============" + query.getCriteria().toString()); String queryString = createQueryStringFromNode(query.getCriteria()); + if(queryString != null && queryString.indexOf("rqq")>-1) + queryString = queryString.substring(0,queryString.indexOf("rqq")); + log.info("===========queryString==========" + queryString); queryString = prependJoin(queryString, query); + log.info("------------queryString-------------" + queryString); + return queryString; + } + + public String getRqqValue(SolrDataQuery query) { + log.info("query.toString()" + query.toString()); + if (query.getCriteria() == null) { + return null; + } + log.info("query.getCriteria() ============" + query.getCriteria().toString()); + String queryString = createQueryStringFromNode(query.getCriteria()); + int indexOfRqq = queryString.indexOf("rqq"); + if(queryString != null && indexOfRqq > -1 && indexOfRqq+4 < queryString.length()) + queryString = queryString.substring(indexOfRqq+4); return queryString; } diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java index 882ac82..f8c0623 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java @@ -30,7 +30,7 @@ * @since 1.4 */ public abstract class AbstractQueryDecorator implements Query { - + private Query query; public AbstractQueryDecorator(Query query) { @@ -162,7 +162,6 @@ public T setOffset(Integer offset) { @Override public T setRqqValue(String rqqValue) { - logger.info("===================== T setRqqValue(String rqqValue)----------------" + rqqValue); return this.query.setRqqValue(rqqValue); } diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java index dba776c..b4f6e2b 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java @@ -19,6 +19,8 @@ import java.util.Collections; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.util.Assert; @@ -33,6 +35,8 @@ * @author Francisco Spaeth */ public class SimpleQuery extends AbstractQuery implements Query, FilterQuery { + + private static final Logger logger = LoggerFactory.getLogger(SimpleQuery.class); private List projectionOnFields = new ArrayList(0); private List filterQueries = new ArrayList(0);; @@ -96,6 +100,7 @@ public static final Query fromQuery(Query source) { } public static T fromQuery(Query source, T destination) { + logger.info("--------- T fromQuery(Query source, T destination)-------------"); if (source == null || destination == null) { return null; } @@ -251,7 +256,7 @@ public Sort getSort() { @Override public Pageable getPageRequest() { - + logger.info("---------Pageable getPageRequest()-------------"); if (this.rows == null && this.offset == null) { return null; } @@ -296,12 +301,14 @@ public T addFilterQuery(FilterQuery filterQuery) { @SuppressWarnings("unchecked") @Override public T setTimeAllowed(Integer timeAllowed) { + logger.info("-------------- T setTimeAllowed(Integer timeAllowed) ----------------"); this.timeAllowed = timeAllowed; return (T) this; } @Override public Integer getTimeAllowed() { + logger.info("-------------- Integer getTimeAllowed() ----------------"); return this.timeAllowed; } @@ -397,6 +404,7 @@ public SpellcheckOptions getSpellcheckOptions() { @SuppressWarnings("unchecked") @Override public T setRqqValue(String rqqValue) { + logger.info("-------------- T setRqqValue(String rqqValue) ----------------"); this.rqqValue=rqqValue; return (T) this; } @@ -406,6 +414,7 @@ public T setRqqValue(String rqqValue) { */ @Override public String getRqqValue() { + logger.info("--------------String getRqqValue() ----------------"); return this.rqqValue; } } diff --git a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java index 587b9c5..f67f458 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java +++ b/src/main/java/org/springframework/data/solr/repository/query/AbstractSolrQuery.java @@ -21,8 +21,6 @@ import java.util.regex.Pattern; import org.apache.solr.common.params.HighlightParams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Page; @@ -76,8 +74,6 @@ public abstract class AbstractSolrQuery implements RepositoryQuery { private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); - private static final Logger logger = LoggerFactory.getLogger(AbstractSolrQuery.class); - private final SolrOperations solrOperations; private final SolrQueryMethod solrQueryMethod; @@ -177,7 +173,6 @@ public Object execute(Object[] parameters) { * @param query */ private void setReRankIfDefined(Query query) { - logger.info(" void setReRankIfDefined(Query query)" + solrQueryMethod.toString()); String rqqValue = solrQueryMethod.getRqqValue(); if(rqqValue!=null) { query.setRqqValue(rqqValue); diff --git a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java index c782f62..1aeaea9 100644 --- a/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java +++ b/src/main/java/org/springframework/data/solr/repository/query/SolrQueryMethod.java @@ -25,6 +25,8 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.data.projection.ProjectionFactory; @@ -54,6 +56,8 @@ * @author Francisco Spaeth */ public class SolrQueryMethod extends QueryMethod { + + private static final Logger logger = LoggerFactory.getLogger(SolrQueryMethod.class); private final Method method; @@ -131,7 +135,10 @@ public Integer getTimeAllowed() { * @return null if {@link Query#rqqValue()} is null or blank */ public String getRqqValue() { + logger.info("hasQueryAnnotation ==" + hasQueryAnnotation()); if (hasQueryAnnotation()) { + String res = getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "rqqValue"); + logger.info("SolrQueryMethod :: Inside getAnnotatedNamedQueryName ========== " + res); return getAnnotationValueAsStringOrNullIfBlank(getQueryAnnotation(), "rqqValue"); } return null; @@ -576,6 +583,7 @@ public SpellcheckOptions getSpellcheckOptions() { private String getAnnotationValueAsStringOrNullIfBlank(Annotation annotation, String attributeName) { String value = (String) AnnotationUtils.getValue(annotation, attributeName); + logger.info("value ======= " + value); return StringUtils.hasText(value) ? value : null; } From 8c27b9bcb2741bb9687485ce5c14eb4ba6bccf7b Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Tue, 5 Dec 2017 09:03:30 +0400 Subject: [PATCH 06/10] Spatial Search changes --- .../data/solr/core/DefaultQueryParser.java | 18 ++++++++ .../data/solr/core/ResultHelper.java | 25 +++++++++++ .../core/query/AbstractQueryDecorator.java | 14 ++++++ .../data/solr/core/query/Query.java | 4 ++ .../data/solr/core/query/SimpleQuery.java | 19 ++++++++ .../solr/core/query/SpatialSearchOptions.java | 43 +++++++++++++++++++ 6 files changed, 123 insertions(+) create mode 100644 src/main/java/org/springframework/data/solr/core/query/SpatialSearchOptions.java diff --git a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java index 43dd2de..2e83702 100644 --- a/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java +++ b/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java @@ -29,6 +29,7 @@ import org.apache.solr.common.params.GroupParams; import org.apache.solr.common.params.HighlightParams; import org.apache.solr.common.params.ModifiableSolrParams; +import org.apache.solr.common.params.SpatialParams; import org.apache.solr.common.params.SpellingParams; import org.apache.solr.common.params.StatsParams; import org.slf4j.Logger; @@ -55,6 +56,7 @@ import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.QueryParameter; import org.springframework.data.solr.core.query.SolrDataQuery; +import org.springframework.data.solr.core.query.SpatialSearchOptions; import org.springframework.data.solr.core.query.SpellcheckOptions; import org.springframework.data.solr.core.query.StatsOptions; import org.springframework.util.Assert; @@ -120,6 +122,7 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { processGroupOptions(solrQuery, query); processStatsOptions(solrQuery, query); processSpellcheckOptions(solrQuery, query); + processSpatialSearchOptions(solrQuery,query); LOGGER.info("solrQuery.toQueryString() ================= "+ solrQuery.toQueryString()); LOGGER.info("solrQuery.toString() == ========= " + solrQuery.toString()); @@ -129,6 +132,21 @@ private void processQueryOptions(SolrQuery solrQuery, Query query) { } } + /** + * @param solrQuery + * @param query + */ + private void processSpatialSearchOptions(SolrQuery solrQuery, Query query) { + SpatialSearchOptions spatialOptions = query.getSpatialSearchOptions(); + if(spatialOptions == null || StringUtils.isBlank(spatialOptions.getField()) || StringUtils.isBlank(spatialOptions.getPoint()) || StringUtils.split(spatialOptions.getPoint(), ",").length!=2) { + return; + } + + solrQuery.set(SpatialParams.FIELD, spatialOptions.getField()); + solrQuery.set(SpatialParams.DISTANCE, spatialOptions.getDistance()); + solrQuery.set(SpatialParams.POINT, spatialOptions.getPoint()); + } + /** * @param solrQuery * @param rqqValue diff --git a/src/main/java/org/springframework/data/solr/core/ResultHelper.java b/src/main/java/org/springframework/data/solr/core/ResultHelper.java index b21fe1d..71ffa46 100644 --- a/src/main/java/org/springframework/data/solr/core/ResultHelper.java +++ b/src/main/java/org/springframework/data/solr/core/ResultHelper.java @@ -34,6 +34,7 @@ import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.RangeFacet; import org.apache.solr.client.solrj.response.SpellCheckResponse; +import org.apache.solr.client.solrj.response.SuggesterResponse; import org.apache.solr.client.solrj.response.TermsResponse; import org.apache.solr.client.solrj.response.TermsResponse.Term; import org.apache.solr.common.SolrDocumentList; @@ -87,6 +88,30 @@ final class ResultHelper { private ResultHelper() {} + +// static Map> convertSuggesterQueryResponseToSuggesterMap(QueryResponse response) { +// if (response == null || response.getTermsResponse() == null || response.getTermsResponse().getTermMap() == null) { +// return Collections.emptyMap(); +// } +// +// SuggesterResponse suggesterResponse = response.getSuggesterResponse(); +// Map> result = new LinkedHashMap>( +// termsResponse.getTermMap().size()); +// +// for (Map.Entry> entry : termsResponse.getTermMap().entrySet()) { +// List terms = new ArrayList(entry.getValue().size()); +// for (Term term : entry.getValue()) { +// SimpleTermsFieldEntry termsEntry = new SimpleTermsFieldEntry(term.getTerm(), term.getFrequency()); +// termsEntry.setField(entry.getKey()); +// terms.add(termsEntry); +// } +// result.put(entry.getKey(), terms); +// } +// +// return result; +// } + + static Map> convertTermsQueryResponseToTermsMap(QueryResponse response) { if (response == null || response.getTermsResponse() == null || response.getTermsResponse().getTermMap() == null) { return Collections.emptyMap(); diff --git a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java index f8c0623..126e97f 100644 --- a/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java +++ b/src/main/java/org/springframework/data/solr/core/query/AbstractQueryDecorator.java @@ -225,6 +225,20 @@ public T setSpellcheckOptions(SpellcheckOptions spellcheckOpti public SpellcheckOptions getSpellcheckOptions() { return query.getSpellcheckOptions(); } + + @Override + public T setSpatialSearchOptions(SpatialSearchOptions spatialSearchOptions) { + return query.setSpatialSearchOptions(spatialSearchOptions); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.solr.core.query.Query#getSpellcheckOptions() + */ + @Override + public SpatialSearchOptions getSpatialSearchOptions() { + return query.getSpatialSearchOptions(); + } /** * Get the {@link Class} of the originally decorated query. diff --git a/src/main/java/org/springframework/data/solr/core/query/Query.java b/src/main/java/org/springframework/data/solr/core/query/Query.java index 5b02ae3..fc68d61 100644 --- a/src/main/java/org/springframework/data/solr/core/query/Query.java +++ b/src/main/java/org/springframework/data/solr/core/query/Query.java @@ -274,5 +274,9 @@ public String toString() { * @return */ String getRqqValue(); + + T setSpatialSearchOptions(SpatialSearchOptions spatialSearchOptions); + + SpatialSearchOptions getSpatialSearchOptions(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java index b4f6e2b..a2f07fa 100644 --- a/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleQuery.java @@ -54,6 +54,7 @@ public class SimpleQuery extends AbstractQuery implements Query, FilterQuery { private GroupOptions groupOptions; private StatsOptions statsOptions; private SpellcheckOptions spellcheckOptions; + private SpatialSearchOptions spatialSearchOptions; public SimpleQuery() {} @@ -417,4 +418,22 @@ public String getRqqValue() { logger.info("--------------String getRqqValue() ----------------"); return this.rqqValue; } + + /* (non-Javadoc) + * @see org.springframework.data.solr.core.query.Query#setSpatialSearchOptions(org.springframework.data.solr.core.query.SpatialSearchOptions) + */ + @SuppressWarnings("unchecked") + @Override + public T setSpatialSearchOptions(SpatialSearchOptions spatialSearchOptions) { + this.spatialSearchOptions = spatialSearchOptions; + return (T) this; + } + + /* (non-Javadoc) + * @see org.springframework.data.solr.core.query.Query#getSpatialSearchOptions() + */ + @Override + public SpatialSearchOptions getSpatialSearchOptions() { + return this.spatialSearchOptions; + } } diff --git a/src/main/java/org/springframework/data/solr/core/query/SpatialSearchOptions.java b/src/main/java/org/springframework/data/solr/core/query/SpatialSearchOptions.java new file mode 100644 index 0000000..bd02e40 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/SpatialSearchOptions.java @@ -0,0 +1,43 @@ +package org.springframework.data.solr.core.query; + +/** + * @author navneetgupta + * @createdOn Dec 1, 2017 + */ +public class SpatialSearchOptions { + private static final int DEFAULT_D=100; + + private int distance = DEFAULT_D; + private String field; + private String point; + + public SpatialSearchOptions() { + super(); + } + public SpatialSearchOptions(int distance, String field, String point) { + super(); + this.distance = distance; + this.field = field; + this.point = point; + } + + public int getDistance() { + return distance; + } + public void setDistance(int distance) { + this.distance = distance; + } + public String getField() { + return field; + } + public void setField(String field) { + this.field = field; + } + public String getPoint() { + return point; + } + public void setPoint(String point) { + this.point = point; + } + +} From 914c9306610ff0db863c396a51e63957c68b8748 Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Tue, 5 Dec 2017 09:28:22 +0400 Subject: [PATCH 07/10] Suggester branch change --- .../data/solr/core/query/result/SuggesterResultPage.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java new file mode 100644 index 0000000..f6e4feb --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java @@ -0,0 +1,9 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SuggesterResultPage { + +} From b9252d18956966105ca8f11e2671d4ffffcb9b65 Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Tue, 5 Dec 2017 17:51:55 +0400 Subject: [PATCH 08/10] changes autoSuggest feature --- .../data/solr/core/QueryParsers.java | 5 +- .../data/solr/core/ResultHelper.java | 44 ++++----- .../data/solr/core/SolrOperations.java | 29 ++++++ .../data/solr/core/SolrTemplate.java | 27 ++++++ .../data/solr/core/SuggestQueryParser.java | 63 +++++++++++++ .../solr/core/query/SimpleSuggestQuery.java | 90 +++++++++++++++++++ .../data/solr/core/query/SuggestOptions.java | 31 +++++++ .../data/solr/core/query/SuggestQuery.java | 30 +++++++ .../query/result/DictionarySuggestEntry.java | 27 ++++++ .../result/SimpleSuggestDictionaryEntry.java | 27 ++++++ .../solr/core/query/result/SuggestEntry.java | 30 +++++++ .../solr/core/query/result/SuggestPage.java | 9 ++ .../query/result/SuggesterResultPage.java | 2 +- 13 files changed, 390 insertions(+), 24 deletions(-) create mode 100644 src/main/java/org/springframework/data/solr/core/SuggestQueryParser.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/SimpleSuggestQuery.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/SuggestOptions.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/SuggestQuery.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java diff --git a/src/main/java/org/springframework/data/solr/core/QueryParsers.java b/src/main/java/org/springframework/data/solr/core/QueryParsers.java index 689c702..7addf83 100644 --- a/src/main/java/org/springframework/data/solr/core/QueryParsers.java +++ b/src/main/java/org/springframework/data/solr/core/QueryParsers.java @@ -25,6 +25,7 @@ import org.springframework.data.solr.core.query.HighlightQuery; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SolrDataQuery; +import org.springframework.data.solr.core.query.SuggestQuery; import org.springframework.data.solr.core.query.TermsQuery; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; @@ -41,8 +42,8 @@ public class QueryParsers { private final Map, QueryParser> cache = new LinkedHashMap, QueryParser>(); public QueryParsers() { - this.parserPairs = new ArrayList(4); - + this.parserPairs = new ArrayList(5); + parserPairs.add(new QueryParserPair(SuggestQuery.class, new SuggestQueryParser())); parserPairs.add(new QueryParserPair(TermsQuery.class, new TermsQueryParser())); parserPairs.add(new QueryParserPair(FacetQuery.class, DEFAULT_QUERY_PARSER)); parserPairs.add(new QueryParserPair(HighlightQuery.class, DEFAULT_QUERY_PARSER)); diff --git a/src/main/java/org/springframework/data/solr/core/ResultHelper.java b/src/main/java/org/springframework/data/solr/core/ResultHelper.java index 71ffa46..958951c 100644 --- a/src/main/java/org/springframework/data/solr/core/ResultHelper.java +++ b/src/main/java/org/springframework/data/solr/core/ResultHelper.java @@ -35,6 +35,7 @@ import org.apache.solr.client.solrj.response.RangeFacet; import org.apache.solr.client.solrj.response.SpellCheckResponse; import org.apache.solr.client.solrj.response.SuggesterResponse; +import org.apache.solr.client.solrj.response.Suggestion; import org.apache.solr.client.solrj.response.TermsResponse; import org.apache.solr.client.solrj.response.TermsResponse.Term; import org.apache.solr.common.SolrDocumentList; @@ -67,6 +68,7 @@ import org.springframework.data.solr.core.query.result.SimpleGroupEntry; import org.springframework.data.solr.core.query.result.SimpleGroupResult; import org.springframework.data.solr.core.query.result.SimpleStatsResult; +import org.springframework.data.solr.core.query.result.SimpleSuggestDictionaryEntry; import org.springframework.data.solr.core.query.result.SimpleTermsFieldEntry; import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; @@ -89,27 +91,27 @@ final class ResultHelper { private ResultHelper() {} -// static Map> convertSuggesterQueryResponseToSuggesterMap(QueryResponse response) { -// if (response == null || response.getTermsResponse() == null || response.getTermsResponse().getTermMap() == null) { -// return Collections.emptyMap(); -// } -// -// SuggesterResponse suggesterResponse = response.getSuggesterResponse(); -// Map> result = new LinkedHashMap>( -// termsResponse.getTermMap().size()); -// -// for (Map.Entry> entry : termsResponse.getTermMap().entrySet()) { -// List terms = new ArrayList(entry.getValue().size()); -// for (Term term : entry.getValue()) { -// SimpleTermsFieldEntry termsEntry = new SimpleTermsFieldEntry(term.getTerm(), term.getFrequency()); -// termsEntry.setField(entry.getKey()); -// terms.add(termsEntry); -// } -// result.put(entry.getKey(), terms); -// } -// -// return result; -// } + static Map> convertSuggesterQueryResponseToSuggesterMap(QueryResponse response) { + if (response == null || response.getSuggesterResponse() == null || response.getSuggesterResponse().getSuggestions() == null) { + return Collections.emptyMap(); + } + + SuggesterResponse suggesterResponse = response.getSuggesterResponse(); + Map> result = new LinkedHashMap>( + suggesterResponse.getSuggestions().size()); + + for (Map.Entry> entry : suggesterResponse.getSuggestions().entrySet()) { + List terms = new ArrayList(entry.getValue().size()); + for (Suggestion term : entry.getValue()) { + SimpleSuggestDictionaryEntry suggestionEntry = new SimpleSuggestDictionaryEntry(term.getTerm(), term.getWeight(),term.getPayload()); + suggestionEntry.setDictionaryName(entry.getKey()); + terms.add(suggestionEntry); + } + result.put(entry.getKey(), terms); + } + + return result; + } static Map> convertTermsQueryResponseToTermsMap(QueryResponse response) { diff --git a/src/main/java/org/springframework/data/solr/core/SolrOperations.java b/src/main/java/org/springframework/data/solr/core/SolrOperations.java index 4a68b99..9097285 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrOperations.java +++ b/src/main/java/org/springframework/data/solr/core/SolrOperations.java @@ -29,6 +29,7 @@ import org.springframework.data.solr.core.query.HighlightQuery; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SolrDataQuery; +import org.springframework.data.solr.core.query.SuggestQuery; import org.springframework.data.solr.core.query.TermsQuery; import org.springframework.data.solr.core.query.result.Cursor; import org.springframework.data.solr.core.query.result.FacetAndHighlightPage; @@ -544,6 +545,34 @@ FacetAndHighlightPage queryForFacetAndHighlightPage(String collectionName * @return */ TermsPage queryForTermsPage(TermsQuery query); + + /** + * Execute query using suggest handler + * + * @param query must not be {@literal null}. + * @return + */ + Object queryForSuggesterPage(SuggestQuery query); + + /** + * Execute query using suggest against given collection. + * + * @param collectionName must not be {@literal null}. + * @param query must not be {@literal null}. + * @return + * @since 2.1 + */ + Object queryForSuggesterPage(String collectionName, SuggestQuery query); + + /** + * Execute query using suggest handler + * + * @param query must not be {@literal null}. + * @param method must not be {@literal null}. + * @return + * @since 2.0 + */ + Object queryForSuggesterPage(SuggestQuery query, RequestMethod method); /** * Execute query using terms handler against given collection. diff --git a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java index 5827fa3..4bd45eb 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java @@ -65,6 +65,7 @@ import org.springframework.data.solr.core.query.HighlightQuery; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SolrDataQuery; +import org.springframework.data.solr.core.query.SuggestQuery; import org.springframework.data.solr.core.query.TermsQuery; import org.springframework.data.solr.core.query.result.Cursor; import org.springframework.data.solr.core.query.result.DelegatingCursor; @@ -992,6 +993,32 @@ public TermsPage queryForTermsPage(String collectionName, TermsQuery query, Requ page.addAllTerms(ResultHelper.convertTermsQueryResponseToTermsMap(response)); return page; } + + @Override + public Object queryForSuggesterPage(SuggestQuery query) { + return queryForSuggesterPage(query, getDefaultRequestMethod()); + } + + @Override + public Object queryForSuggesterPage(String collectionName, SuggestQuery query) { + return queryForSuggesterPage(collectionName, query, getDefaultRequestMethod()); + } + + @Override + public Object queryForSuggesterPage(SuggestQuery query, RequestMethod method) { + return queryForSuggesterPage(null, query, method); + } + + public Object queryForSuggesterPage(String collectionName, SuggestQuery query, RequestMethod method) { + + Assert.notNull(query, "Query must not be 'null'."); + + QueryResponse response = querySolr(collectionName, query, null, method); + +// TermsResultPage page = new TermsResultPage(); +// page.addAllTerms(ResultHelper.convertTermsQueryResponseToTermsMap(response)); + return ResultHelper.convertSuggesterQueryResponseToSuggesterMap(response); + } final QueryResponse querySolr(String collectionName, SolrDataQuery query, Class clazz) { return querySolr(collectionName, query, clazz, defaultRequestMethod); diff --git a/src/main/java/org/springframework/data/solr/core/SuggestQueryParser.java b/src/main/java/org/springframework/data/solr/core/SuggestQueryParser.java new file mode 100644 index 0000000..6edf159 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/SuggestQueryParser.java @@ -0,0 +1,63 @@ +package org.springframework.data.solr.core; + +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.common.params.CommonParams; +import org.springframework.data.solr.core.query.Field; +import org.springframework.data.solr.core.query.SuggestOptions; +import org.springframework.data.solr.core.query.SuggestQuery; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SuggestQueryParser extends QueryParserBase{ + + private static final String SUGGEST="suggest"; + private static final String SUGGEST_COUNT="suggest.count"; + private static final String SUGGEST_DICTIONARY="suggest.dictionary"; + private static final String Q="suggest.q"; + + @Override + public SolrQuery doConstructSolrQuery(SuggestQuery query) { + Assert.notNull(query, "Cannot construct solrQuery from null value."); + + SolrQuery solrQuery = new SolrQuery(); + String queryString = getQueryString(query); + if (StringUtils.hasText(queryString)) { + solrQuery.setParam(CommonParams.Q, queryString); + } + appendSuggestOptionsToSolrQuery(query.getSuggestOptions(), solrQuery); + processSuggestDictionary(solrQuery, query); + appendRequestHandler(solrQuery, query.getRequestHandler()); + return solrQuery; + } + + /** + * @param solrQuery + * @param query + */ + private void processSuggestDictionary(SolrQuery solrQuery, SuggestQuery query) { + for (String dictionary : query.getSuggestDictionary()) { + appendSuggestDictionaryToSolrQuery(dictionary, solrQuery); + } + } + + /** + * @param suggestOptions + * @param solrQuery + */ + private void appendSuggestOptionsToSolrQuery(SuggestOptions suggestOptions, SolrQuery solrQuery) { + solrQuery.setParam(SUGGEST, true); + solrQuery.setParam(SUGGEST_COUNT, suggestOptions.getCount()+""); + solrQuery.setParam(Q, suggestOptions.getQ()); + } + + protected void appendSuggestDictionaryToSolrQuery(String dictionary, SolrQuery solrQuery) { + if (dictionary != null && StringUtils.hasText(dictionary)) { + solrQuery.add(SUGGEST_DICTIONARY, dictionary); + } + } + +} diff --git a/src/main/java/org/springframework/data/solr/core/query/SimpleSuggestQuery.java b/src/main/java/org/springframework/data/solr/core/query/SimpleSuggestQuery.java new file mode 100644 index 0000000..0bc872f --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/SimpleSuggestQuery.java @@ -0,0 +1,90 @@ +package org.springframework.data.solr.core.query; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.springframework.util.StringUtils; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SimpleSuggestQuery extends AbstractQuery implements SuggestQuery { + + public static final String DEFAULT_REQUEST_HANDLER = "/suggest"; + + private List dictionaries = new ArrayList(1); + private SuggestOptions suggestOptions = new SuggestOptions(); + + public SimpleSuggestQuery() { + super(); + } + + public void addDictionary(String dictionary) { + this.dictionaries.add(dictionary); + } + + public void addDictionaries(String... dictionaries) { + for (String dictionary : dictionaries) { + addDictionary(dictionary); + } + } + + @Override + public List getSuggestDictionary() { + return Collections.unmodifiableList(this.dictionaries); + } + + @Override + public String getRequestHandler() { + return StringUtils.hasText(super.getRequestHandler()) ? super.getRequestHandler() : DEFAULT_REQUEST_HANDLER; + } + + public static Builder queryBuilder() { + return new Builder(); + } + + public static Builder queryBuilder(String... fieldnames) { + return new Builder(fieldnames); + } + + public static class Builder { + + private SimpleSuggestQuery query; + + public Builder() { + this.query = new SimpleSuggestQuery(); + } + + public Builder(String... dictionaries) { + this.query = new SimpleSuggestQuery(); + this.query.addDictionaries(dictionaries); + } + + public Builder withCriteria(Criteria criteria) { + this.query.addCriteria(criteria); + return this; + } + + public Builder q(String q) { + this.query.suggestOptions.setQ(q); + return this; + } + + public Builder count(int count) { + this.query.suggestOptions.setCount(count); + return this; + } + + public SimpleSuggestQuery build() { + return this.query; + } + } + + @Override + public SuggestOptions getSuggestOptions() { + return this.suggestOptions; + } + +} diff --git a/src/main/java/org/springframework/data/solr/core/query/SuggestOptions.java b/src/main/java/org/springframework/data/solr/core/query/SuggestOptions.java new file mode 100644 index 0000000..2e518a8 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/SuggestOptions.java @@ -0,0 +1,31 @@ +package org.springframework.data.solr.core.query; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SuggestOptions { + private boolean suggest=true; + private String q; + private long count=10; + //private String cfq; + + public boolean isSuggest() { + return suggest; + } + public void setSuggest(boolean suggest) { + this.suggest = suggest; + } + public String getQ() { + return q; + } + public void setQ(String q) { + this.q = q; + } + public long getCount() { + return count; + } + public void setCount(long count) { + this.count = count; + } +} \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/core/query/SuggestQuery.java b/src/main/java/org/springframework/data/solr/core/query/SuggestQuery.java new file mode 100644 index 0000000..5aed03b --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/SuggestQuery.java @@ -0,0 +1,30 @@ +package org.springframework.data.solr.core.query; + +import java.util.List; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public interface SuggestQuery extends SolrDataQuery { + + /** + * @return null if not set + */ + SuggestOptions getSuggestOptions(); + + /** + * @return fields included + */ + List getSuggestDictionary(); + + /** + * Returns the request handler. + */ + String getRequestHandler(); + + /** + * Sets the request handler. + */ + void setRequestHandler(String requestHandler); +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java new file mode 100644 index 0000000..30827ee --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java @@ -0,0 +1,27 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class DictionarySuggestEntry extends SuggestEntry { + + private String dictionaryName; + + public DictionarySuggestEntry(String term, long weight, String payload) { + super(term, weight, payload); + } + + public DictionarySuggestEntry(String term, long weight, String payload, String dictionaryName) { + super(term, weight, payload); + this.dictionaryName = dictionaryName; + } + + public String getDictionaryName() { + return dictionaryName; + } + + public void setDictionaryName(String dictionaryName) { + this.dictionaryName = dictionaryName; + } +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java new file mode 100644 index 0000000..1334b23 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java @@ -0,0 +1,27 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SimpleSuggestDictionaryEntry extends DictionarySuggestEntry { + + /** + * @param term + * @param weight + * @param payload + */ + public SimpleSuggestDictionaryEntry(String term, long weight, String payload) { + super(term, weight, payload); + } + + /** + * @param term + * @param weight + * @param payload + */ + public SimpleSuggestDictionaryEntry(String dictionaryName, String term, long weight, String payload) { + super(term, weight, payload); + setDictionaryName(dictionaryName); + } +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java new file mode 100644 index 0000000..9b75772 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java @@ -0,0 +1,30 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class SuggestEntry { + private final String term; + private final long weight; + private final String payload; + + public SuggestEntry(String term, long weight, String payload) { + super(); + this.term = term; + this.weight = weight; + this.payload = payload; + } + + public String getTerm() { + return term; + } + + public long getWeight() { + return weight; + } + + public String getPayload() { + return payload; + } +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java new file mode 100644 index 0000000..d5dca05 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java @@ -0,0 +1,9 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public interface SuggestPage { + +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java index f6e4feb..38d6ce1 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java @@ -5,5 +5,5 @@ * @createdOn Dec 5, 2017 */ public class SuggesterResultPage { - + } From 0371a66cb9a3b9de516d9d60a1d5499c8bec09c4 Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Wed, 6 Dec 2017 09:11:56 +0400 Subject: [PATCH 09/10] SuggestComonent changes similar classes to terms --- .../data/solr/core/ResultHelper.java | 12 ++-- .../data/solr/core/SolrTemplate.java | 16 +++-- .../query/result/DictionarySuggestEntry.java | 38 +++++----- .../result/DictionaryWeightTermEntry.java | 30 ++++++++ .../result/SimpleSuggestDictionaryEntry.java | 17 +++-- .../query/result/SuggestDictionaryEntry.java | 12 ++++ .../solr/core/query/result/SuggestEntry.java | 25 +------ .../solr/core/query/result/SuggestPage.java | 25 ++++++- .../query/result/SuggesterResultPage.java | 70 ++++++++++++++++++- .../solr/core/query/result/WeightEntry.java | 11 +++ .../core/query/result/WeightTermEntry.java | 27 +++++++ 11 files changed, 218 insertions(+), 65 deletions(-) create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/DictionaryWeightTermEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/SuggestDictionaryEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/WeightEntry.java create mode 100644 src/main/java/org/springframework/data/solr/core/query/result/WeightTermEntry.java diff --git a/src/main/java/org/springframework/data/solr/core/ResultHelper.java b/src/main/java/org/springframework/data/solr/core/ResultHelper.java index 958951c..c64c282 100644 --- a/src/main/java/org/springframework/data/solr/core/ResultHelper.java +++ b/src/main/java/org/springframework/data/solr/core/ResultHelper.java @@ -73,6 +73,7 @@ import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; import org.springframework.data.solr.core.query.result.StatsResult; +import org.springframework.data.solr.core.query.result.SuggestDictionaryEntry; import org.springframework.data.solr.core.query.result.TermsFieldEntry; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -91,20 +92,21 @@ final class ResultHelper { private ResultHelper() {} - static Map> convertSuggesterQueryResponseToSuggesterMap(QueryResponse response) { + static Map> convertSuggesterQueryResponseToSuggesterMap(QueryResponse response) { if (response == null || response.getSuggesterResponse() == null || response.getSuggesterResponse().getSuggestions() == null) { return Collections.emptyMap(); } SuggesterResponse suggesterResponse = response.getSuggesterResponse(); - Map> result = new LinkedHashMap>( + Map> result = new LinkedHashMap>( suggesterResponse.getSuggestions().size()); for (Map.Entry> entry : suggesterResponse.getSuggestions().entrySet()) { - List terms = new ArrayList(entry.getValue().size()); + List terms = new ArrayList(entry.getValue().size()); for (Suggestion term : entry.getValue()) { - SimpleSuggestDictionaryEntry suggestionEntry = new SimpleSuggestDictionaryEntry(term.getTerm(), term.getWeight(),term.getPayload()); - suggestionEntry.setDictionaryName(entry.getKey()); + SimpleSuggestDictionaryEntry suggestionEntry = new SimpleSuggestDictionaryEntry(term.getTerm(), term.getWeight()); + suggestionEntry.setDictionary(entry.getKey()); + suggestionEntry.setPayLoad(term.getPayload()); terms.add(suggestionEntry); } result.put(entry.getKey(), terms); diff --git a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java index 4bd45eb..7a23490 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java @@ -77,6 +77,8 @@ import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; import org.springframework.data.solr.core.query.result.StatsPage; +import org.springframework.data.solr.core.query.result.SuggestPage; +import org.springframework.data.solr.core.query.result.SuggesterResultPage; import org.springframework.data.solr.core.query.result.TermsPage; import org.springframework.data.solr.core.query.result.TermsResultPage; import org.springframework.data.solr.core.schema.DefaultSchemaOperations; @@ -995,29 +997,29 @@ public TermsPage queryForTermsPage(String collectionName, TermsQuery query, Requ } @Override - public Object queryForSuggesterPage(SuggestQuery query) { + public SuggestPage queryForSuggesterPage(SuggestQuery query) { return queryForSuggesterPage(query, getDefaultRequestMethod()); } @Override - public Object queryForSuggesterPage(String collectionName, SuggestQuery query) { + public SuggestPage queryForSuggesterPage(String collectionName, SuggestQuery query) { return queryForSuggesterPage(collectionName, query, getDefaultRequestMethod()); } @Override - public Object queryForSuggesterPage(SuggestQuery query, RequestMethod method) { + public SuggestPage queryForSuggesterPage(SuggestQuery query, RequestMethod method) { return queryForSuggesterPage(null, query, method); } - public Object queryForSuggesterPage(String collectionName, SuggestQuery query, RequestMethod method) { + public SuggestPage queryForSuggesterPage(String collectionName, SuggestQuery query, RequestMethod method) { Assert.notNull(query, "Query must not be 'null'."); QueryResponse response = querySolr(collectionName, query, null, method); -// TermsResultPage page = new TermsResultPage(); -// page.addAllTerms(ResultHelper.convertTermsQueryResponseToTermsMap(response)); - return ResultHelper.convertSuggesterQueryResponseToSuggesterMap(response); + SuggesterResultPage page = new SuggesterResultPage(); + page.addAllSuggestions(ResultHelper.convertSuggesterQueryResponseToSuggesterMap(response)); + return page; } final QueryResponse querySolr(String collectionName, SolrDataQuery query, Class clazz) { diff --git a/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java index 30827ee..00e4f1f 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/DictionarySuggestEntry.java @@ -4,24 +4,24 @@ * @author navneetgupta * @createdOn Dec 5, 2017 */ -public class DictionarySuggestEntry extends SuggestEntry { +public class DictionarySuggestEntry {// extends SuggestEntry { - private String dictionaryName; - - public DictionarySuggestEntry(String term, long weight, String payload) { - super(term, weight, payload); - } - - public DictionarySuggestEntry(String term, long weight, String payload, String dictionaryName) { - super(term, weight, payload); - this.dictionaryName = dictionaryName; - } - - public String getDictionaryName() { - return dictionaryName; - } - - public void setDictionaryName(String dictionaryName) { - this.dictionaryName = dictionaryName; - } +// private String dictionaryName; +// +// public DictionarySuggestEntry(String term, long weight, String payload) { +// super(term, weight, payload); +// } +// +// public DictionarySuggestEntry(String term, long weight, String payload, String dictionaryName) { +// super(term, weight, payload); +// this.dictionaryName = dictionaryName; +// } +// +// public String getDictionaryName() { +// return dictionaryName; +// } +// +// public void setDictionaryName(String dictionaryName) { +// this.dictionaryName = dictionaryName; +// } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/DictionaryWeightTermEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/DictionaryWeightTermEntry.java new file mode 100644 index 0000000..e798325 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/DictionaryWeightTermEntry.java @@ -0,0 +1,30 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class DictionaryWeightTermEntry extends WeightTermEntry { + + private String dictionary; + private String payLoad; + + public DictionaryWeightTermEntry(String term, long weight) { + super(term, weight); + } + + public String getDictionary() { + return dictionary; + } + + public void setDictionary(String dictionary) { + this.dictionary = dictionary; + } + public void setPayLoad(String payLoad) { + this.payLoad=payLoad; + } + + public String getPayLoad() { + return this.payLoad; + } +} \ No newline at end of file diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java index 1334b23..7afcdc7 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SimpleSuggestDictionaryEntry.java @@ -4,24 +4,23 @@ * @author navneetgupta * @createdOn Dec 5, 2017 */ -public class SimpleSuggestDictionaryEntry extends DictionarySuggestEntry { +public class SimpleSuggestDictionaryEntry extends DictionaryWeightTermEntry implements SuggestDictionaryEntry { /** * @param term * @param weight - * @param payload */ - public SimpleSuggestDictionaryEntry(String term, long weight, String payload) { - super(term, weight, payload); + public SimpleSuggestDictionaryEntry(String term, long weight) { + super(term, weight); } - + /** * @param term * @param weight - * @param payload + * @param dictionary */ - public SimpleSuggestDictionaryEntry(String dictionaryName, String term, long weight, String payload) { - super(term, weight, payload); - setDictionaryName(dictionaryName); + public SimpleSuggestDictionaryEntry(String term, long weight,String dictionary) { + super(term, weight); + setDictionary(dictionary); } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggestDictionaryEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggestDictionaryEntry.java new file mode 100644 index 0000000..626b752 --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggestDictionaryEntry.java @@ -0,0 +1,12 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public interface SuggestDictionaryEntry extends SuggestEntry { + String getDictionary(); + + @Override + String getPayLoad(); +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java index 9b75772..9d5bd56 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggestEntry.java @@ -4,27 +4,6 @@ * @author navneetgupta * @createdOn Dec 5, 2017 */ -public class SuggestEntry { - private final String term; - private final long weight; - private final String payload; - - public SuggestEntry(String term, long weight, String payload) { - super(); - this.term = term; - this.weight = weight; - this.payload = payload; - } - - public String getTerm() { - return term; - } - - public long getWeight() { - return weight; - } - - public String getPayload() { - return payload; - } +public interface SuggestEntry extends WeightEntry { + String getPayLoad(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java index d5dca05..44c0a6b 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggestPage.java @@ -1,9 +1,32 @@ package org.springframework.data.solr.core.query.result; +import java.util.List; + +import org.springframework.data.domain.Page; + /** * @author navneetgupta * @createdOn Dec 5, 2017 */ -public interface SuggestPage { +public interface SuggestPage extends Iterable { + /** + * Returns the page content as {@link List}. + * + * @return + */ + Iterable getContent(); + + /** + * + * @param fieldname + * @return + */ + Iterable getSuggestionForDictionary(String dictionary); + /** + * Returns whether the {@link Page} has content at all. + * + * @return + */ + boolean hasContent(); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java index 38d6ce1..44cd417 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SuggesterResultPage.java @@ -1,9 +1,77 @@ package org.springframework.data.solr.core.query.result; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.util.Assert; + /** * @author navneetgupta * @createdOn Dec 5, 2017 */ -public class SuggesterResultPage { +public class SuggesterResultPage implements SuggestPage { + + private Map> termsMap = new LinkedHashMap>( + 1); + + public final void addSuggestResult(List entries, String dictionary) { + Assert.notNull(dictionary, "Cannot add terms for 'null' field."); + this.termsMap.put(new StringPageKey(dictionary), entries); + } + + public void addAllSuggestions(Map> pageMap) { + for (Map.Entry> entry : pageMap.entrySet()) { + addSuggestResult(entry.getValue(), entry.getKey()); + } + } + + @Override + public Iterator iterator() { + return getContent().iterator(); + } + + @Override + public Iterable getContent() { + List values = new ArrayList(); + for (List entries : termsMap.values()) { + values.addAll(entries); + } + return values; + } + + @Override + public Iterable getSuggestionForDictionary(String dictionary) { + Iterable terms = this.termsMap.get(new StringPageKey(dictionary)); + return terms != null ? terms : Collections. emptyList(); + } + + public Iterable getTerms(String dictionary) { + Assert.notNull(dictionary, "Field cannot be null."); + return getSuggestionForDictionary(dictionary); + } + + + public Collection getSuggesterDictionaries() { + if (this.termsMap.isEmpty()) { + return Collections.emptyList(); + } + + List dictionaires = new ArrayList(this.termsMap.size()); + for (StringPageKey pageKey : this.termsMap.keySet()) { + dictionaires.add(pageKey.getKey()); + } + return dictionaires; + } + + + @Override + public boolean hasContent() { + return !termsMap.isEmpty(); + } } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/WeightEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/WeightEntry.java new file mode 100644 index 0000000..2c3bb9c --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/WeightEntry.java @@ -0,0 +1,11 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public interface WeightEntry { + + long getWeight(); + String getTerm(); +} diff --git a/src/main/java/org/springframework/data/solr/core/query/result/WeightTermEntry.java b/src/main/java/org/springframework/data/solr/core/query/result/WeightTermEntry.java new file mode 100644 index 0000000..47d4b9a --- /dev/null +++ b/src/main/java/org/springframework/data/solr/core/query/result/WeightTermEntry.java @@ -0,0 +1,27 @@ +package org.springframework.data.solr.core.query.result; + +/** + * @author navneetgupta + * @createdOn Dec 5, 2017 + */ +public class WeightTermEntry implements WeightEntry { + + private final String term; + private final long weight; + + public WeightTermEntry(String term, long weight) { + this.term = term; + this.weight = weight; + } + + @Override + public long getWeight() { + return this.weight; + } + + @Override + public String getTerm() { + return this.term; + } + +} From 4fafe8b93331e2599a962860dcf4a9f75e35eb9a Mon Sep 17 00:00:00 2001 From: Navneet Gupta Date: Sun, 10 Dec 2017 13:32:27 +0400 Subject: [PATCH 10/10] Added Support for 1. Custom HttpSolrClient for adding Authentication paramater. 2. SpellCheck Collation adding 3. SpellCheck Optioin changes --- .../data/solr/core/ResultHelper.java | 25 ++++++++++++++++++- .../data/solr/core/SolrTemplate.java | 5 +++- .../core/query/result/SolrResultPage.java | 14 +++++++++++ .../query/result/SpellcheckQueryResult.java | 16 ++++++++++++ .../support/SimpleSolrRepository.java | 2 +- .../solr/server/support/SolrClientUtils.java | 2 ++ 6 files changed, 61 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/springframework/data/solr/core/ResultHelper.java b/src/main/java/org/springframework/data/solr/core/ResultHelper.java index c64c282..d9b33b1 100644 --- a/src/main/java/org/springframework/data/solr/core/ResultHelper.java +++ b/src/main/java/org/springframework/data/solr/core/ResultHelper.java @@ -72,6 +72,7 @@ import org.springframework.data.solr.core.query.result.SimpleTermsFieldEntry; import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; +import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Collations; import org.springframework.data.solr.core.query.result.StatsResult; import org.springframework.data.solr.core.query.result.SuggestDictionaryEntry; import org.springframework.data.solr.core.query.result.TermsFieldEntry; @@ -473,8 +474,9 @@ static Map> extreactSuggestions(QueryResponse response if (!CollectionUtils.isEmpty(suggestion.getAlternatives())) { for (int i = 0; i < suggestion.getAlternatives().size(); i++) { + List freq = suggestion.getAlternativeFrequencies(); alternatives.add(new Alternative(suggestion.getToken(), suggestion.getOriginalFrequency(), - suggestion.getAlternatives().get(i), suggestion.getAlternativeFrequencies().get(i))); + suggestion.getAlternatives().get(i), (freq != null) ? suggestion.getAlternativeFrequencies().get(i):Integer.valueOf(1))); } } alternativesMap.put(suggestion.getToken(), alternatives); @@ -484,4 +486,25 @@ static Map> extreactSuggestions(QueryResponse response return alternativesMap; } + + /** + * @param response + * @return + */ + static List extreactCollations(QueryResponse response) { + if (response == null || response.getSpellCheckResponse() == null + || response.getSpellCheckResponse().getSuggestions() == null) { + return Collections.emptyList(); + } + List collations = new ArrayList(); + SpellCheckResponse scr = response.getSpellCheckResponse(); + if (scr != null && scr.getCollatedResults() != null) { + for (SpellCheckResponse.Collation collation : scr.getCollatedResults()) { + + collations.add(new Collations(collation.getCollationQueryString(),collation.getNumberOfHits())); + } + } + return collations; + } + } diff --git a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java index 7a23490..a30b4af 100644 --- a/src/main/java/org/springframework/data/solr/core/SolrTemplate.java +++ b/src/main/java/org/springframework/data/solr/core/SolrTemplate.java @@ -76,6 +76,7 @@ import org.springframework.data.solr.core.query.result.ScoredPage; import org.springframework.data.solr.core.query.result.SolrResultPage; import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Alternative; +import org.springframework.data.solr.core.query.result.SpellcheckQueryResult.Collations; import org.springframework.data.solr.core.query.result.StatsPage; import org.springframework.data.solr.core.query.result.SuggestPage; import org.springframework.data.solr.core.query.result.SuggesterResultPage; @@ -950,6 +951,8 @@ private SolrResultPage createSolrResultPage(Query query, Class clazz, for (Entry> entry : suggestions.entrySet()) { page.addSuggestions(entry.getKey(), entry.getValue()); } + List collations = ResultHelper.extreactCollations(response); + page.addCollations(collations); } return page; @@ -1047,7 +1050,7 @@ final QueryResponse querySolr(String collectionName, SolrDataQuery query, Class< } } - LOGGER.debug("Executing query '" + solrQuery + "' against solr."); + LOGGER.info("Executing query '" + solrQuery + "' against solr."); return executeSolrQuery(collectionName, solrQuery, getSolrRequestMethod(requestMethod)); } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java b/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java index f1cc4d0..35279d5 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SolrResultPage.java @@ -58,6 +58,7 @@ public class SolrResultPage extends PageImpl implements FacetPage, High private Map> groupResults = Collections.emptyMap(); private Map fieldStatsResults; private Map> suggestions = new LinkedHashMap>(); + private List collations; public SolrResultPage(List content) { super(content); @@ -322,6 +323,11 @@ public void addSuggestions(String term, List suggestions) { this.suggestions.put(term, suggestions); } + @Override + public void addCollations(List collations) { + this.collations = collations; + } + /* * (non-Javadoc) * @see org.springframework.data.solr.core.query.result.SpellcheckQueryResult#getAlternatives() @@ -346,4 +352,12 @@ public Collection getAlternatives(String term) { : Collections. emptyList(); } + /* (non-Javadoc) + * @see org.springframework.data.solr.core.query.result.SpellcheckQueryResult#getCollations() + */ + @Override + public Collection getCollations() { + return collations; + } + } diff --git a/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java b/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java index 3efb9d0..875d8b4 100644 --- a/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java +++ b/src/main/java/org/springframework/data/solr/core/query/result/SpellcheckQueryResult.java @@ -32,6 +32,13 @@ public interface SpellcheckQueryResult { * @return never {@literal null}. */ Collection getAlternatives(); + + /** + * Get all {@link Alternative}s; + * + * @return never {@literal null}. + */ + Collection getCollations(); /** * Get the {@link Alternative}s for a given term. @@ -57,6 +64,8 @@ public interface SpellcheckQueryResult { Collection getSuggestions(String term); void addSuggestions(String term, List suggestions); + + void addCollations(List collations); /** * @author Christoph Strobl @@ -70,4 +79,11 @@ public static class Alternative { private final String suggestion; private final int suggestionFrequency; } + + @Data + public static class Collations { + + private final String query; + private final long hits; + } } diff --git a/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java b/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java index 8ae2c0d..015621a 100644 --- a/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java +++ b/src/main/java/org/springframework/data/solr/repository/support/SimpleSolrRepository.java @@ -146,7 +146,7 @@ protected long count(org.springframework.data.solr.core.query.Query query) { public S save(S entity) { Assert.notNull(entity, "Cannot save 'null' entity."); registerTransactionSynchronisationIfSynchronisationActive(); - this.solrOperations.saveBean(entity); + getSolrOperations().saveBean(entity); commitIfTransactionSynchronisationIsInactive(); return entity; } diff --git a/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java b/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java index c627710..0060222 100644 --- a/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java +++ b/src/main/java/org/springframework/data/solr/server/support/SolrClientUtils.java @@ -105,6 +105,8 @@ public static T clone(T solrClient, String core) { clone = cloneCloudSolrClient(solrClient, core); } else if (shortName.equals("EmbeddedSolrServer")) { clone = cloneEmbeddedSolrServer(solrClient, core); + } else if(shortName.equals("MyHttpSolrClient")) { + clone = cloneHttpSolrClient(solrClient, core); } if (clone == null) {